import ReconnectingWebSocket from 'reconnecting-websocket'; const OpCodes = { // from device to frontend INITIAL_INFO: 1, SESSION_STARTED: 2, SESSION_STOPPED: 3, SESSION_NEW_DATA: 4, ANSWER_USER_LIST : 5, ANSWER_SESSION_LIST : 6, // from frontend to device START_SESSION: 7, STOP_SESSION: 8, TARE: 9, QUERY_USER_LIST: 10, QUERY_SESSION_LIST: 11 }; export default class SwimTrackerWebsocketConnection { constructor(swimTrackerHost, onData, onStarted, onStopped, onConnect, onDisconnect) { this.swimTrackerHost = swimTrackerHost; this.onData = onData; this.onStarted = onStarted; this.onStopped = onStopped; this.onConnect = onConnect; this.onDisconnect = onDisconnect; const wsOptions = { maxReconnectionDelay: 4000 }; this.ws = new ReconnectingWebSocket(`ws://${swimTrackerHost}:81`, [], wsOptions); this.ws.onmessage = this._onMessage; this.ws.onopen = this.onConnect; this.ws.onclose = this.onDisconnect; this.ws.onerror = this._onError; this.ws.binaryType = 'arraybuffer'; } sendStartCommand() { const data = new Uint8Array(1); data[0] = OpCodes.START_SESSION; this.ws.send(data); } sendStopCommand() { const data = new Uint8Array(1); data[0] = OpCodes.STOP_SESSION; this.ws.send(data); } sendTareCommand() { const data = new Uint8Array(1); data[0] = OpCodes.TARE; this.ws.send(data); } _onMessage = (e) => { const dv = new DataView(e.data); const opCode = dv.getInt8(0); if (opCode === OpCodes.INITIAL_INFO) { const headerSize = 6; const running = Boolean(dv.getInt8(1)); const sessionId = dv.getUint32(2); if (running && e.data.byteLength > headerSize) { const data = new Uint16Array(e.data.slice(headerSize)); this.onStarted(sessionId); this.onData(data); } else this.onStopped(); } else if (opCode === OpCodes.SESSION_STARTED) { const sessionId = dv.getUint32(1); this.onStarted(sessionId); } else if (opCode === OpCodes.SESSION_STOPPED) { this.onStopped(); } else if (opCode === OpCodes.SESSION_NEW_DATA) { const data = new Uint16Array(e.data.slice(1)); this.onData(data); } } _onError = (ev) => { console.log("Websocket error", ev); } };