Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

81 lines
2.3KB

  1. /** Modified from original Node-Red source, for audio system visualization
  2. * vim: set ts=4:
  3. * Copyright 2014 IBM Corp.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. **/
  17. RED.comms = (function() {
  18. var errornotification = null;
  19. var subscriptions = {};
  20. var ws;
  21. function connectWS() {
  22. var path = location.hostname+":"+location.port+document.location.pathname;
  23. path = path+(path.slice(-1) == "/"?"":"/")+"comms";
  24. path = "ws"+(document.location.protocol=="https:"?"s":"")+"://"+path;
  25. ws = new WebSocket(path);
  26. ws.onopen = function() {
  27. if (errornotification) {
  28. errornotification.close();
  29. errornotification = null;
  30. }
  31. for (var t in subscriptions) {
  32. if (subscriptions.hasOwnProperty(t)) {
  33. ws.send(JSON.stringify({subscribe:t}));
  34. }
  35. }
  36. }
  37. ws.onmessage = function(event) {
  38. var msg = JSON.parse(event.data);
  39. if (msg.topic) {
  40. for (var t in subscriptions) {
  41. if (subscriptions.hasOwnProperty(t)) {
  42. var re = new RegExp("^"+t.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g,"\\$1").replace(/\+/g,"[^/]+").replace(/\/#$/,"(\/.*)?")+"$");
  43. if (re.test(msg.topic)) {
  44. var subscribers = subscriptions[t];
  45. if (subscribers) {
  46. for (var i=0;i<subscribers.length;i++) {
  47. subscribers[i](msg.topic,msg.data);
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. };
  55. ws.onclose = function() {
  56. if (errornotification == null) {
  57. //errornotification = RED.notify("<b>Error</b>: Lost connection to server","error",true);
  58. }
  59. setTimeout(connectWS,1000);
  60. }
  61. }
  62. function subscribe(topic,callback) {
  63. if (subscriptions[topic] == null) {
  64. subscriptions[topic] = [];
  65. }
  66. subscriptions[topic].push(callback);
  67. if (ws && ws.readyState == 1) {
  68. ws.send(JSON.stringify({subscribe:topic}));
  69. }
  70. }
  71. return {
  72. connect: connectWS,
  73. subscribe: subscribe
  74. }
  75. })();