chaining of callbacks

This commit is contained in:
Wolfgang Hottgenroth
2017-07-29 00:26:29 +02:00
parent ac5566a402
commit 1aa7765079
4 changed files with 58 additions and 19 deletions

6
dist/main.js vendored
View File

@ -5,13 +5,13 @@ const mqtt = require("./mqttclient");
class Dispatcher {
constructor() {
this._mqttClient = new mqtt.MqttClient();
this._mqttClient.register('IoT/test', (message) => {
this._mqttClient.register('IoT/test', 'print', (message) => {
log.info("Callback for IoT/test");
log.info(`message is ${message}`);
return `<<${message}>>`;
});
this._mqttClient.register('IoT/Device/#', mqtt.passThrough);
this._mqttClient.register('IoT/Device/#', mqtt.passThrough);
this._mqttClient.register('IoT/Device/#', 'null1', mqtt.passThrough);
this._mqttClient.register('IoT/Device/#', 'null2', mqtt.passThrough);
}
exec() {
log.info("Dispatcher starting");

30
dist/mqttclient.js vendored
View File

@ -3,6 +3,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
const Mqtt = require("mqtt");
const log = require("./log");
const MQTT_BROKER_DEFAULT_URL = "mqtt://localhost";
class TopicHandlerCallback {
constructor(label, func) {
this._label = label;
this._func = func;
}
get func() {
return this._func;
}
toString() {
let funcName = (this._func.name === "") ? "lambda" : this._func.name;
return `<${funcName}, ${this._label}>`;
}
}
function passThrough(message) {
return message;
}
@ -12,20 +25,19 @@ class MqttClient {
this._mqttBrokerUrl = (mqttBrokerUrl) ? mqttBrokerUrl : MQTT_BROKER_DEFAULT_URL;
this._topicHandlers = [];
}
register(topic, callback) {
register(topic, label, callbackFunc) {
let done = false;
let callbackName = (callback.name === "") ? "lambda" : callback.name;
let callback = new TopicHandlerCallback(label, callbackFunc);
for (let topicHandler of this._topicHandlers) {
if (topicHandler.topic === topic) {
topicHandler.callbacks.push(callback);
done = true;
log.info(`additional callback <${callbackName}> added for topic ${topic}`);
log.info(`additional callback ${callback.toString()} added for topic ${topic}`);
}
}
if (!done) {
let cbs = [callback];
this._topicHandlers.push({ topic: topic, callbacks: cbs });
log.info(`first callback <${callbackName}> added for topic ${topic}`);
this._topicHandlers.push({ topic: topic, callbacks: [callback] });
log.info(`first callback ${callback.toString()} added for topic ${topic}`);
}
}
exec() {
@ -43,6 +55,12 @@ class MqttClient {
if (this.topicMatch(topicHandler.topic, topic)) {
log.info(`received topic ${topic} matches registered topic ${topicHandler.topic}`);
// topicHandler.callback(payload)
let returnValue = payload;
for (let topicHandlerCallback of topicHandler.callbacks) {
log.info(`Calling ${topicHandlerCallback}`);
returnValue = topicHandlerCallback.func(returnValue);
}
log.info(`Final return value is ${returnValue}`);
}
}
});