receptor/src/socket.js

72 lines
1.6 KiB
JavaScript
Raw Normal View History

import { dispatch } from './store';
2018-03-10 15:48:10 +01:00
import { subscribe, unsubscribe } from './actions/subscribe';
let ws;
let serial = 0;
let transactions = {};
2017-09-08 09:35:12 +02:00
let connected = false;
let queue = [];
2017-10-13 06:34:26 +02:00
const getURI = ({ uri, password }) => `${uri}${password ?
`?password=${encodeURIComponent(password)}` : ''}`;
2017-12-30 18:23:50 +01:00
export default function ws_send(type, body, callback = null, __serial = null) {
const _serial = __serial !== null ? __serial : serial++;
if (callback) {
transactions[_serial] = callback;
}
const obj = {
type,
serial: _serial,
...body
};
const msg = JSON.stringify(obj);
console.log("->", type, obj);
2017-09-08 09:35:12 +02:00
if (!connected) {
queue.push(msg);
} else {
ws.send(msg);
}
return _serial;
}
2018-03-10 15:48:10 +01:00
function _resources_removed(msg) {
dispatch(unsubscribe(...msg.ids));
dispatch(msg);
}
const handlers = {
RESOURCES_EXTANT: msg => dispatch(subscribe(...msg.ids)),
2017-09-08 10:27:00 +02:00
UPDATE_RESOURCES: msg => dispatch(msg),
2018-03-10 15:48:10 +01:00
RESOURCES_REMOVED: msg => _resources_removed(msg),
};
function ws_recv(e) {
const msg = JSON.parse(e.data);
console.log("<-", msg.type, msg);
const cb = transactions[msg.serial];
cb && cb(msg);
const handler = handlers[msg.type];
handler && handler(msg);
}
2017-09-08 06:55:47 +02:00
export function ws_init(uri, open, close) {
2017-10-13 06:34:26 +02:00
ws = new WebSocket(getURI(uri));
2017-09-08 09:35:12 +02:00
ws.addEventListener("open", () => {
connected = true;
open.apply(this, arguments);
while (queue.length > 0) {
ws.send(queue.pop());
}
});
ws.addEventListener("message", ws_recv);
2017-09-08 09:35:12 +02:00
ws.addEventListener("close", () => {
connected = false;
close.apply(this, arguments);
});
}
2017-09-08 07:07:31 +02:00
export function ws_disconnect() {
ws.close();
}