mirror of
https://github.com/smartyellow/status.git
synced 2025-01-18 21:47:58 +00:00
41 lines
870 B
JavaScript
41 lines
870 B
JavaScript
|
import { ringBell } from './lib';
|
||
|
|
||
|
const socketUrl = window.location.href.replace('http', 'ws') + '/socket';
|
||
|
let reconnectAttempts = 0;
|
||
|
let ws;
|
||
|
|
||
|
export async function connect({ onData }) {
|
||
|
ws = new WebSocket(socketUrl);
|
||
|
|
||
|
ws.onmessage = async evt => {
|
||
|
const data = JSON.parse(evt.data || 'false');
|
||
|
|
||
|
switch (data.cmd) {
|
||
|
case 'data':
|
||
|
onData(data);
|
||
|
break;
|
||
|
|
||
|
case 'bell':
|
||
|
ringBell();
|
||
|
break;
|
||
|
|
||
|
default:
|
||
|
break;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
ws.onopen = () => {
|
||
|
if (reconnectAttempts) {
|
||
|
window.location.reload();
|
||
|
}
|
||
|
};
|
||
|
|
||
|
ws.onclose = async () => {
|
||
|
console.error(`Websocket closed, trying to reconnect... (#${reconnectAttempts++})`);
|
||
|
await new Promise(res => setTimeout(res, reconnectAttempts * 500));
|
||
|
await connect({ onData });
|
||
|
};
|
||
|
|
||
|
ws.onerror = err => console.error('Connection error', err);
|
||
|
}
|