unistore wip

This commit is contained in:
ntr committed 2022-09-03 14:26:41 +10:00
1 parent a43d4f32e4
commit cf01670ee6
17 files changed
+253 -79

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
const SOCKET_URL = (window.location.host.includes('localhost') || window.location.host === '' || window.location.host.includes('192.168.0'))
? `ws://${window.location.hostname}:40080`
: `${window.location.protocol === 'https:' ? 'wss://' : 'ws://'}${window.location.host}/api/ws`;
export default function createSocket(store) {
let ws;
// -------------
// Outgoing
// -------------
function send(msg) {
if (msg[0] !== 'Ping') console.log('outgoing msg', msg);
if (ws.readyState !== 1) return false;
try {
ws.send(JSON.stringify(msg));
} catch (e) {
console.warn(e);
}
}
// let ping;
function sendPing() {
// ping = Date.now();
send(['Ping', {}]);
// setTimeout(sendPing, 50);
}
function sendSourcesAvailable() {
send(['SourcesAvailable', {}]);
}
let pongTimeout;
function onPong() {
pongTimeout = setTimeout(sendPing, 1000);
}
// -------------
// Incoming
// -------------
function onSourcesAvailable(clouds) {
// store.dispatch(http.LIBRARY_RECEIVE_POINTCLOUDS, clouds);
}
// -------------
// Setup
// -------------
// when the server sends a reply it will have one of these message types
// this object wraps the reply types to a function
const handlers = {
SourcesAvailable: onSourcesAvailable,
Pong: onPong,
Error: errHandler,
};
function errHandler(error) {
// store.dispatch(http.LIBRARY_EVENT, { level: 'error', log: error });
console.error(error);
}
function onMessage(event) {
const res = event.data;
const [msgType, params] = JSON.parse(res);
if (msgType !== 'Pong') {
console.log(msgType, params);
}
// check for error and split into response type and data
if (!handlers[msgType]) return console.error(`${msgType} handler missing`);
return handlers[msgType](params);
}
// Connection opened
function onOpen() {
sendPing();
}
function onError(event) {
console.error('WebSocket error', event);
}
function onClose(event) {
console.error('WebSocket closed', event);
return setTimeout(connect, 2000);
}
function connect() {
if (ws) {
clearTimeout(pongTimeout);
ws.removeEventListener('open', onOpen);
ws.removeEventListener('message', onMessage);
ws.removeEventListener('error', onError);
ws.removeEventListener('close', onClose);
ws = null;
}
console.log('connecting to websocket', SOCKET_URL);
ws = new WebSocket(SOCKET_URL);
// Listen for messages
ws.addEventListener('open', onOpen);
ws.addEventListener('message', onMessage);
ws.addEventListener('error', onError);
ws.addEventListener('close', onClose);
return ws;
}
return {
connect,
sendSourcesAvailable,
};
}