import { hubConnection } from 'signalr-no-jquery'; import { EIOT_DEVICE_MANAGER_HUBNAME, EIOT_DEVICE_MANAGER_URL } from '../lib-constants/env.const'; class EIoTDeviceManagerService { //#region Variables proxy: any; connection: any; connState = [ 'Connecting', 'Connected', 'Reconnecting', 'Disconnecting', 'Disconnected', ]; currConnState = 4; //#endregion Variables //#endregion Initializations //#region Public Methods async getServiceStatus() { return this.currConnState; } getSignalRConn(): any { return new Promise((resolve, reject) => this.connection .start() .done((conn: any) => resolve(this.proxy)) .fail((err: any) => reject(err)) ); } async getActiveComps() { try { const proxy = await this.getSignalRConn(); const proxyResult = await new Promise((resolve) => // Returns a list of all active // components that have been // published to your device proxy.invoke('GetAllComponents').done((res: any) => { resolve(res) }) ); return proxyResult; } catch (err) { console.error(JSON.stringify(err)); return true; } } async tryToConn() { this.connection = hubConnection( EIOT_DEVICE_MANAGER_URL ); this.proxy = this.connection?.createHubProxy( EIOT_DEVICE_MANAGER_HUBNAME ); // Must register an event before connection.start() is called. this.proxy.on('_a', () => undefined); this.connection.stateChanged((t: any, u: any) => { this.currConnState = t.newState; console.info( "Device Manager state changed from: '" + this.connState[t.oldState] + "' to '" + this.connState[t.newState] + "'" ); }); this.connection.disconnected(() => { console.log('Unable to connect to Device Manager.'); }); for (let index = 0; index < 20; index++) { console.log('Trying to connect Device Manager - '+(index + 1)+'/20'); let res: any = false; res = await new Promise((resolve, reject) => setTimeout(async () => { this.connection.start() .done((conn: any) => resolve(true)) .fail((err: any) => resolve(false)) }, 500) ); if (res == true) { return res; } else { if (index == 19) return res; continue; } } } //#endregion Public Methods } export const eiotDeviceManagerService = new EIoTDeviceManagerService();