You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.8KB

  1. /**
  2. * Copyright 2014 IBM Corp.
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. **/
  16. RED.comms = (function() {
  17. var errornotification = null;
  18. var subscriptions = {};
  19. var ws;
  20. function connectWS() {
  21. var path = location.hostname+":"+location.port+document.location.pathname;
  22. path = path+(path.slice(-1) == "/"?"":"/")+"comms";
  23. path = "ws"+(document.location.protocol=="https:"?"s":"")+"://"+path;
  24. ws = new WebSocket(path);
  25. ws.onopen = function() {
  26. if (errornotification) {
  27. errornotification.close();
  28. errornotification = null;
  29. }
  30. for (var t in subscriptions) {
  31. if (subscriptions.hasOwnProperty(t)) {
  32. ws.send(JSON.stringify({subscribe:t}));
  33. }
  34. }
  35. }
  36. ws.onmessage = function(event) {
  37. var msg = JSON.parse(event.data);
  38. if (msg.topic) {
  39. for (var t in subscriptions) {
  40. if (subscriptions.hasOwnProperty(t)) {
  41. var re = new RegExp("^"+t.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g,"\\$1").replace(/\+/g,"[^/]+").replace(/\/#$/,"(\/.*)?")+"$");
  42. if (re.test(msg.topic)) {
  43. var subscribers = subscriptions[t];
  44. if (subscribers) {
  45. for (var i=0;i<subscribers.length;i++) {
  46. subscribers[i](msg.topic,msg.data);
  47. }
  48. }
  49. }
  50. }
  51. }
  52. }
  53. };
  54. ws.onclose = function() {
  55. if (errornotification == null) {
  56. errornotification = RED.notify("<b>Error</b>: Lost connection to server","error",true);
  57. }
  58. setTimeout(connectWS,1000);
  59. }
  60. }
  61. function subscribe(topic,callback) {
  62. if (subscriptions[topic] == null) {
  63. subscriptions[topic] = [];
  64. }
  65. subscriptions[topic].push(callback);
  66. if (ws && ws.readyState == 1) {
  67. ws.send(JSON.stringify({subscribe:topic}));
  68. }
  69. }
  70. return {
  71. connect: connectWS,
  72. subscribe: subscribe
  73. }
  74. })();