From: Jérôme Benoit Date: Fri, 1 Jan 2021 18:15:26 +0000 (+0100) Subject: Add enum list for request command name. X-Git-Tag: v1.0.1-0~152^2~9 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=d9f60ba1bd2b6d44bc99bf02d76d8da16a0566e6;p=e-mobility-charging-stations-simulator.git Add enum list for request command name. Signed-off-by: Jérôme Benoit --- diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 7da49c30..20d8db73 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -6,7 +6,7 @@ import ChargingStationTemplate, { PowerOutType } from '../types/ChargingStationT import Connectors, { Connector } from '../types/Connectors'; import { MeterValue, MeterValueLocation, MeterValueMeasurand, MeterValuePhase, MeterValueUnit, MeterValuesRequest, MeterValuesResponse, SampledValue } from '../types/ocpp/1.6/MeterValues'; import { PerformanceObserver, performance } from 'perf_hooks'; -import Requests, { BootNotificationRequest, ChangeConfigurationRequest, GetConfigurationRequest, HeartbeatRequest, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests'; +import Requests, { BootNotificationRequest, ChangeConfigurationRequest, GetConfigurationRequest, HeartbeatRequest, IncomingRequestCommand, RemoteStartTransactionRequest, RemoteStopTransactionRequest, RequestCommand, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests'; import WebSocket, { MessageEvent } from 'ws'; import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; @@ -697,10 +697,10 @@ export default class ChargingStation { // Incoming Message case MessageType.CALL_MESSAGE: if (this.getEnableStatistics()) { - this._statistics.addMessage(commandName, messageType); + this._statistics.addMessage(commandName as IncomingRequestCommand, messageType); } // Process the call - await this.handleRequest(messageId, commandName, commandPayload); + await this.handleRequest(messageId, commandName as IncomingRequestCommand, commandPayload); break; // Outcome Message case MessageType.CALL_RESULT_MESSAGE: @@ -746,26 +746,24 @@ export default class ChargingStation { // Log logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent, error, this._requests[messageId]); // Send error - messageType !== MessageType.CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName); + messageType !== MessageType.CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName as IncomingRequestCommand); } } async sendHeartbeat(): Promise { try { const payload: HeartbeatRequest = {}; - await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, 'Heartbeat'); + await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.HEARTBEAT); } catch (error) { - logger.error(this._logPrefix() + ' Send Heartbeat error: %j', error); - throw error; + this.handleRequestError(RequestCommand.HEARTBEAT, error); } } async sendBootNotification(): Promise { try { - return await this.sendMessage(Utils.generateUUID(), this._bootNotificationRequest, MessageType.CALL_MESSAGE, 'BootNotification') as BootNotificationResponse; + return await this.sendMessage(Utils.generateUUID(), this._bootNotificationRequest, MessageType.CALL_MESSAGE, RequestCommand.BOOT_NOTIFICATION) as BootNotificationResponse; } catch (error) { - logger.error(this._logPrefix() + ' Send BootNotification error: %j', error); - throw error; + this.handleRequestError(RequestCommand.BOOT_NOTIFICATION, error); } } @@ -777,10 +775,9 @@ export default class ChargingStation { errorCode, status, }; - await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, 'StatusNotification'); + await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.STATUS_NOTIFICATION); } catch (error) { - logger.error(this._logPrefix() + ' Send StatusNotification error: %j', error); - throw error; + this.handleRequestError(RequestCommand.STATUS_NOTIFICATION, error); } } @@ -792,10 +789,9 @@ export default class ChargingStation { meterStart: 0, timestamp: new Date().toISOString(), }; - return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, 'StartTransaction') as StartTransactionResponse; + return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.START_TRANSACTION) as StartTransactionResponse; } catch (error) { - logger.error(this._logPrefix() + ' Send StartTransaction error: %j', error); - throw error; + this.handleRequestError(RequestCommand.START_TRANSACTION, error); } } @@ -809,10 +805,9 @@ export default class ChargingStation { timestamp: new Date().toISOString(), ...reason && { reason }, }; - return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, 'StopTransaction') as StartTransactionResponse; + return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.STOP_TRANSACTION) as StartTransactionResponse; } catch (error) { - logger.error(this._logPrefix() + ' Send StopTransaction error: %j', error); - throw error; + this.handleRequestError(RequestCommand.STOP_TRANSACTION, error); } } @@ -1030,21 +1025,20 @@ export default class ChargingStation { transactionId: self.getConnector(connectorId).transactionId, meterValue: meterValue, }; - await self.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, 'MeterValues'); + await self.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.METERVALUES); } catch (error) { - logger.error(self._logPrefix() + ' Send MeterValues error: %j', error); - throw error; + this.handleRequestError(RequestCommand.METERVALUES, error); } } - async sendError(messageId: string, err: Error | OCPPError, commandName: string): Promise { + async sendError(messageId: string, err: Error | OCPPError, commandName: RequestCommand | IncomingRequestCommand): Promise { // Check exception type: only OCPP error are accepted const error = err instanceof OCPPError ? err : new OCPPError(ErrorType.INTERNAL_ERROR, err.message, err.stack && err.stack); // Send error return this.sendMessage(messageId, error, MessageType.CALL_ERROR_MESSAGE, commandName); } - async sendMessage(messageId: string, commandParams, messageType = MessageType.CALL_RESULT_MESSAGE, commandName: string): Promise { + async sendMessage(messageId: string, commandParams, messageType = MessageType.CALL_RESULT_MESSAGE, commandName: RequestCommand | IncomingRequestCommand): Promise { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; // Send a message through wsConnection @@ -1070,7 +1064,7 @@ export default class ChargingStation { break; } // Check if wsConnection opened and charging station registered - if (this._isWebSocketOpen() && (this._isRegistered() || commandName === 'BootNotification')) { + if (this._isWebSocketOpen() && (this._isRegistered() || commandName === RequestCommand.BOOT_NOTIFICATION)) { if (this.getEnableStatistics()) { this._statistics.addMessage(commandName, messageType); } @@ -1108,7 +1102,7 @@ export default class ChargingStation { self._statistics.addMessage(commandName, messageType); } // Send the response - await self.handleResponse(commandName, payload, requestPayload); + await self.handleResponse(commandName as RequestCommand, payload, requestPayload); resolve(payload); } @@ -1127,7 +1121,7 @@ export default class ChargingStation { }); } - async handleResponse(commandName: string, payload, requestPayload): Promise { + async handleResponse(commandName: RequestCommand, payload, requestPayload): Promise { const responseCallbackFn = 'handleResponse' + commandName; if (typeof this[responseCallbackFn] === 'function') { await this[responseCallbackFn](payload, requestPayload); @@ -1238,7 +1232,7 @@ export default class ChargingStation { logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload); } - async handleRequest(messageId: string, commandName: string, commandPayload): Promise { + async handleRequest(messageId: string, commandName: IncomingRequestCommand, commandPayload): Promise { let response; // Call if (typeof this['handleRequest' + commandName] === 'function') { @@ -1458,5 +1452,10 @@ export default class ChargingStation { logger.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString()); return Constants.OCPP_RESPONSE_REJECTED; } + + private handleRequestError(commandName: RequestCommand, error: Error) { + logger.error(this._logPrefix() + ' Send ' + commandName + ' error: %j', error); + throw error; + } } diff --git a/src/types/ocpp/1.6/Requests.ts b/src/types/ocpp/1.6/Requests.ts index e8368793..bbcf5145 100644 --- a/src/types/ocpp/1.6/Requests.ts +++ b/src/types/ocpp/1.6/Requests.ts @@ -7,6 +7,27 @@ export default interface Requests { [id: string]: [(payload?, requestPayload?) => void, (error?: OCPPError) => void, Record]; } +export enum RequestCommand { + BOOT_NOTIFICATION = 'BootNotification', + HEARTBEAT = 'Heartbeat', + STATUS_NOTIFICATION = 'StatusNotification', + CHANGE_CONFIGURATION = 'ChangeConfiguration', + START_TRANSACTION = 'StartTransaction', + STOP_TRANSACTION = 'StopTransaction', + METERVALUES = 'MeterValues' +} + +export enum IncomingRequestCommand { + RESET = 'Reset', + CLEAR_CACHE = 'ClearCache', + UNLOCK_CONNECTOR = 'UnlockConnector', + GET_CONFIGURATION = 'GetConfiguration', + CHANGE_CONFIGURATION = 'ChangeConfiguration', + SET_CHARGING_PROFILE = 'SetChargingProfile', + REMOTE_START_TRANSACTION = 'RemoteStartTransaction', + REMOTE_STOP_TRANSACTION = 'RemoteStopTransaction' +} + // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface HeartbeatRequest {} diff --git a/src/utils/Statistics.ts b/src/utils/Statistics.ts index 1b69b30e..d6174d96 100644 --- a/src/utils/Statistics.ts +++ b/src/utils/Statistics.ts @@ -1,4 +1,5 @@ import CommandStatistics, { CommandStatisticsData, PerfEntry } from '../types/CommandStatistics'; +import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/1.6/Requests'; import CircularArray from './CircularArray'; import Configuration from './Configuration'; @@ -27,7 +28,7 @@ export default class Statistics { return Statistics.instance; } - addMessage(command: string, messageType: number): void { + addMessage(command: RequestCommand | IncomingRequestCommand, messageType: MessageType): void { switch (messageType) { case MessageType.CALL_MESSAGE: if (this._commandsStatistics[command] && this._commandsStatistics[command].countRequest) { @@ -68,7 +69,7 @@ export default class Statistics { } logPerformance(entry: PerformanceEntry, className: string): void { - this.addPerformanceTimer(entry.name, entry.duration); + this.addPerformanceTimer(entry.name as RequestCommand | IncomingRequestCommand, entry.duration); const perfEntry: PerfEntry = {} as PerfEntry; perfEntry.name = entry.name; perfEntry.entryType = entry.entryType; @@ -106,7 +107,7 @@ export default class Statistics { return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2; } - private addPerformanceTimer(command: string, duration: number): void { + private addPerformanceTimer(command: RequestCommand | IncomingRequestCommand, duration: number): void { // Map to proper command name const MAPCOMMAND = { sendMeterValues: 'MeterValues', @@ -114,7 +115,7 @@ export default class Statistics { stopTransaction: 'StopTransaction', }; if (MAPCOMMAND[command]) { - command = MAPCOMMAND[command] as string; + command = MAPCOMMAND[command] as RequestCommand | IncomingRequestCommand; } // Initialize command statistics if (!this._commandsStatistics[command]) {