Commit 53f1faa2 authored by Vladimir Kiryakov's avatar Vladimir Kiryakov
Browse files

mqtt reconnect after page reload

parent 5fd911a0
......@@ -20,43 +20,55 @@ const mqttMiddleware = (function () {
messages = [];
}
}, 1000);
return next => (action) => {
switch (action.type) {
case MQTT_CONNECT:
if (client != null) {
client.end();
}
setTimeout(() => {
url = action.payload.url;
topic = action.payload.topic;
reconnectPeriod = action.payload.reconnectPeriod;
try {
client = mqtt.connect(url, {reconnectPeriod});
client.on('connect', () => {
if (config.debug) console.log('MQTT: client connected');
store.dispatch(connected());
client.subscribe(topic);
});
client.on('close', () => {
if (config.debug) console.log('MQTT: client disconnected');
client.end();
store.dispatch(disconnected());
});
client.on('message', (msgTopic, msg) => {
const message = msg.toString();
if (config.debug) console.info('MQTT: Message recieved.\nTopic: %s\nPayload: %s', topic, message);
if (_.isEqual(topic, msgTopic)) {
messages.push({topic, message: message, timestamp: new Date().getTime()});
}
});
} catch (e) {
store.dispatch(disconnected());
const subscribe = (newUrl, newTopic, newReconnectPeriod) => {
if (client != null) {
client.end();
client = null;
}
setTimeout(() => {
url = newUrl;
topic = newTopic;
reconnectPeriod = newReconnectPeriod;
try {
client = mqtt.connect(url, {reconnectPeriod});
client.on('connect', () => {
if (config.debug) console.log('MQTT: client connected');
store.dispatch(connected());
client.subscribe(topic);
});
client.on('close', () => {
if (config.debug) console.log('MQTT: client disconnected');
client.end();
store.dispatch(disconnected());
});
client.on('message', (msgTopic, msg) => {
const message = msg.toString();
if (config.debug) console.info('MQTT: Message recieved.\nTopic: %s\nPayload: %s', topic, message);
if (_.isEqual(topic, msgTopic)) {
messages.push({topic, message: message, timestamp: new Date().getTime()});
}
return next(action);
}, 100);
});
} catch (e) {
store.dispatch(disconnected());
}
}, 100);
};
const isConnected = _.get(store.getState(), 'mqtt.isConnected');
const clientIsNull = client == null;
break;
if (isConnected && clientIsNull) {
const formValues = _.get(store.getState(), 'form.mqtt.values');
subscribe(formValues.url, formValues.topic);
}
return next => (action) => {
switch (action.type) {
case MQTT_CONNECT:
subscribe(action.payload.url, action.payload.topic, action.payload.reconnectPeriod);
return next(action);
default:
return next(action);
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment