Skip to content

Instantly share code, notes, and snippets.

@mamuesp
Created March 13, 2019 12:31
Show Gist options
  • Save mamuesp/a2c35a842e253cfc1ab649a4e2ab6ec3 to your computer and use it in GitHub Desktop.
Save mamuesp/a2c35a842e253cfc1ab649a4e2ab6ec3 to your computer and use it in GitHub Desktop.
Idea for a queued MQTT publishing in MJS
// sketch to publish MQTT message with queue, if MQTT is not connected
// when connected, on every try to pubslish a message, eventually queued
// messages will be published fist
let mqtt_test = {
_queue: [], // a simple filo queue by array
_mqttConected: false, // will be set in other function by event
publishMsgQueued: function (topic, payload) {
if (this.handleQueue(topic, payload)) {
this.publishMsg(topic, payload);
}
},
publishMsg: function (topic, payload) {
// add your publishing code here ...
},
handleQueue: function (topic, payload) {
let result = true;
if (this._mqttConected === false) {
this._queue.push(JSON.parse('{ "payload": "' + payload + '", "topic": "' + topic + '"}'));
Log.error('Error publishing, trying again later ...');
result = false;
} else if (this._queue.length > 0) {
// if there is a queue, process these entries first
let pubObj = this._queue.shift();
while (pubObj !== null) {
Log.debug('Processing queue entry ...');
this.publishMsg(pubObj.topic, pubObj.payload);
pubObj = this._queue.shift();
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment