Add node status updates

This commit is contained in:
Nick O'Leary
2014-05-08 14:15:54 +01:00
parent 8e7fc011f0
commit 7ecb80bf40
7 changed files with 145 additions and 42 deletions

View File

@@ -23,6 +23,8 @@ var settings;
var wsServer;
var activeConnections = [];
var retained = {};
var heartbeatTimer;
var lastSentTime;
@@ -47,6 +49,12 @@ function start() {
}
}
});
ws.on('message', function(data,flags) {
var msg = JSON.parse(data);
if (msg.subscribe) {
handleRemoteSubscription(ws,msg.subscribe);
}
});
ws.on('error', function(err) {
util.log("[red:comms] error : "+err.toString());
});
@@ -67,17 +75,34 @@ function start() {
}, 15000);
}
function publish(topic,data) {
var msg = JSON.stringify({topic:topic,data:data});
function publish(topic,data,retain) {
if (retain) {
retained[topic] = data;
}
lastSentTime = Date.now();
activeConnections.forEach(function(conn) {
try {
conn.send(msg);
} catch(err) {
util.log("[red:comms] send error : "+err.toString());
}
publishTo(conn,topic,data);
});
}
function publishTo(ws,topic,data) {
var msg = JSON.stringify({topic:topic,data:data});
try {
ws.send(msg);
} catch(err) {
util.log("[red:comms] send error : "+err.toString());
}
}
function handleRemoteSubscription(ws,topic) {
var re = new RegExp("^"+topic.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g,"\\$1").replace(/\+/g,"[^/]+").replace(/\/#$/,"(\/.*)?")+"$");
for (var t in retained) {
if (re.test(t)) {
publishTo(ws,t,retained[t]);
}
}
}
module.exports = {
init:init,

View File

@@ -20,7 +20,7 @@ var clone = require("clone");
var flows = require("./flows");
var comms = require("../comms");
function Node(n) {
this.id = n.id;
@@ -114,6 +114,11 @@ Node.prototype.error = function(msg) {
if (this.name) o.name = this.name;
this.emit("log",o);
}
/**
* status: { fill:"red|green", shape:"dot|ring", text:"blah" }
*/
Node.prototype.status = function(status,retain) {
comms.publish("status/"+this.id,status,retain);
}
module.exports = Node;

View File

@@ -18,7 +18,6 @@ var events = require("./events");
var server = require("./server");
var nodes = require("./nodes");
var library = require("./library");
var comms = require("./comms");
var log = require("./log");
var fs = require("fs");
var settings = null;
@@ -51,7 +50,6 @@ var RED = {
stop: server.stop,
nodes: nodes,
library: library,
comms: comms,
events: events,
log: log
};