callchains implemented

This commit is contained in:
Wolfgang Hottgenroth
2017-08-09 00:03:57 +02:00
parent 1aa7765079
commit ca1dea597c
7 changed files with 278 additions and 67 deletions

45
dist/mqttclient.js vendored
View File

@ -2,20 +2,8 @@
Object.defineProperty(exports, "__esModule", { value: true });
const Mqtt = require("mqtt");
const log = require("./log");
const callchain = require("./callchain");
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;
}
@ -25,22 +13,33 @@ class MqttClient {
this._mqttBrokerUrl = (mqttBrokerUrl) ? mqttBrokerUrl : MQTT_BROKER_DEFAULT_URL;
this._topicHandlers = [];
}
register(topic, label, callbackFunc) {
registerCallbackFunc(topic, label, callbackFunc) {
let newChainItem = new callchain.ChainItem(label);
newChainItem.registerFunc(callbackFunc);
this.registerCallbackClass(topic, label, newChainItem);
}
registerCallbackClass(topic, label, newChainItem) {
let done = false;
let callback = new TopicHandlerCallback(label, callbackFunc);
for (let topicHandler of this._topicHandlers) {
if (topicHandler.topic === topic) {
topicHandler.callbacks.push(callback);
topicHandler.last.registerNext(newChainItem);
topicHandler.last = newChainItem;
done = true;
log.info(`additional callback ${callback.toString()} added for topic ${topic}`);
log.info(`additional callback ${newChainItem.toString()} added for topic ${topic}`);
}
}
if (!done) {
this._topicHandlers.push({ topic: topic, callbacks: [callback] });
log.info(`first callback ${callback.toString()} added for topic ${topic}`);
this._topicHandlers.push({ topic: topic, root: newChainItem, last: newChainItem });
log.info(`first callback ${newChainItem.toString()} added for topic ${topic}`);
}
}
test() {
this._mqttClient.emit("message", 'IoT/test', 'payload');
}
exec() {
for (let topicHandler of this._topicHandlers) {
topicHandler.root.begin();
}
this._mqttClient = Mqtt.connect(this._mqttBrokerUrl);
this._mqttClient.on('error', log.error);
this._mqttClient.on('connect', () => {
@ -54,13 +53,7 @@ class MqttClient {
for (let topicHandler of this._topicHandlers) {
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}`);
topicHandler.root.send(payload);
}
}
});