X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Fui-server%2FUIWebSocketServer.ts;h=c4829dcc29d9362d024fde7644c2df8355405218;hb=5e3cb7281de2b6fa8b61a453f964c2f213fefa80;hp=abc3ec6730808f522ae83e0ce00e4d4b4f6a33cd;hpb=18d3414af1e352238e2888687b02d6e2606fb4f9;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ui-server/UIWebSocketServer.ts b/src/charging-station/ui-server/UIWebSocketServer.ts index abc3ec67..c4829dcc 100644 --- a/src/charging-station/ui-server/UIWebSocketServer.ts +++ b/src/charging-station/ui-server/UIWebSocketServer.ts @@ -1,65 +1,114 @@ -import { Protocol, ProtocolVersion } from '../../types/UIProtocol'; -import WebSocket, { OPEN, Server, ServerOptions } from 'ws'; +import type { IncomingMessage } from 'http'; -import AbstractUIService from './ui-services/AbstractUIService'; +import WebSocket, { RawData } from 'ws'; + +import BaseError from '../../exception/BaseError'; +import type { ServerOptions } from '../../types/ConfigurationData'; +import type { ProtocolRequest, ProtocolResponse } from '../../types/UIProtocol'; +import { WebSocketCloseEventStatusCode } from '../../types/WebSocket'; import Configuration from '../../utils/Configuration'; -import { IncomingMessage } from 'http'; -import UIServiceFactory from './ui-services/UIServiceFactory'; -import Utils from '../../utils/Utils'; import logger from '../../utils/Logger'; +import Utils from '../../utils/Utils'; +import { AbstractUIServer } from './AbstractUIServer'; +import UIServiceFactory from './ui-services/UIServiceFactory'; +import { UIServiceUtils } from './ui-services/UIServiceUtils'; -export default class UIWebSocketServer extends Server { - public readonly chargingStations: Set; - private readonly uiServices: Map; +const moduleName = 'UIWebSocketServer'; - public constructor(options?: ServerOptions, callback?: () => void) { - // Create the WebSocket Server - super(options ?? Configuration.getUIServer().options, callback); - this.chargingStations = new Set(); - this.uiServices = new Map(); +export default class UIWebSocketServer extends AbstractUIServer { + public constructor(options?: ServerOptions) { + super(); + this.server = new WebSocket.Server(options ?? Configuration.getUIServer().options); } public start(): void { - this.on('connection', (socket: WebSocket, request: IncomingMessage): void => { - const protocolIndex = socket.protocol.indexOf(Protocol.UI); - const version = socket.protocol.substring( - protocolIndex + Protocol.UI.length - ) as ProtocolVersion; + this.server.on('connection', (ws: WebSocket, request: IncomingMessage): void => { + const [protocol, version] = UIServiceUtils.getProtocolAndVersion(ws.protocol); + if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === false) { + logger.error( + `${this.logPrefix( + moduleName, + 'start.server.onconnection' + )} Unsupported UI protocol version: '${protocol}${version}'` + ); + ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR); + } if (!this.uiServices.has(version)) { this.uiServices.set(version, UIServiceFactory.getUIServiceImplementation(version, this)); } - // FIXME: check connection validity - socket.on('message', (messageData) => { + ws.on('message', (rawData) => { + const [messageId, procedureName, payload] = this.validateRawDataRequest(rawData); this.uiServices .get(version) - .messageHandler(messageData) + .requestHandler(this.buildProtocolRequest(messageId, procedureName, payload)) .catch(() => { - logger.error(`${this.logPrefix()} Error while handling message data: %j`, messageData); + /* Error caught by AbstractUIService */ }); }); - socket.on('error', (error) => { - logger.error(`${this.logPrefix()} Error on WebSocket: %j`, error); + ws.on('error', (error) => { + logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error); + }); + ws.on('close', (code, reason) => { + logger.debug( + `${this.logPrefix( + moduleName, + 'start.ws.onclose' + )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString( + code + )}' - '${reason.toString()}'` + ); }); }); } public stop(): void { - this.close(); + this.chargingStations.clear(); + } + + public sendRequest(request: ProtocolRequest): void { + this.broadcastToClients(JSON.stringify(request)); } - public sendResponse(message: string): void { - this.broadcastToClients(message); + public sendResponse(response: ProtocolResponse): void { + // TODO: send response only to the client that sent the request + this.broadcastToClients(JSON.stringify(response)); } - public logPrefix(): string { - return Utils.logPrefix(' UI WebSocket Server:'); + public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string { + const logMsgPrefix = prefixSuffix + ? `UI WebSocket Server ${prefixSuffix}` + : 'UI WebSocket Server'; + const logMsg = + modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`; + return Utils.logPrefix(logMsg); } private broadcastToClients(message: string): void { - for (const client of this.clients) { - if (client?.readyState === OPEN) { + for (const client of (this.server as WebSocket.Server).clients) { + if (client?.readyState === WebSocket.OPEN) { client.send(message); } } } + + private validateRawDataRequest(rawData: RawData): ProtocolRequest { + // logger.debug( + // `${this.logPrefix( + // moduleName, + // 'validateRawDataRequest' + // )} Raw data received in string format: ${rawData.toString()}` + // ); + + const request = JSON.parse(rawData.toString()) as ProtocolRequest; + + if (Array.isArray(request) === false) { + throw new BaseError('UI protocol request is not an array'); + } + + if (request.length !== 3) { + throw new BaseError('UI protocol request is malformed'); + } + + return request; + } }