import * as Html5WebSocket from '@ont-community/html5-websocket' ; import * as WebSocketAsPromised from 'websocket-as-promised' ; import { TEST_ONT_URL } from '../../consts' ; /**
 * We can import html5-websocket directly, because webpack will use html5-websocket/browser.js
 * in browser environment, which does not require 'ws'.
 */ /**
 * Websocket sender for send messages and handle notify.
 */ export class WebsocketSender { private static generateReqId ( ) { return Math . floor ( Math . random ( ) * 10e8 ) ; } debug : boolean ; private wsp : any ; constructor ( url = TEST_ONT_URL . SOCKET_URL , debug = false ) { this . debug = debug ; this . wsp = new WebSocketAsPromised ( url , { createWebSocket : ( socketUrl ) => new Html5WebSocket ( socketUrl ) , attachRequestId : ( data , id ) => ( { Id : id , ... data } ) , extractRequestId : ( data ) => data && data . Id , packMessage : ( data ) => JSON . stringify ( data ) , unpackMessage : ( message ) => JSON . parse ( message ) } ) ; this . wsp . onOpen . addListener ( ( ) => { if ( this . debug ) { console . log ( 'connected' ) ; } } ) ; this . wsp . onClose . addListener ( ( ) => { if ( this . debug ) { console . log ( 'disconnected' ) ; } } ) ; this . wsp . onSend . addListener ( ( message ) => { if ( this . debug ) { console . log ( 'sent: ' , message ) ; } } ) ; this . wsp . onMessage . addListener ( ( message ) => { if ( this . debug ) { console . log ( 'received: ' , message ) ; } } ) ; this . wsp . onError . addListener ( ( event ) => { if ( this . debug ) { console . log ( 'error: ' , event ) ; } } ) ; } async send < T extends object > ( param , close = true ) { try { if ( ! param ) { return ; } await this . wsp . open ( ) ; const response = await this . wsp . sendRequest ( param , { requestId : WebsocketSender . generateReqId ( ) } ) ; return response ; } finally { if ( close ) { await this . wsp . close ( ) ; } } } addListener ( listener ) { this . wsp . onUnpackedMessage . addListener ( listener ) ; } close ( ) { this . wsp . close ( ) ; } }