UNPKG

@parkersoftware/whoson-lib

Version:

Useful whoson related library

73 lines (72 loc) 2.09 kB
"use strict"; var _self = self; var _ports = []; var _ws = null; var _connected; var _ackWait = 30000; //30secs var _ack = false; var _ackTimer; _self.onconnect = function (e) { var port = e.ports[0]; port.addEventListener('message', function (eventMessage) { switch (eventMessage.data[0]) { case "socket.connect": if (_connected) { port.postMessage(["socket.opened"]); return; } _connected = true; _ws = new WebSocket(eventMessage.data[1]); bindEvents(); break; case "socket.send": _ws.send(eventMessage.data[1]); break; case "socket.close": _ws.close(1000, "Socket Closing"); break; } }); _ports.push(port); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. }; function bindEvents() { _ws.onopen = function (e) { sendToAll(["socket.opened"]); }; _ws.onmessage = function (e) { clearTimeout(_ackTimer); sendToAll(["socket.message", e.data]); }; _ws.onclose = function (e) { sendToAll(["socket.closed"]); _connected = false; }; _ws.onerror = function (e) { sendToAll(["socket.error", e]); }; } function sendToAll(message) { _ports.forEach(function (port) { return port.postMessage(message); }); } setInterval(function () { if (_ws == null || _connected === false) return; self.send("noop"); }, 30000); function send(cmdName) { var msg = { Command: "" + cmdName }; startAck(); _ws.send(JSON.stringify(msg)); } function startAck() { _ack = false; if (typeof (_ackTimer) !== "undefined" && _ackTimer !== null) clearTimeout(_ackTimer); _ackTimer = setTimeout(function () { sendToAll(["socket.ack.timer.elapsed", null]); }, _ackWait); }