1 import type { IncomingMessage
} from
'http';
3 import WebSocket from
'ws';
5 import type { ServerOptions
} from
'../../types/ConfigurationData';
6 import Configuration from
'../../utils/Configuration';
7 import logger from
'../../utils/Logger';
8 import Utils from
'../../utils/Utils';
9 import { AbstractUIServer
} from
'./AbstractUIServer';
10 import UIServiceFactory from
'./ui-services/UIServiceFactory';
11 import { UIServiceUtils
} from
'./ui-services/UIServiceUtils';
13 const moduleName
= 'UIWebSocketServer';
15 export default class UIWebSocketServer
extends AbstractUIServer
{
16 public constructor(options
?: ServerOptions
) {
18 this.server
= new WebSocket
.Server(options
?? Configuration
.getUIServer().options
);
21 public start(): void {
22 this.server
.on('connection', (socket
: WebSocket
, request
: IncomingMessage
): void => {
23 const [protocol
, version
] = UIServiceUtils
.getProtocolAndVersion(socket
.protocol
);
24 if (UIServiceUtils
.isProtocolAndVersionSupported(protocol
, version
) === false) {
28 'start.server.onconnection'
29 )} Unsupported UI protocol version: '${protocol}${version}'`
33 if (!this.uiServices
.has(version
)) {
34 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
36 // FIXME: check connection validity
37 socket
.on('message', (rawData
) => {
40 .requestHandler(rawData
)
42 /* Error caught by AbstractUIService */
45 socket
.on('error', (error
) => {
47 `${this.logPrefix(moduleName, 'start.socket.onerror')} Error on WebSocket:`,
55 this.chargingStations
.clear();
58 public sendRequest(request
: string): void {
59 this.broadcastToClients(request
);
62 public sendResponse(response
: string): void {
63 // TODO: send response only to the client that sent the request
64 this.broadcastToClients(response
);
67 public logPrefix(modName
?: string, methodName
?: string): string {
70 ? ` UI WebSocket Server | ${modName}.${methodName}:`
71 : ' UI WebSocket Server |';
72 return Utils
.logPrefix(logMsg
);
75 private broadcastToClients(message
: string): void {
76 for (const client
of (this.server
as WebSocket
.Server
).clients
) {
77 if (client
?.readyState
=== WebSocket
.OPEN
) {