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