X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Focpp%2F1.6%2FOCPP16ResponseService.ts;h=0af8ad16f046f80318a8f47beb09c1606e95be2f;hb=b2a0452d368cfc43bbacc4991de59afa64f662a4;hp=984cb1b34c09ab53bfe90d518d9c2e86b8c55b3a;hpb=9c5c4195dabbbe1481553a495e3c54c70aef9aa5;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts index 984cb1b3..0af8ad16 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts @@ -1,54 +1,75 @@ -// Partial Copyright Jerome Benoit. 2021. All Rights Reserved. +// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; -import { JSONSchemaType } from 'ajv'; +import type { JSONSchemaType } from 'ajv'; +import { OCPP16ServiceUtils } from './OCPP16ServiceUtils'; import OCPPError from '../../../exception/OCPPError'; -import { JsonObject, JsonType } from '../../../types/JsonType'; +import type { JsonObject, JsonType } from '../../../types/JsonType'; import { OCPP16ChargePointErrorCode } from '../../../types/ocpp/1.6/ChargePointErrorCode'; import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus'; import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration'; -import { +import type { OCPP16MeterValuesRequest, OCPP16MeterValuesResponse, } from '../../../types/ocpp/1.6/MeterValues'; import { - OCPP16BootNotificationRequest, + type OCPP16BootNotificationRequest, + OCPP16IncomingRequestCommand, OCPP16RequestCommand, - OCPP16StatusNotificationRequest, + type OCPP16StatusNotificationRequest, } from '../../../types/ocpp/1.6/Requests'; -import { - DiagnosticsStatusNotificationResponse, +import type { + ChangeAvailabilityResponse, + ChangeConfigurationResponse, + ClearChargingProfileResponse, + GetConfigurationResponse, + GetDiagnosticsResponse, OCPP16BootNotificationResponse, + OCPP16DataTransferResponse, + OCPP16DiagnosticsStatusNotificationResponse, + OCPP16FirmwareStatusNotificationResponse, OCPP16HeartbeatResponse, - OCPP16RegistrationStatus, OCPP16StatusNotificationResponse, + OCPP16TriggerMessageResponse, + OCPP16UpdateFirmwareResponse, + SetChargingProfileResponse, + UnlockConnectorResponse, } from '../../../types/ocpp/1.6/Responses'; import { OCPP16AuthorizationStatus, - OCPP16AuthorizeRequest, - OCPP16AuthorizeResponse, - OCPP16StartTransactionRequest, - OCPP16StartTransactionResponse, - OCPP16StopTransactionRequest, - OCPP16StopTransactionResponse, + type OCPP16AuthorizeRequest, + type OCPP16AuthorizeResponse, + type OCPP16StartTransactionRequest, + type OCPP16StartTransactionResponse, + type OCPP16StopTransactionRequest, + type OCPP16StopTransactionResponse, } from '../../../types/ocpp/1.6/Transaction'; import { ErrorType } from '../../../types/ocpp/ErrorType'; -import { ResponseHandler } from '../../../types/ocpp/Responses'; +import { OCPPVersion } from '../../../types/ocpp/OCPPVersion'; +import { + type GenericResponse, + RegistrationStatusEnumType, + type ResponseHandler, +} from '../../../types/ocpp/Responses'; +import Constants from '../../../utils/Constants'; import logger from '../../../utils/Logger'; import Utils from '../../../utils/Utils'; import type ChargingStation from '../../ChargingStation'; import { ChargingStationConfigurationUtils } from '../../ChargingStationConfigurationUtils'; -import { ChargingStationUtils } from '../../ChargingStationUtils'; import OCPPResponseService from '../OCPPResponseService'; -import { OCPP16ServiceUtils } from './OCPP16ServiceUtils'; const moduleName = 'OCPP16ResponseService'; export default class OCPP16ResponseService extends OCPPResponseService { + public jsonIncomingRequestResponseSchemas: Map< + OCPP16IncomingRequestCommand, + JSONSchemaType + >; + private responseHandlers: Map; private jsonSchemas: Map>; @@ -56,7 +77,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { if (new.target?.name === moduleName) { throw new TypeError(`Cannot construct ${new.target?.name} instances directly`); } - super(); + super(OCPPVersion.VERSION_16); this.responseHandlers = new Map([ [OCPP16RequestCommand.BOOT_NOTIFICATION, this.handleResponseBootNotification.bind(this)], [OCPP16RequestCommand.HEARTBEAT, this.emptyResponseHandler.bind(this)], @@ -66,105 +87,158 @@ export default class OCPP16ResponseService extends OCPPResponseService { [OCPP16RequestCommand.STATUS_NOTIFICATION, this.emptyResponseHandler.bind(this)], [OCPP16RequestCommand.METER_VALUES, this.emptyResponseHandler.bind(this)], [OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, this.emptyResponseHandler.bind(this)], + [OCPP16RequestCommand.DATA_TRANSFER, this.emptyResponseHandler.bind(this)], + [OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, this.emptyResponseHandler.bind(this)], ]); this.jsonSchemas = new Map>([ [ OCPP16RequestCommand.BOOT_NOTIFICATION, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/BootNotificationResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/BootNotificationResponse.json' + ), ], [ OCPP16RequestCommand.HEARTBEAT, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/HeartbeatResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/HeartbeatResponse.json' + ), ], [ OCPP16RequestCommand.AUTHORIZE, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/AuthorizeResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/AuthorizeResponse.json' + ), ], [ OCPP16RequestCommand.START_TRANSACTION, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/StartTransactionResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/StartTransactionResponse.json' + ), ], [ OCPP16RequestCommand.STOP_TRANSACTION, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/StopTransactionResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/StopTransactionResponse.json' + ), ], [ OCPP16RequestCommand.STATUS_NOTIFICATION, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json' + ), ], [ OCPP16RequestCommand.METER_VALUES, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/MeterValuesResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/MeterValuesResponse.json' + ), ], [ OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, - JSON.parse( - fs.readFileSync( - path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json' - ), - 'utf8' - ) - ) as JSONSchemaType, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json' + ), + ], + [ + OCPP16RequestCommand.DATA_TRANSFER, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/DataTransferResponse.json' + ), + ], + [ + OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json' + ), ], ]); + this.jsonIncomingRequestResponseSchemas = new Map([ + [ + OCPP16IncomingRequestCommand.RESET, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/ResetResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.CLEAR_CACHE, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/ClearCacheResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.GET_CONFIGURATION, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.DATA_TRANSFER, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/DataTransferResponse.json' + ), + ], + [ + OCPP16IncomingRequestCommand.UPDATE_FIRMWARE, + this.parseJsonSchemaFile( + '../../../assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json' + ), + ], + ]); + this.validatePayload.bind(this); } public async responseHandler( @@ -173,23 +247,29 @@ export default class OCPP16ResponseService extends OCPPResponseService { payload: JsonType, requestPayload: JsonType ): Promise { - if (chargingStation.isRegistered() || commandName === OCPP16RequestCommand.BOOT_NOTIFICATION) { + if ( + chargingStation.isRegistered() === true || + commandName === OCPP16RequestCommand.BOOT_NOTIFICATION + ) { if ( - this.responseHandlers.has(commandName) && - ChargingStationUtils.isRequestCommandSupported(commandName, chargingStation) + this.responseHandlers.has(commandName) === true && + OCPP16ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true ) { try { this.validatePayload(chargingStation, commandName, payload); await this.responseHandlers.get(commandName)(chargingStation, payload, requestPayload); } catch (error) { - logger.error(chargingStation.logPrefix() + ' Handle request response error: %j', error); + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`, + error + ); throw error; } } else { // Throw exception throw new OCPPError( ErrorType.NOT_IMPLEMENTED, - `${commandName} is not implemented to handle request response PDU ${JSON.stringify( + `${commandName} is not implemented to handle response PDU ${JSON.stringify( payload, null, 2 @@ -201,11 +281,11 @@ export default class OCPP16ResponseService extends OCPPResponseService { } else { throw new OCPPError( ErrorType.SECURITY_ERROR, - `${commandName} cannot be issued to handle request response PDU ${JSON.stringify( + `${commandName} cannot be issued to handle response PDU ${JSON.stringify( payload, null, 2 - )} while the charging station is not registered on the central server. `, + )} while the charging station is not registered on the central server.`, commandName, payload ); @@ -217,7 +297,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { commandName: OCPP16RequestCommand, payload: JsonType ): boolean { - if (this.jsonSchemas.has(commandName)) { + if (this.jsonSchemas.has(commandName) === true) { return this.validateResponsePayload( chargingStation, commandName, @@ -226,7 +306,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { ); } logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.responseHandler: No JSON schema found for command ${commandName} PDU validation` + `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation` ); return false; } @@ -235,7 +315,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { chargingStation: ChargingStation, payload: OCPP16BootNotificationResponse ): void { - if (payload.status === OCPP16RegistrationStatus.ACCEPTED) { + if (payload.status === RegistrationStatusEnumType.ACCEPTED) { ChargingStationConfigurationUtils.addConfigurationKey( chargingStation, OCPP16StandardParametersKey.HeartbeatInterval, @@ -254,11 +334,11 @@ export default class OCPP16ResponseService extends OCPPResponseService { ? chargingStation.restartHeartbeat() : chargingStation.startHeartbeat(); } - if (Object.values(OCPP16RegistrationStatus).includes(payload.status)) { + if (Object.values(RegistrationStatusEnumType).includes(payload.status)) { const logMsg = `${chargingStation.logPrefix()} Charging station in '${ payload.status }' state on the central server`; - payload.status === OCPP16RegistrationStatus.REJECTED + payload.status === RegistrationStatusEnumType.REJECTED ? logger.warn(logMsg) : logger.info(logMsg); } else { @@ -285,20 +365,24 @@ export default class OCPP16ResponseService extends OCPPResponseService { break; } } + const isAuthorizeConnectorIdDefined = authorizeConnectorId !== undefined; if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) { - chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = true; + isAuthorizeConnectorIdDefined && + (chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = true); logger.debug( - `${chargingStation.logPrefix()} IdTag ${ - requestPayload.idTag - } authorized on connector ${authorizeConnectorId}` + `${chargingStation.logPrefix()} IdTag '${requestPayload.idTag}' accepted${ + isAuthorizeConnectorIdDefined ? ` on connector ${authorizeConnectorId}` : '' + }` ); } else { - chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = false; - delete chargingStation.getConnectorStatus(authorizeConnectorId).authorizeIdTag; + if (isAuthorizeConnectorIdDefined) { + chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = false; + delete chargingStation.getConnectorStatus(authorizeConnectorId).authorizeIdTag; + } logger.debug( - `${chargingStation.logPrefix()} IdTag ${requestPayload.idTag} refused with status '${ + `${chargingStation.logPrefix()} IdTag '${requestPayload.idTag}' rejected with status '${ payload.idTagInfo.status - }' on connector ${authorizeConnectorId}` + }'${isAuthorizeConnectorIdDefined ? ` on connector ${authorizeConnectorId}` : ''}` ); } } @@ -326,11 +410,11 @@ export default class OCPP16ResponseService extends OCPPResponseService { return; } if ( - chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted && - chargingStation.getAuthorizeRemoteTxRequests() && - chargingStation.getLocalAuthListEnabled() && + chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true && + chargingStation.getAuthorizeRemoteTxRequests() === true && + chargingStation.getLocalAuthListEnabled() === true && chargingStation.hasAuthorizedTags() && - !chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized + chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false ) { logger.error( chargingStation.logPrefix() + @@ -343,11 +427,11 @@ export default class OCPP16ResponseService extends OCPPResponseService { return; } if ( - chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted && - chargingStation.getAuthorizeRemoteTxRequests() && - chargingStation.getMayAuthorizeAtRemoteStart() && - !chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized && - !chargingStation.getConnectorStatus(connectorId).idTagAuthorized + chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true && + chargingStation.getAuthorizeRemoteTxRequests() === true && + chargingStation.getMustAuthorizeAtRemoteStart() === true && + chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false && + chargingStation.getConnectorStatus(connectorId).idTagAuthorized === false ) { logger.error( chargingStation.logPrefix() + @@ -391,7 +475,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { await this.resetConnectorOnStartTransactionError(chargingStation, connectorId); return; } - if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted) { + if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) { logger.debug( chargingStation.logPrefix() + ' Trying to start a transaction on an already used connector ' + @@ -413,14 +497,14 @@ export default class OCPP16ResponseService extends OCPPResponseService { ); return; } - if (!Number.isInteger(payload.transactionId)) { - logger.warn( - `${chargingStation.logPrefix()} Trying to start a transaction on connector ${connectorId.toString()} with a non integer transaction Id ${ - payload.transactionId - }, converting to integer` - ); - payload.transactionId = Utils.convertToInt(payload.transactionId); - } + // if (!Number.isInteger(payload.transactionId)) { + // logger.warn( + // `${chargingStation.logPrefix()} Trying to start a transaction on connector ${connectorId.toString()} with a non integer transaction Id ${ + // payload.transactionId + // }, converting to integer` + // ); + // payload.transactionId = Utils.convertToInt(payload.transactionId); + // } if (payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) { chargingStation.getConnectorStatus(connectorId).transactionStarted = true; @@ -461,8 +545,9 @@ export default class OCPP16ResponseService extends OCPPResponseService { chargingStation.stationInfo.chargingStationId + '#' + connectorId.toString() + - ' for idTag ' + - requestPayload.idTag + " for idTag '" + + requestPayload.idTag + + "'" ); if (chargingStation.stationInfo.powerSharedByConnectors) { chargingStation.powerDivider++; @@ -476,7 +561,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { connectorId, configuredMeterValueSampleInterval ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000 - : 60000 + : Constants.DEFAULT_METER_VALUES_INTERVAL ); } else { logger.warn( @@ -485,8 +570,9 @@ export default class OCPP16ResponseService extends OCPPResponseService { payload.transactionId.toString() + " REJECTED with status '" + payload?.idTagInfo?.status + - "', idTag " + - requestPayload.idTag + "', idTag '" + + requestPayload.idTag + + "'" ); await this.resetConnectorOnStartTransactionError(chargingStation, connectorId); } @@ -529,9 +615,9 @@ export default class OCPP16ResponseService extends OCPPResponseService { return; } if (payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) { - chargingStation.getBeginEndMeterValues() && - !chargingStation.getOcppStrictCompliance() && - chargingStation.getOutOfOrderEndMeterValues() && + chargingStation.getBeginEndMeterValues() === true && + chargingStation.getOcppStrictCompliance() === false && + chargingStation.getOutOfOrderEndMeterValues() === true && (await chargingStation.ocppRequestService.requestHandler< OCPP16MeterValuesRequest, OCPP16MeterValuesResponse @@ -547,8 +633,8 @@ export default class OCPP16ResponseService extends OCPPResponseService { ], })); if ( - !chargingStation.isChargingStationAvailable() || - !chargingStation.isConnectorAvailable(transactionConnectorId) + chargingStation.isChargingStationAvailable() === false || + chargingStation.isConnectorAvailable(transactionConnectorId) === false ) { await chargingStation.ocppRequestService.requestHandler< OCPP16StatusNotificationRequest, @@ -575,6 +661,7 @@ export default class OCPP16ResponseService extends OCPPResponseService { if (chargingStation.stationInfo.powerSharedByConnectors) { chargingStation.powerDivider--; } + chargingStation.resetConnectorStatus(transactionConnectorId); logger.info( chargingStation.logPrefix() + ' Transaction ' + @@ -584,7 +671,6 @@ export default class OCPP16ResponseService extends OCPPResponseService { '#' + transactionConnectorId.toString() ); - chargingStation.resetConnectorStatus(transactionConnectorId); } else { logger.warn( chargingStation.logPrefix() + @@ -596,4 +682,13 @@ export default class OCPP16ResponseService extends OCPPResponseService { ); } } + + private parseJsonSchemaFile(relativePath: string): JSONSchemaType { + return JSON.parse( + fs.readFileSync( + path.resolve(path.dirname(fileURLToPath(import.meta.url)), relativePath), + 'utf8' + ) + ) as JSONSchemaType; + } }