2 * Copyright 2014 IBM Corp.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 RED.comms = (function() {
19 var errornotification = null;
20 var subscriptions = {};
22 function connectWS() {
23 var path = location.hostname+":"+location.port+document.location.pathname;
24 path = path+(path.slice(-1) == "/"?"":"/")+"comms";
25 path = "ws"+(document.location.protocol=="https:"?"s":"")+"://"+path;
26 ws = new WebSocket(path);
27 ws.onopen = function() {
28 if (errornotification) {
29 errornotification.close();
30 errornotification = null;
32 for (var t in subscriptions) {
33 if (subscriptions.hasOwnProperty(t)) {
34 ws.send(JSON.stringify({subscribe:t}));
38 ws.onmessage = function(event) {
39 var msg = JSON.parse(event.data);
41 for (var t in subscriptions) {
42 if (subscriptions.hasOwnProperty(t)) {
43 var re = new RegExp("^"+t.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g,"\\$1").replace(/\+/g,"[^/]+").replace(/\/#$/,"(\/.*)?")+"$");
44 if (re.test(msg.topic)) {
45 var subscribers = subscriptions[t];
47 for (var i=0;i<subscribers.length;i++) {
48 subscribers[i](msg.topic,msg.data);
56 ws.onclose = function() {
57 if (errornotification == null) {
58 errornotification = RED.notify("<b>Error</b>: Lost connection to server","error",true);
60 setTimeout(connectWS,1000);
64 function subscribe(topic,callback) {
65 if (subscriptions[topic] == null) {
66 subscriptions[topic] = [];
68 subscriptions[topic].push(callback);
69 if (ws && ws.readyState == 1) {
70 ws.send(JSON.stringify({subscribe:topic}));
74 function unsubscribe(topic,callback) {
75 if (subscriptions.topic) {
76 for (var i=0;i<subscriptions.topic.length;i++) {
77 if (subscriptions.topic[i] === callback) {
78 subscriptions.topic.splice(i,1);
82 if (subscriptions.topic.length === 0) {
83 delete subscriptions.topic;
91 unsubscribe:unsubscribe