be2961c522584172560a9736b15f6703f10599da
1 import { IncomingMessage
} from
'http';
3 import WebSocket from
'ws';
5 import { ServerOptions
} from
'../../types/ConfigurationData';
6 import { Protocol
, ProtocolVersion
} from
'../../types/UIProtocol';
7 import Configuration from
'../../utils/Configuration';
8 import logger from
'../../utils/Logger';
9 import Utils from
'../../utils/Utils';
10 import { AbstractUIServer
} from
'./AbstractUIServer';
11 import UIServiceFactory from
'./ui-services/UIServiceFactory';
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 protocolIndex
= socket
.protocol
.indexOf(Protocol
.UI
);
24 const version
= socket
.protocol
.substring(
25 protocolIndex
+ Protocol
.UI
.length
27 if (!this.uiServices
.has(version
)) {
28 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
30 // FIXME: check connection validity
31 socket
.on('message', (rawData
) => {
34 .requestHandler(rawData
)
36 /* Error caught by AbstractUIService */
39 socket
.on('error', (error
) => {
41 `${this.logPrefix(moduleName, 'start.socket.onerror')} Error on WebSocket:`,
49 this.chargingStations
.clear();
52 public sendRequest(request
: string): void {
53 this.broadcastToClients(request
);
56 public sendResponse(response
: string): void {
57 // TODO: send response only to the client that sent the request
58 this.broadcastToClients(response
);
61 public logPrefix(modName
?: string, methodName
?: string): string {
64 ? ` UI WebSocket Server | ${modName}.${methodName}:`
65 : ' UI WebSocket Server |';
66 return Utils
.logPrefix(logMsg
);
69 private broadcastToClients(message
: string): void {
70 for (const client
of (this.server
as WebSocket
.Server
).clients
) {
71 if (client
?.readyState
=== WebSocket
.OPEN
) {