import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { webSocket, WebSocketSubject } from 'rxjs/webSocket'; import { filter, map } from 'rxjs/operators'; import { WebSocketMessage } from '../message-types/websocket-message'; export enum Scope { ZMQ = 'zmq', WEBSOCKET = 'websocket' } export enum Intent { CONTROL = 'control', EVENT = 'event' } @Injectable() export class WebSocketService { private ws: WebSocketSubject; constructor() {} public connect() { if (!this.ws) { const wsproto = (location.protocol === 'https:') ? 'wss://' : 'ws://'; const connAddr = wsproto + window.location.host + '/ws'; this.ws = webSocket(connAddr); } } public observeControl(key: string): Observable { return this.observeAll(key).pipe( filter(message => message.intent !== Intent.EVENT) ); } public observeAll(key: string): Observable { return this.ws.pipe( filter(message => message.key.startsWith(key)), map(message => message) ); } public send(json: any) { this.ws.next(json); } }