Skip to content

Commit 9784b7d

Browse files
committed
Re-subscribe to all topics subscribed previously after a connection loss
1 parent fab5a27 commit 9784b7d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/index.js

+27
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import CBOR from 'cbor-js';
4949
import ArduinoCloudError from './ArduinoCloudError';
5050

5151
const connections = {};
52+
const subscribedTopics = {};
5253
const propertyCallback = {};
5354
const arduinoCloudPort = 8443;
5455
const arduinoCloudHost = 'wss.iot.arduino.cc';
@@ -78,6 +79,7 @@ const connect = options => new Promise((resolve, reject) => {
7879
token: options.token,
7980
onDisconnect: options.onDisconnect,
8081
onTrace: options.onTrace,
82+
onConnected: options.onConnected,
8183
};
8284

8385
if (!opts.host) {
@@ -134,6 +136,22 @@ const connect = options => new Promise((resolve, reject) => {
134136
}
135137
};
136138

139+
client.onConnected = (reconnect) => {
140+
if (reconnect === true) {
141+
// This is a re-connection: re-subscribe to all topics subscribed before the
142+
// connection loss
143+
Object.getOwnPropertySymbols(subscribedTopics).forEach((connectionId) => {
144+
Object.values(subscribedTopics[connectionId]).forEach((subscribeParams) => {
145+
subscribe(connectionId, subscribeParams.topic, subscribeParams.cb)
146+
});
147+
});
148+
}
149+
150+
if (typeof opts.onConnected === 'function') {
151+
opts.onConnected(reconnect)
152+
}
153+
};
154+
137155
if (typeof onDisconnect === 'function') {
138156
client.onConnectionLost = opts.onDisconnect;
139157
}
@@ -346,6 +364,15 @@ const onPropertyValue = (connectionId, thingId, name, cb) => {
346364
}
347365
const propOutputTopic = `/a/t/${thingId}/e/o`;
348366

367+
if (!subscribedTopics[connectionId]) {
368+
subscribedTopics[connectionId] = {};
369+
}
370+
371+
subscribedTopics[connectionId][thingId] = {
372+
topic: propOutputTopic,
373+
cb: cb,
374+
};
375+
349376
if (!propertyCallback[propOutputTopic]) {
350377
propertyCallback[propOutputTopic] = {};
351378
propertyCallback[propOutputTopic][name] = cb;

0 commit comments

Comments
 (0)