Skip to content

Re-subscribe to all topics subscribed previously after a connection loss #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 14, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import CBOR from 'cbor-js';
import ArduinoCloudError from './ArduinoCloudError';

const connections = {};
const subscribedTopics = {};
const propertyCallback = {};
const arduinoCloudPort = 8443;
const arduinoCloudHost = 'wss.iot.arduino.cc';
Expand Down Expand Up @@ -78,6 +79,7 @@ const connect = options => new Promise((resolve, reject) => {
token: options.token,
onDisconnect: options.onDisconnect,
onTrace: options.onTrace,
onConnected: options.onConnected,
};

if (!opts.host) {
Expand Down Expand Up @@ -134,6 +136,22 @@ const connect = options => new Promise((resolve, reject) => {
}
};

client.onConnected = (reconnect) => {
if (reconnect === true) {
// This is a re-connection: re-subscribe to all topics subscribed before the
// connection loss
Object.getOwnPropertySymbols(subscribedTopics).forEach((connectionId) => {
Object.values(subscribedTopics[connectionId]).forEach((subscribeParams) => {
subscribe(connectionId, subscribeParams.topic, subscribeParams.cb)
});
});
}

if (typeof opts.onConnected === 'function') {
opts.onConnected(reconnect)
}
};

if (typeof onDisconnect === 'function') {
client.onConnectionLost = opts.onDisconnect;
}
Expand Down Expand Up @@ -346,6 +364,15 @@ const onPropertyValue = (connectionId, thingId, name, cb) => {
}
const propOutputTopic = `/a/t/${thingId}/e/o`;

if (!subscribedTopics[connectionId]) {
subscribedTopics[connectionId] = {};
}

subscribedTopics[connectionId][thingId] = {
topic: propOutputTopic,
cb: cb,
};

if (!propertyCallback[propOutputTopic]) {
propertyCallback[propOutputTopic] = {};
propertyCallback[propOutputTopic][name] = cb;
Expand Down