X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2Focpp%2F1.6%2FOCPP16IncomingRequestService.ts;h=c870fbc14107624b0f942a09e5c9430c6e3144d6;hb=6c1761d470507ea23d186be61b94ca7375c5144a;hp=45f3723c5a3b7db22aa6fbc4cff2f1db4853d417;hpb=08f130a055123f5e47c59e1a64875f8cff44d020;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 45f3723c..c870fbc1 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -1,5 +1,30 @@ // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. +import fs from 'fs'; +import path from 'path'; +import { URL, fileURLToPath } from 'url'; + +import type { JSONSchemaType } from 'ajv'; +import { Client, FTPResponse } from 'basic-ftp'; +import tar from 'tar'; + +import OCPPError from '../../../exception/OCPPError'; +import type { JsonObject, JsonType } from '../../../types/JsonType'; +import { OCPP16ChargePointErrorCode } from '../../../types/ocpp/1.6/ChargePointErrorCode'; +import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus'; +import { + ChargingProfilePurposeType, + OCPP16ChargingProfile, +} from '../../../types/ocpp/1.6/ChargingProfile'; +import { + OCPP16StandardParametersKey, + OCPP16SupportedFeatureProfiles, +} from '../../../types/ocpp/1.6/Configuration'; +import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus'; +import type { + OCPP16MeterValuesRequest, + OCPP16MeterValuesResponse, +} from '../../../types/ocpp/1.6/MeterValues'; import { ChangeAvailabilityRequest, ChangeConfigurationRequest, @@ -10,6 +35,7 @@ import { MessageTrigger, OCPP16AvailabilityType, OCPP16BootNotificationRequest, + OCPP16ClearCacheRequest, OCPP16HeartbeatRequest, OCPP16IncomingRequestCommand, OCPP16RequestCommand, @@ -21,7 +47,7 @@ import { SetChargingProfileRequest, UnlockConnectorRequest, } from '../../../types/ocpp/1.6/Requests'; -import { +import type { ChangeAvailabilityResponse, ChangeConfigurationResponse, ClearChargingProfileResponse, @@ -35,11 +61,6 @@ import { SetChargingProfileResponse, UnlockConnectorResponse, } from '../../../types/ocpp/1.6/Responses'; -import { - ChargingProfilePurposeType, - OCPP16ChargingProfile, -} from '../../../types/ocpp/1.6/ChargingProfile'; -import { Client, FTPResponse } from 'basic-ftp'; import { OCPP16AuthorizationStatus, OCPP16AuthorizeRequest, @@ -50,39 +71,24 @@ import { OCPP16StopTransactionRequest, OCPP16StopTransactionResponse, } from '../../../types/ocpp/1.6/Transaction'; -import { - OCPP16MeterValuesRequest, - OCPP16MeterValuesResponse, -} from '../../../types/ocpp/1.6/MeterValues'; -import { - OCPP16StandardParametersKey, - OCPP16SupportedFeatureProfiles, -} from '../../../types/ocpp/1.6/Configuration'; - -import type ChargingStation from '../../ChargingStation'; -import Constants from '../../../utils/Constants'; -import { DefaultResponse } from '../../../types/ocpp/Responses'; +import type { OCPPConfigurationKey } from '../../../types/ocpp/Configuration'; import { ErrorType } from '../../../types/ocpp/ErrorType'; -import { IncomingRequestHandler } from '../../../types/ocpp/Requests'; -import { JsonType } from '../../../types/JsonType'; -import { OCPP16ChargePointErrorCode } from '../../../types/ocpp/1.6/ChargePointErrorCode'; -import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus'; -import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus'; -import { OCPP16ServiceUtils } from './OCPP16ServiceUtils'; -import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration'; -import OCPPError from '../../../exception/OCPPError'; -import OCPPIncomingRequestService from '../OCPPIncomingRequestService'; -import { URL } from 'url'; -import Utils from '../../../utils/Utils'; -import fs from 'fs'; +import type { IncomingRequestHandler } from '../../../types/ocpp/Requests'; +import type { DefaultResponse } from '../../../types/ocpp/Responses'; +import Constants from '../../../utils/Constants'; import logger from '../../../utils/Logger'; -import path from 'path'; -import tar from 'tar'; +import Utils from '../../../utils/Utils'; +import type ChargingStation from '../../ChargingStation'; +import { ChargingStationConfigurationUtils } from '../../ChargingStationConfigurationUtils'; +import { ChargingStationUtils } from '../../ChargingStationUtils'; +import OCPPIncomingRequestService from '../OCPPIncomingRequestService'; +import { OCPP16ServiceUtils } from './OCPP16ServiceUtils'; const moduleName = 'OCPP16IncomingRequestService'; export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private incomingRequestHandlers: Map; + private jsonSchemas: Map>; public constructor() { if (new.target?.name === moduleName) { @@ -124,6 +130,153 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer [OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, this.handleRequestGetDiagnostics.bind(this)], [OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, this.handleRequestTriggerMessage.bind(this)], ]); + this.jsonSchemas = new Map>([ + [ + OCPP16IncomingRequestCommand.RESET, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/Reset.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.CLEAR_CACHE, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/ClearCache.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.GET_CONFIGURATION, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + [ + OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, + JSON.parse( + fs.readFileSync( + path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json' + ), + 'utf8' + ) + ) as JSONSchemaType, + ], + ]); + this.validatePayload.bind(this); } public async incomingRequestHandler( @@ -141,20 +294,25 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer ) { throw new OCPPError( ErrorType.SECURITY_ERROR, - `${commandName} cannot be issued to handle request payload ${JSON.stringify( + `${commandName} cannot be issued to handle request PDU ${JSON.stringify( commandPayload, null, 2 )} while the charging station is in pending state on the central server`, - commandName + commandName, + commandPayload ); } if ( chargingStation.isRegistered() || (!chargingStation.getOcppStrictCompliance() && chargingStation.isInUnknownState()) ) { - if (this.incomingRequestHandlers.has(commandName)) { + if ( + this.incomingRequestHandlers.has(commandName) && + ChargingStationUtils.isIncomingRequestCommandSupported(commandName, chargingStation) + ) { try { + this.validatePayload(chargingStation, commandName, commandPayload); // Call the method to build the response response = await this.incomingRequestHandlers.get(commandName)( chargingStation, @@ -162,30 +320,35 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer ); } catch (error) { // Log - logger.error(chargingStation.logPrefix() + ' Handle request error: %j', error); + logger.error( + `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`, + error + ); throw error; } } else { // Throw exception throw new OCPPError( ErrorType.NOT_IMPLEMENTED, - `${commandName} is not implemented to handle request payload ${JSON.stringify( + `${commandName} is not implemented to handle request PDU ${JSON.stringify( commandPayload, null, 2 )}`, - commandName + commandName, + commandPayload ); } } else { throw new OCPPError( ErrorType.SECURITY_ERROR, - `${commandName} cannot be issued to handle request payload ${JSON.stringify( + `${commandName} cannot be issued to handle request PDU ${JSON.stringify( commandPayload, null, 2 )} while the charging station is not registered on the central server.`, - commandName + commandName, + commandPayload ); } // Send the built response @@ -197,6 +360,25 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer ); } + private validatePayload( + chargingStation: ChargingStation, + commandName: OCPP16IncomingRequestCommand, + commandPayload: JsonType + ): boolean { + if (this.jsonSchemas.has(commandName)) { + return this.validateIncomingRequestPayload( + chargingStation, + commandName, + this.jsonSchemas.get(commandName), + commandPayload + ); + } + logger.warn( + `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation` + ); + return false; + } + // Simulate charging station restart private handleRequestReset( chargingStation: ChargingStation, @@ -250,7 +432,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer >(chargingStation, OCPP16RequestCommand.METER_VALUES, { connectorId, transactionId, - meterValue: transactionEndMeterValue, + meterValue: [transactionEndMeterValue], }); } const stopResponse = await chargingStation.ocppRequestService.requestHandler< @@ -301,7 +483,10 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer } } else { for (const key of commandPayload.key) { - const keyFound = chargingStation.getConfigurationKey(key); + const keyFound = ChargingStationConfigurationUtils.getConfigurationKey( + chargingStation, + key + ); if (keyFound) { if (Utils.isUndefined(keyFound.visible)) { keyFound.visible = true; @@ -329,24 +514,11 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer chargingStation: ChargingStation, commandPayload: ChangeConfigurationRequest ): ChangeConfigurationResponse { - // JSON request fields type sanity check - if (!Utils.isString(commandPayload.key)) { - logger.error( - `${chargingStation.logPrefix()} ${ - OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION - } request key field is not a string:`, - commandPayload - ); - } - if (!Utils.isString(commandPayload.value)) { - logger.error( - `${chargingStation.logPrefix()} ${ - OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION - } request value field is not a string:`, - commandPayload - ); - } - const keyToChange = chargingStation.getConfigurationKey(commandPayload.key, true); + const keyToChange = ChargingStationConfigurationUtils.getConfigurationKey( + chargingStation, + commandPayload.key, + true + ); if (!keyToChange) { return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED; } else if (keyToChange && keyToChange.readonly) { @@ -354,19 +526,26 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer } else if (keyToChange && !keyToChange.readonly) { let valueChanged = false; if (keyToChange.value !== commandPayload.value) { - chargingStation.setConfigurationKeyValue(commandPayload.key, commandPayload.value, true); + ChargingStationConfigurationUtils.setConfigurationKeyValue( + chargingStation, + commandPayload.key, + commandPayload.value, + true + ); valueChanged = true; } let triggerHeartbeatRestart = false; if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) { - chargingStation.setConfigurationKeyValue( + ChargingStationConfigurationUtils.setConfigurationKeyValue( + chargingStation, OCPP16StandardParametersKey.HeartbeatInterval, commandPayload.value ); triggerHeartbeatRestart = true; } if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) { - chargingStation.setConfigurationKeyValue( + ChargingStationConfigurationUtils.setConfigurationKeyValue( + chargingStation, OCPP16StandardParametersKey.HeartBeatInterval, commandPayload.value ); @@ -496,7 +675,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer clearCurrentCP = true; } if (clearCurrentCP) { - connectorStatus.chargingProfiles[index] = {} as OCPP16ChargingProfile; + connectorStatus.chargingProfiles.splice(index, 1); logger.debug( `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${ commandPayload.connectorId @@ -599,7 +778,11 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer if ( chargingStation.getLocalAuthListEnabled() && chargingStation.hasAuthorizedTags() && - chargingStation.authorizedTags.find((value) => value === commandPayload.idTag) + chargingStation.authorizedTagsCache + .getAuthorizedTags( + ChargingStationUtils.getAuthorizationFile(chargingStation.stationInfo) + ) + .find((value) => value === commandPayload.idTag) ) { connectorStatus.localAuthorizeIdTag = commandPayload.idTag; connectorStatus.idTagLocalAuthorized = true; @@ -819,7 +1002,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer >(chargingStation, OCPP16RequestCommand.METER_VALUES, { connectorId, transactionId, - meterValue: transactionEndMeterValue, + meterValue: [transactionEndMeterValue], }); } await chargingStation.ocppRequestService.requestHandler< @@ -833,7 +1016,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer return Constants.OCPP_RESPONSE_ACCEPTED; } } - logger.info( + logger.warn( chargingStation.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString() @@ -866,7 +1049,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer let ftpClient: Client; try { const logFiles = fs - .readdirSync(path.resolve(__dirname, '../../../../')) + .readdirSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../')) .filter((file) => file.endsWith('.log')) .map((file) => path.join('./', file)); const diagnosticsArchive = chargingStation.stationInfo.chargingStationId + '_logs.tar.gz'; @@ -895,7 +1078,10 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer }); }); uploadResponse = await ftpClient.uploadFrom( - path.join(path.resolve(__dirname, '../../../../'), diagnosticsArchive), + path.join( + path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../'), + diagnosticsArchive + ), uri.pathname + diagnosticsArchive ); if (uploadResponse.code === 226) {