X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=6797515f076fc40385f53ca2c6baf1e7de516a38;hb=d0641efac20e7bc7c114a3183574b6cad8667733;hp=abef0e29fe5b84726bb3f7805f920f095cd756fe;hpb=ec977daf25908bc656769c1743d1350f2ff774ea;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index abef0e29..6797515f 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, IncomingRequest, IncomingRequestCommand, RemoteStartTransactionRequest, RemoteStopTransactionRequest, Request, RequestCommand, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests'; import WebSocket, { MessageEvent } from 'ws'; import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; @@ -16,7 +16,9 @@ import ChargingStationInfo from '../types/ChargingStationInfo'; import Configuration from '../utils/Configuration'; import Constants from '../utils/Constants'; import ElectricUtils from '../utils/ElectricUtils'; +import { ErrorType } from '../types/ocpp/ErrorType'; import MeasurandValues from '../types/MeasurandValues'; +import { MessageType } from '../types/ocpp/MessageType'; import OCPPError from './OcppError'; import Statistics from '../utils/Statistics'; import Utils from '../utils/Utils'; @@ -619,7 +621,7 @@ export default class ChargingStation { this._openWSConnection({ handshakeTimeout: reconnectDelay - 100 }); this._hasSocketRestarted = true; } else if (this._getAutoReconnectMaxRetries() !== -1) { - logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`); + logger.error(`${this._logPrefix()} Socket reconnect failure: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`); } } @@ -647,7 +649,7 @@ export default class ChargingStation { } } } else { - logger.error(`${this._logPrefix()} Registration: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`); + logger.error(`${this._logPrefix()} Registration failure: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`); } this._autoReconnectRetryCount = 0; this._hasSocketRestarted = false; @@ -685,15 +687,19 @@ export default class ChargingStation { } async onMessage(messageEvent: MessageEvent): Promise { - let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', '']; + let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, '', '']; + let responseCallback: (payload?, requestPayload?) => void; + let rejectCallback: (error: OCPPError) => void; + let requestPayload: Record; + let errMsg: string; try { // Parse the message - [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()); + [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest; // Check the Type of message switch (messageType) { // Incoming Message - case Constants.OCPP_JSON_CALL_MESSAGE: + case MessageType.CALL_MESSAGE: if (this.getEnableStatistics()) { this._statistics.addMessage(commandName, messageType); } @@ -701,10 +707,8 @@ export default class ChargingStation { await this.handleRequest(messageId, commandName, commandPayload); break; // Outcome Message - case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: + case MessageType.CALL_RESULT_MESSAGE: // Respond - // eslint-disable-next-line no-case-declarations - let responseCallback; let requestPayload; if (Utils.isIterable(this._requests[messageId])) { [responseCallback, , requestPayload] = this._requests[messageId]; } else { @@ -718,13 +722,11 @@ export default class ChargingStation { responseCallback(commandName, requestPayload); break; // Error Message - case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: + case MessageType.CALL_ERROR_MESSAGE: if (!this._requests[messageId]) { // Error throw new Error(`Error request for unknown message id ${messageId}`); } - // eslint-disable-next-line no-case-declarations - let rejectCallback; if (Utils.isIterable(this._requests[messageId])) { [, rejectCallback] = this._requests[messageId]; } else { @@ -735,35 +737,32 @@ export default class ChargingStation { break; // Error default: - // eslint-disable-next-line no-case-declarations - const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`; + errMsg = `${this._logPrefix()} Wrong message type ${messageType}`; logger.error(errMsg); throw new Error(errMsg); } } catch (error) { // Log - logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent, error, this._requests[messageId]); + logger.error('%s Incoming message %j processing error %j on request content type %j', this._logPrefix(), messageEvent, error, this._requests[messageId]); // Send error - messageType !== Constants.OCPP_JSON_CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName); + messageType !== MessageType.CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName); } } async sendHeartbeat(): Promise { try { const payload: HeartbeatRequest = {}; - await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_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, Constants.OCPP_JSON_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); } } @@ -775,10 +774,9 @@ export default class ChargingStation { errorCode, status, }; - await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_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); } } @@ -790,10 +788,9 @@ export default class ChargingStation { meterStart: 0, timestamp: new Date().toISOString(), }; - return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_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); } } @@ -807,10 +804,9 @@ export default class ChargingStation { timestamp: new Date().toISOString(), ...reason && { reason }, }; - return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_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); } } @@ -1028,47 +1024,46 @@ export default class ChargingStation { transactionId: self.getConnector(connectorId).transactionId, meterValue: meterValue, }; - await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_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(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack); + const error = err instanceof OCPPError ? err : new OCPPError(ErrorType.INTERNAL_ERROR, err.message, err.stack && err.stack); // Send error - return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName); + return this.sendMessage(messageId, error, MessageType.CALL_ERROR_MESSAGE, commandName); } - async sendMessage(messageId: string, commandParams, messageType = Constants.OCPP_JSON_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 return new Promise((resolve: (value?: any | PromiseLike) => void, reject: (reason?: any) => void) => { - let messageToSend; + let messageToSend: string; // Type of message switch (messageType) { // Request - case Constants.OCPP_JSON_CALL_MESSAGE: + case MessageType.CALL_MESSAGE: // Build request - this._requests[messageId] = [responseCallback, rejectCallback, commandParams]; + this._requests[messageId] = [responseCallback, rejectCallback, commandParams] as Request; messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]); break; // Response - case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: + case MessageType.CALL_RESULT_MESSAGE: // Build response messageToSend = JSON.stringify([messageType, messageId, commandParams]); break; // Error Message - case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: + case MessageType.CALL_ERROR_MESSAGE: // Build Error Message - messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]); + messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]); 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); } @@ -1079,7 +1074,7 @@ export default class ChargingStation { // Handle dups in buffer for (const message of this._messageQueue) { // Same message - if (JSON.stringify(messageToSend) === JSON.stringify(message)) { + if (messageToSend === message) { dups = true; break; } @@ -1089,15 +1084,15 @@ export default class ChargingStation { this._messageQueue.push(messageToSend); } // Reject it - return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {})); + return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {})); } // Response? - if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) { + if (messageType === MessageType.CALL_RESULT_MESSAGE) { // Yes: send Ok resolve(); - } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) { + } else if (messageType === MessageType.CALL_ERROR_MESSAGE) { // Send timeout - setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_SOCKET_TIMEOUT); + setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_ERROR_TIMEOUT); } // Function that will receive the request's response @@ -1106,7 +1101,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); } @@ -1125,7 +1120,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); @@ -1236,7 +1231,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') { @@ -1252,11 +1247,11 @@ export default class ChargingStation { } } else { // Throw exception - await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName); + await this.sendError(messageId, new OCPPError(ErrorType.NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName); throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`); } // Send response - await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName); + await this.sendMessage(messageId, response, MessageType.CALL_RESULT_MESSAGE, commandName); } // Simulate charging station restart @@ -1456,5 +1451,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; + } }