| 1 | import { Protocol, ProtocolVersion } from '../../types/UIProtocol'; |
| 2 | import WebSocket, { OPEN, Server } from 'ws'; |
| 3 | |
| 4 | import AbstractUIService from './ui-services/AbstractUIService'; |
| 5 | import Configuration from '../../utils/Configuration'; |
| 6 | import { IncomingMessage } from 'http'; |
| 7 | import { ServerOptions } from '../../types/ConfigurationData'; |
| 8 | import UIServiceFactory from './ui-services/UIServiceFactory'; |
| 9 | import Utils from '../../utils/Utils'; |
| 10 | import logger from '../../utils/Logger'; |
| 11 | |
| 12 | export default class UIWebSocketServer extends Server { |
| 13 | public readonly chargingStations: Set<string>; |
| 14 | private readonly uiServices: Map<ProtocolVersion, AbstractUIService>; |
| 15 | |
| 16 | public constructor(options?: ServerOptions, callback?: () => void) { |
| 17 | // Create the WebSocket server |
| 18 | super(options ?? Configuration.getUIServer().options, callback); |
| 19 | this.chargingStations = new Set<string>(); |
| 20 | this.uiServices = new Map<ProtocolVersion, AbstractUIService>(); |
| 21 | } |
| 22 | |
| 23 | public start(): void { |
| 24 | this.on('connection', (socket: WebSocket, request: IncomingMessage): void => { |
| 25 | const protocolIndex = socket.protocol.indexOf(Protocol.UI); |
| 26 | const version = socket.protocol.substring( |
| 27 | protocolIndex + Protocol.UI.length |
| 28 | ) as ProtocolVersion; |
| 29 | if (!this.uiServices.has(version)) { |
| 30 | this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this)); |
| 31 | } |
| 32 | // FIXME: check connection validity |
| 33 | socket.on('message', (messageData) => { |
| 34 | this.uiServices |
| 35 | .get(version) |
| 36 | .messageHandler(messageData) |
| 37 | .catch(() => { |
| 38 | logger.error(`${this.logPrefix()} Error while handling message data: %j`, messageData); |
| 39 | }); |
| 40 | }); |
| 41 | socket.on('error', (error) => { |
| 42 | logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error); |
| 43 | }); |
| 44 | }); |
| 45 | } |
| 46 | |
| 47 | public stop(): void { |
| 48 | this.close(); |
| 49 | } |
| 50 | |
| 51 | public sendResponse(message: string): void { |
| 52 | this.broadcastToClients(message); |
| 53 | } |
| 54 | |
| 55 | public logPrefix(): string { |
| 56 | return Utils.logPrefix(' UI WebSocket Server:'); |
| 57 | } |
| 58 | |
| 59 | private broadcastToClients(message: string): void { |
| 60 | for (const client of this.clients) { |
| 61 | if (client?.readyState === OPEN) { |
| 62 | client.send(message); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |