X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Focpp%2F1.6%2FOCPP16IncomingRequestService.ts;h=6d60d402aeb0c98ba7b48bcb5302ca07276c834a;hb=0ddd246049162ae6adcbf20265f072854a9d258f;hp=9b3748d3304dc9cd591075862c40b064062bdf54;hpb=54510a60e9114c2076c86e6c90fe73c0dfefdb45;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts index 9b3748d3..6d60d402 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -1,7 +1,7 @@ // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved. import { createWriteStream, readdirSync } from 'node:fs' -import { dirname, join, resolve } from 'node:path' +import { dirname, extname, join, resolve } from 'node:path' import { URL, fileURLToPath } from 'node:url' import type { ValidateFunction } from 'ajv' @@ -32,6 +32,7 @@ import { OCPPError } from '../../../exception/index.js' import { type ChangeConfigurationRequest, type ChangeConfigurationResponse, + ConfigurationSection, ErrorType, type GenericResponse, GenericStatus, @@ -41,6 +42,7 @@ import { type GetDiagnosticsResponse, type IncomingRequestHandler, type JsonType, + type LogConfiguration, OCPP16AuthorizationStatus, OCPP16AvailabilityType, type OCPP16BootNotificationRequest, @@ -83,6 +85,7 @@ import { OCPP16SupportedFeatureProfiles, type OCPP16TriggerMessageRequest, type OCPP16TriggerMessageResponse, + OCPP16TriggerMessageStatus, type OCPP16UpdateFirmwareRequest, type OCPP16UpdateFirmwareResponse, type OCPPConfigurationKey, @@ -97,11 +100,13 @@ import { type UnlockConnectorResponse } from '../../../types/index.js' import { + Configuration, Constants, convertToDate, convertToInt, formatDurationMilliSeconds, getRandomInteger, + isAsyncFunction, isEmptyArray, isNotEmptyArray, isNotEmptyString, @@ -404,39 +409,183 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { .bind(this) ] ]) + // Handle incoming request events this.on( OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION, - (chargingStation: ChargingStation, connectorId: number, idTag: string) => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - chargingStation.getConnectorStatus(connectorId)!.transactionRemoteStarted = true - chargingStation.ocppRequestService - .requestHandler( - chargingStation, - OCPP16RequestCommand.START_TRANSACTION, - { - connectorId, - idTag - } - ) - .then(response => { - if (response.status === OCPP16AuthorizationStatus.ACCEPTED) { - logger.debug(` - ${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${ - chargingStation.stationInfo?.chargingStationId - }#${connectorId} for idTag '${idTag}'`) - } else { - logger.debug(` - ${chargingStation.logPrefix()} Remote start transaction REJECTED on ${ - chargingStation.stationInfo?.chargingStationId - }#${connectorId} for idTag '${idTag}'`) + ( + chargingStation: ChargingStation, + request: RemoteStartTransactionRequest, + response: GenericResponse + ) => { + if (response.status === GenericStatus.Accepted) { + const { connectorId, idTag } = request + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + chargingStation.getConnectorStatus(connectorId)!.transactionRemoteStarted = true + chargingStation.ocppRequestService + .requestHandler( + chargingStation, + OCPP16RequestCommand.START_TRANSACTION, + { + connectorId, + idTag } - }) - .catch(error => { - logger.error( - `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`, - error + ) + .then(response => { + if (response.status === OCPP16AuthorizationStatus.ACCEPTED) { + logger.debug( + `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'` + ) + } else { + logger.debug( + `${chargingStation.logPrefix()} Remote start transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${idTag}'` + ) + } + }) + .catch(error => { + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote start transaction error:`, + error + ) + }) + } + } + ) + this.on( + OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION, + ( + chargingStation: ChargingStation, + request: RemoteStopTransactionRequest, + response: GenericResponse + ) => { + if (response.status === GenericStatus.Accepted) { + const { transactionId } = request + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const connectorId = chargingStation.getConnectorIdByTransactionId(transactionId)! + OCPP16ServiceUtils.remoteStopTransaction(chargingStation, connectorId) + .then(response => { + if (response.status === GenericStatus.Accepted) { + logger.debug( + `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for transaction '${transactionId}'` + ) + } else { + logger.debug( + `${chargingStation.logPrefix()} Remote stop transaction REJECTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for transaction '${transactionId}'` + ) + } + }) + .catch(error => { + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.constructor: Remote stop transaction error:`, + error + ) + }) + } + } + ) + this.on( + OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, + ( + chargingStation: ChargingStation, + request: OCPP16TriggerMessageRequest, + response: OCPP16TriggerMessageResponse + ) => { + if (response.status !== OCPP16TriggerMessageStatus.ACCEPTED) { + return + } + const { requestedMessage, connectorId } = request + const errorHandler = (error: Error): void => { + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.constructor: Trigger ${requestedMessage} error:`, + error + ) + } + switch (requestedMessage) { + case OCPP16MessageTrigger.BootNotification: + chargingStation.ocppRequestService + .requestHandler( + chargingStation, + OCPP16RequestCommand.BOOT_NOTIFICATION, + chargingStation.bootNotificationRequest, + { skipBufferingOnError: true, triggerMessage: true } ) - }) + .then(response => { + chargingStation.bootNotificationResponse = response + }) + .catch(errorHandler) + break + case OCPP16MessageTrigger.Heartbeat: + chargingStation.ocppRequestService + .requestHandler( + chargingStation, + OCPP16RequestCommand.HEARTBEAT, + undefined, + { + triggerMessage: true + } + ) + .catch(errorHandler) + break + case OCPP16MessageTrigger.StatusNotification: + if (connectorId != null) { + chargingStation.ocppRequestService + .requestHandler( + chargingStation, + OCPP16RequestCommand.STATUS_NOTIFICATION, + { + connectorId, + errorCode: OCPP16ChargePointErrorCode.NO_ERROR, + status: chargingStation.getConnectorStatus(connectorId)?.status + }, + { + triggerMessage: true + } + ) + .catch(errorHandler) + } else if (chargingStation.hasEvses) { + for (const evseStatus of chargingStation.evses.values()) { + for (const [id, connectorStatus] of evseStatus.connectors) { + chargingStation.ocppRequestService + .requestHandler< + OCPP16StatusNotificationRequest, + OCPP16StatusNotificationResponse + >( + chargingStation, + OCPP16RequestCommand.STATUS_NOTIFICATION, + { + connectorId: id, + errorCode: OCPP16ChargePointErrorCode.NO_ERROR, + status: connectorStatus.status + }, + { + triggerMessage: true + } + ) + .catch(errorHandler) + } + } + } else { + for (const [id, connectorStatus] of chargingStation.connectors) { + chargingStation.ocppRequestService + .requestHandler< + OCPP16StatusNotificationRequest, + OCPP16StatusNotificationResponse + >( + chargingStation, + OCPP16RequestCommand.STATUS_NOTIFICATION, + { + connectorId: id, + errorCode: OCPP16ChargePointErrorCode.NO_ERROR, + status: connectorStatus.status + }, + { + triggerMessage: true + } + ) + .catch(errorHandler) + } + } + break + } } ) this.validatePayload = this.validatePayload.bind(this) @@ -479,10 +628,12 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { this.validatePayload(chargingStation, commandName, commandPayload) // Call the method to build the response // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - response = (await this.incomingRequestHandlers.get(commandName)!( - chargingStation, - commandPayload - )) as ResType + const incomingRequestHandler = this.incomingRequestHandlers.get(commandName)! + if (isAsyncFunction(incomingRequestHandler)) { + response = (await incomingRequestHandler(chargingStation, commandPayload)) as ResType + } else { + response = incomingRequestHandler(chargingStation, commandPayload) as ResType + } } catch (error) { // Log logger.error( @@ -495,7 +646,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { // Throw exception throw new OCPPError( ErrorType.NOT_IMPLEMENTED, - `${commandName} is not implemented to handle request PDU ${JSON.stringify( + `'${commandName}' is not implemented to handle request PDU ${JSON.stringify( commandPayload, undefined, 2 @@ -511,7 +662,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { commandPayload, undefined, 2 - )} while the charging station is not registered on the central server.`, + )} while the charging station is not registered on the central server`, commandName, commandPayload ) @@ -523,6 +674,8 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { response, commandName ) + // Emit command name event to allow delayed handling + this.emit(commandName, chargingStation, commandPayload, response) } private validatePayload ( @@ -1046,11 +1199,8 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { idTag ) } - this.emit( - OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION, - chargingStation, - transactionConnectorId, - idTag + logger.debug( + `${chargingStation.logPrefix()} Remote start transaction ACCEPTED on connector id ${transactionConnectorId}, idTag '${idTag}'` ) return OCPP16Constants.OCPP_RESPONSE_ACCEPTED } @@ -1068,7 +1218,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ChargePointStatus.Available ) } - logger.warn( + logger.debug( `${chargingStation.logPrefix()} Remote start transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'` ) return OCPP16Constants.OCPP_RESPONSE_REJECTED @@ -1087,7 +1237,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ) return true } - logger.warn( + logger.debug( `${chargingStation.logPrefix()} Not allowed to set ${ chargingProfile.chargingProfilePurpose } charging profile(s) at remote start transaction` @@ -1095,33 +1245,19 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { return false } - private async handleRequestRemoteStopTransaction ( + private handleRequestRemoteStopTransaction ( chargingStation: ChargingStation, commandPayload: RemoteStopTransactionRequest - ): Promise { + ): GenericResponse { const { transactionId } = commandPayload - if (chargingStation.hasEvses) { - for (const [evseId, evseStatus] of chargingStation.evses) { - if (evseId > 0) { - for (const [connectorId, connectorStatus] of evseStatus.connectors) { - if (connectorStatus.transactionId === transactionId) { - return await OCPP16ServiceUtils.remoteStopTransaction(chargingStation, connectorId) - } - } - } - } - } else { - for (const connectorId of chargingStation.connectors.keys()) { - if ( - connectorId > 0 && - chargingStation.getConnectorStatus(connectorId)?.transactionId === transactionId - ) { - return await OCPP16ServiceUtils.remoteStopTransaction(chargingStation, connectorId) - } - } + if (chargingStation.getConnectorIdByTransactionId(transactionId) != null) { + logger.debug( + `${chargingStation.logPrefix()} Remote stop transaction ACCEPTED for transactionId '${transactionId}'` + ) + return OCPP16Constants.OCPP_RESPONSE_ACCEPTED } - logger.warn( - `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}` + logger.debug( + `${chargingStation.logPrefix()} Remote stop transaction REJECTED for transactionId '${transactionId}'` ) return OCPP16Constants.OCPP_RESPONSE_REJECTED } @@ -1332,14 +1468,19 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (uri.protocol.startsWith('ftp:')) { let ftpClient: Client | undefined try { + const logConfiguration = Configuration.getConfigurationSection( + ConfigurationSection.log + ) const logFiles = readdirSync(resolve(dirname(fileURLToPath(import.meta.url)), '../')) - .filter(file => file.endsWith('.log')) - .map(file => join('./', file)) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + .filter(file => file.endsWith(extname(logConfiguration.file!))) + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + .map(file => join(dirname(logConfiguration.file!), file)) const diagnosticsArchive = `${chargingStation.stationInfo?.chargingStationId}_logs.tar.gz` create({ gzip: true }, logFiles).pipe(createWriteStream(diagnosticsArchive)) ftpClient = new Client() const accessResponse = await ftpClient.access({ - host: uri.host, + host: uri.hostname, ...(isNotEmptyString(uri.port) && { port: convertToInt(uri.port) }), ...(isNotEmptyString(uri.username) && { user: uri.username }), ...(isNotEmptyString(uri.password) && { password: uri.password }) @@ -1450,110 +1591,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ) { return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED } - try { - switch (requestedMessage) { - case OCPP16MessageTrigger.BootNotification: - setTimeout(() => { - chargingStation.ocppRequestService - .requestHandler( - chargingStation, - OCPP16RequestCommand.BOOT_NOTIFICATION, - chargingStation.bootNotificationRequest, - { skipBufferingOnError: true, triggerMessage: true } - ) - .then(response => { - chargingStation.bootNotificationResponse = response - }) - .catch(Constants.EMPTY_FUNCTION) - }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY) - return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED - case OCPP16MessageTrigger.Heartbeat: - setTimeout(() => { - chargingStation.ocppRequestService - .requestHandler( - chargingStation, - OCPP16RequestCommand.HEARTBEAT, - undefined, - { - triggerMessage: true - } - ) - .catch(Constants.EMPTY_FUNCTION) - }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY) - return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED - case OCPP16MessageTrigger.StatusNotification: - setTimeout(() => { - if (connectorId != null) { - chargingStation.ocppRequestService - .requestHandler( - chargingStation, - OCPP16RequestCommand.STATUS_NOTIFICATION, - { - connectorId, - errorCode: OCPP16ChargePointErrorCode.NO_ERROR, - status: chargingStation.getConnectorStatus(connectorId)?.status - }, - { - triggerMessage: true - } - ) - .catch(Constants.EMPTY_FUNCTION) - } else if (chargingStation.hasEvses) { - for (const evseStatus of chargingStation.evses.values()) { - for (const [id, connectorStatus] of evseStatus.connectors) { - chargingStation.ocppRequestService - .requestHandler< - OCPP16StatusNotificationRequest, - OCPP16StatusNotificationResponse - >( - chargingStation, - OCPP16RequestCommand.STATUS_NOTIFICATION, - { - connectorId: id, - errorCode: OCPP16ChargePointErrorCode.NO_ERROR, - status: connectorStatus.status - }, - { - triggerMessage: true - } - ) - .catch(Constants.EMPTY_FUNCTION) - } - } - } else { - for (const [id, connectorStatus] of chargingStation.connectors) { - chargingStation.ocppRequestService - .requestHandler< - OCPP16StatusNotificationRequest, - OCPP16StatusNotificationResponse - >( - chargingStation, - OCPP16RequestCommand.STATUS_NOTIFICATION, - { - connectorId: id, - errorCode: OCPP16ChargePointErrorCode.NO_ERROR, - status: connectorStatus.status - }, - { - triggerMessage: true - } - ) - .catch(Constants.EMPTY_FUNCTION) - } - } - }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY) - return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED - default: - return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED - } - } catch (error) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return this.handleIncomingRequestError( - chargingStation, - OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, - error as Error, - { errorResponse: OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED } - )! + switch (requestedMessage) { + case OCPP16MessageTrigger.BootNotification: + case OCPP16MessageTrigger.Heartbeat: + case OCPP16MessageTrigger.StatusNotification: + return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED + default: + return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED } }