2017-08-22 00:10:52 +02:00
|
|
|
import { dispatch } from './store';
|
|
|
|
import { subscribe } from './actions/subscribe';
|
|
|
|
|
|
|
|
let ws;
|
|
|
|
let serial = 0;
|
|
|
|
let transactions = {};
|
2017-09-08 09:35:12 +02:00
|
|
|
let connected = false;
|
|
|
|
let queue = [];
|
2017-08-22 00:10:52 +02:00
|
|
|
|
2017-10-13 06:34:26 +02:00
|
|
|
const getURI = ({ uri, password }) => `${uri}${password ?
|
|
|
|
`?password=${encodeURIComponent(password)}` : ''}`;
|
|
|
|
|
2017-08-22 00:10:52 +02:00
|
|
|
export default function ws_send(type, body, callback = null) {
|
|
|
|
const _serial = serial++;
|
|
|
|
if (callback) {
|
|
|
|
transactions[_serial] = callback;
|
|
|
|
}
|
2017-08-25 03:13:01 +02:00
|
|
|
const obj = {
|
2017-08-22 00:10:52 +02:00
|
|
|
type,
|
|
|
|
serial: _serial,
|
|
|
|
...body
|
2017-08-25 03:13:01 +02:00
|
|
|
};
|
|
|
|
const msg = JSON.stringify(obj);
|
2017-08-25 03:46:55 +02:00
|
|
|
console.log("->", type, obj);
|
2017-09-08 09:35:12 +02:00
|
|
|
if (!connected) {
|
|
|
|
queue.push(msg);
|
|
|
|
} else {
|
|
|
|
ws.send(msg);
|
|
|
|
}
|
2017-08-22 00:10:52 +02:00
|
|
|
return _serial;
|
|
|
|
}
|
|
|
|
|
|
|
|
const handlers = {
|
|
|
|
RESOURCES_EXTANT: msg => dispatch(subscribe(...msg.ids)),
|
2017-09-08 10:27:00 +02:00
|
|
|
UPDATE_RESOURCES: msg => dispatch(msg),
|
|
|
|
RESOURCES_REMOVED: msg => dispatch(msg),
|
2017-08-22 00:10:52 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
function ws_recv(e) {
|
|
|
|
const msg = JSON.parse(e.data);
|
2017-08-25 03:46:55 +02:00
|
|
|
console.log("<-", msg.type, msg);
|
2017-08-22 00:10:52 +02:00
|
|
|
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());
|
|
|
|
}
|
|
|
|
});
|
2017-08-22 00:10:52 +02:00
|
|
|
ws.addEventListener("message", ws_recv);
|
2017-09-08 09:35:12 +02:00
|
|
|
ws.addEventListener("close", () => {
|
|
|
|
connected = false;
|
|
|
|
close.apply(this, arguments);
|
|
|
|
});
|
2017-08-22 00:10:52 +02:00
|
|
|
}
|
2017-09-08 07:07:31 +02:00
|
|
|
|
|
|
|
export function ws_disconnect() {
|
|
|
|
ws.close();
|
|
|
|
}
|