UNPKG

camstreamerlib

Version:

Helper library for CamStreamer ACAP applications.

74 lines (73 loc) 2.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WsEvents = void 0; class WsEvents { zodSchema; ws; _isDestroyed = false; listeners = {}; constructor(zodSchema, ws) { this.zodSchema = zodSchema; this.ws = ws; this.ws.onMessage = (e) => this.onMessage(e); } get isDestroyed() { return this._isDestroyed; } resendInitData() { const request = { command: 'sendInitData', }; this.ws.send(JSON.stringify(request)); } addListener(type, listener, id) { const typeList = this.listeners[type]; if (typeList === undefined) { this.listeners[type] = { [id]: listener }; return; } typeList[id] = listener; } removeListener(type, id) { const typeList = this.listeners[type]; if (typeList) { delete typeList[id]; if (Object.keys(typeList).length === 0) { delete this.listeners[type]; } } } onMessage(incomeData) { if (this.isDestroyed) { return; } try { const eventData = JSON.parse(incomeData.toString()); const data = this.zodSchema.parse(eventData); if (isInitEvent(data)) { this.processMessage(data.data, true); return; } this.processMessage(data, false); } catch (error) { console.error('Error parsing event data:', incomeData.toString(), error); } } processMessage(event, isInit) { const listeners = this.listeners[event.type]; const list = Object.values(listeners ?? {}); list.forEach((listener) => listener(event, isInit)); } destroy() { this._isDestroyed = true; this.ws.onMessage = () => { }; this.ws.onOpen = () => Promise.reject(new Error('Websocket is destroyed')); this.ws.destroy(); this.listeners = {}; } } exports.WsEvents = WsEvents; const isInitEvent = (event) => { return event.type === 'init'; };