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

@@ -18,24 +18,34 @@ RED.comms = function() {
var errornotification = null;
var subscriptions = {};
var ws;
function connectWS() {
var path = location.hostname+":"+location.port+document.location.pathname;
path = path+(path.slice(-1) == "/"?"":"/")+"comms";
path = "ws"+(document.location.protocol=="https:"?"s":"")+"://"+path;
var ws = new WebSocket(path);
ws = new WebSocket(path);
ws.onopen = function() {
if (errornotification) {
errornotification.close();
errornotification = null;
}
for (var t in subscriptions) {
ws.send(JSON.stringify({subscribe:t}));
}
}
ws.onmessage = function(event) {
var msg = JSON.parse(event.data);
var subscribers = subscriptions[msg.topic];
if (subscribers) {
for (var i=0;i<subscribers.length;i++) {
subscribers[i](msg.topic,msg.data);
if (msg.topic) {
for (var t in subscriptions) {
var re = new RegExp("^"+t.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g,"\\$1").replace(/\+/g,"[^/]+").replace(/\/#$/,"(\/.*)?")+"$");
if (re.test(msg.topic)) {
var subscribers = subscriptions[t];
if (subscribers) {
for (var i=0;i<subscribers.length;i++) {
subscribers[i](msg.topic,msg.data);
}
}
}
}
}
};
@@ -46,16 +56,20 @@ RED.comms = function() {
setTimeout(connectWS,1000);
}
}
connectWS();
function subscribe(topic,callback) {
if (subscriptions[topic] == null) {
subscriptions[topic] = [];
}
subscriptions[topic].push(callback);
if (ws && ws.readyState == 1) {
ws.send(JSON.stringify({subscribe:topic}));
}
}
return {
connect: connectWS,
subscribe: subscribe
}
}();