X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=90b788a68b83235e599c843139ef79406a610bb9;hb=00db15b822b3f26f67fb36094daf7bd206c96fc2;hp=cc0fd47f2ab9edd15f41d7202a1a4b0bab24cb38;hpb=a59737e33418e805972d57d8f52aa3bc0f28d51e;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index cc0fd47f..90b788a6 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -8,7 +8,13 @@ import { IncomingRequestCommand, RequestCommand, } from '../types/ocpp/Requests'; -import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses'; +import { + BootNotificationResponse, + HeartbeatResponse, + MeterValuesResponse, + RegistrationStatus, + StatusNotificationResponse, +} from '../types/ocpp/Responses'; import ChargingStationConfiguration, { ConfigurationKey, } from '../types/ChargingStationConfiguration'; @@ -24,6 +30,7 @@ import { VendorDefaultParametersKey, } from '../types/ocpp/Configuration'; import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues'; +import { StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction'; import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket'; import WebSocket, { ClientOptions, Data, OPEN, RawData } from 'ws'; @@ -52,7 +59,6 @@ import OCPPRequestService from './ocpp/OCPPRequestService'; import { OCPPVersion } from '../types/ocpp/OCPPVersion'; import PerformanceStatistics from '../performance/PerformanceStatistics'; import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates'; -import { StopTransactionReason } from '../types/ocpp/Transaction'; import { SupervisionUrlDistribution } from '../types/ConfigurationData'; import { URL } from 'url'; import Utils from '../utils/Utils'; @@ -63,7 +69,7 @@ import { parentPort } from 'worker_threads'; import path from 'path'; export default class ChargingStation { - public readonly id: string; + public hashId!: string; public readonly stationTemplateFile: string; public authorizedTags: string[]; public stationInfo!: ChargingStationInfo; @@ -74,10 +80,10 @@ export default class ChargingStation { public performanceStatistics!: PerformanceStatistics; public heartbeatSetInterval!: NodeJS.Timeout; public ocppRequestService!: OCPPRequestService; + public bootNotificationResponse!: BootNotificationResponse | null; private readonly index: number; private configurationFile!: string; private bootNotificationRequest!: BootNotificationRequest; - private bootNotificationResponse!: BootNotificationResponse | null; private connectorsConfigurationHash!: string; private ocppIncomingRequestService!: OCPPIncomingRequestService; private readonly messageBuffer: Set; @@ -89,7 +95,6 @@ export default class ChargingStation { private webSocketPingSetInterval!: NodeJS.Timeout; constructor(index: number, stationTemplateFile: string) { - this.id = Utils.generateUUID(); this.index = index; this.stationTemplateFile = stationTemplateFile; this.stopped = false; @@ -102,7 +107,7 @@ export default class ChargingStation { this.authorizedTags = this.getAuthorizedTags(); } - get wsConnectionUrl(): URL { + private get wsConnectionUrl(): URL { return this.getSupervisionUrlOcppConfiguration() ? new URL( this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value + @@ -396,7 +401,9 @@ export default class ChargingStation { ) { // eslint-disable-next-line @typescript-eslint/no-misused-promises this.heartbeatSetInterval = setInterval(async (): Promise => { - await this.ocppRequestService.sendMessageHandler(RequestCommand.HEARTBEAT); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.HEARTBEAT + ); }, this.getHeartbeatInterval()); logger.info( this.logPrefix() + @@ -466,11 +473,14 @@ export default class ChargingStation { this.getConnectorStatus(connectorId).transactionId, interval ); - await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, { - connectorId, - transactionId: this.getConnectorStatus(connectorId).transactionId, - meterValue: [meterValue], - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.METER_VALUES, + { + connectorId, + transactionId: this.getConnectorStatus(connectorId).transactionId, + meterValue: [meterValue], + } + ); }, interval ); @@ -536,12 +546,6 @@ export default class ChargingStation { } } ); - FileUtils.watchJsonFile( - this.logPrefix(), - FileType.ChargingStationConfiguration, - this.configurationFile, - this.configuration - ); // Handle WebSocket message this.wsConnection.on( 'message', @@ -574,11 +578,14 @@ export default class ChargingStation { await this.stopMessageSequence(reason); for (const connectorId of this.connectors.keys()) { if (connectorId > 0) { - await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: ChargePointStatus.UNAVAILABLE, - errorCode: ChargePointErrorCode.NO_ERROR, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.STATUS_NOTIFICATION, + { + connectorId, + status: ChargePointStatus.UNAVAILABLE, + errorCode: ChargePointErrorCode.NO_ERROR, + } + ); this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE; } } @@ -625,15 +632,12 @@ export default class ChargingStation { reboot: false, }; } - const readonly = options.readonly; - const visible = options.visible; - const reboot = options.reboot; + const readonly = options.readonly ?? false; + const visible = options.visible ?? true; + const reboot = options.reboot ?? false; let keyFound = this.getConfigurationKey(key); if (keyFound && params?.overwrite) { - this.configuration.configurationKey.splice( - this.configuration.configurationKey.indexOf(keyFound), - 1 - ); + this.deleteConfigurationKey(keyFound.key, { save: false }); keyFound = undefined; } if (!keyFound) { @@ -671,6 +675,21 @@ export default class ChargingStation { } } + public deleteConfigurationKey( + key: string | StandardParametersKey, + params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false } + ): ConfigurationKey[] { + const keyFound = this.getConfigurationKey(key, params?.caseInsensitive); + if (keyFound) { + const deletedConfigurationKey = this.configuration.configurationKey.splice( + this.configuration.configurationKey.indexOf(keyFound), + 1 + ); + params?.save && this.saveConfiguration(); + return deletedConfigurationKey; + } + } + public setChargingProfile(connectorId: number, cp: ChargingProfile): void { let cpReplaced = false; if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { @@ -718,14 +737,14 @@ export default class ChargingStation { } } - private getSupervisionUrlOcppKey(): string { - return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; - } - private getSupervisionUrlOcppConfiguration(): boolean { return this.stationInfo.supervisionUrlOcppConfiguration ?? false; } + private getSupervisionUrlOcppKey(): string { + return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; + } + private getChargingStationId(stationTemplate: ChargingStationTemplate): string { // In case of multiple instances: add instance index to charging station id const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; @@ -795,6 +814,10 @@ export default class ChargingStation { return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16; } + private getOcppPersistentConfiguration(): boolean { + return this.stationInfo.ocppPersistentConfiguration ?? true; + } + private handleUnsupportedVersion(version: OCPPVersion) { const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${ this.stationTemplateFile @@ -805,14 +828,6 @@ export default class ChargingStation { private initialize(): void { this.stationInfo = this.buildStationInfo(); - this.configurationFile = path.join( - path.resolve(__dirname, '../'), - 'assets', - 'configurations', - this.stationInfo.chargingStationId + '.json' - ); - this.configuration = this.getConfiguration(); - delete this.stationInfo.Configuration; this.bootNotificationRequest = { chargePointModel: this.stationInfo.chargePointModel, chargePointVendor: this.stationInfo.chargePointVendor, @@ -822,7 +837,29 @@ export default class ChargingStation { ...(!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion, }), + ...(!Utils.isUndefined(this.stationInfo.iccid) && { iccid: this.stationInfo.iccid }), + ...(!Utils.isUndefined(this.stationInfo.imsi) && { imsi: this.stationInfo.imsi }), + ...(!Utils.isUndefined(this.stationInfo.meterSerialNumber) && { + meterSerialNumber: this.stationInfo.meterSerialNumber, + }), + ...(!Utils.isUndefined(this.stationInfo.meterType) && { + meterType: this.stationInfo.meterType, + }), }; + + this.hashId = crypto + .createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update(JSON.stringify(this.bootNotificationRequest) + this.stationInfo.chargingStationId) + .digest('hex'); + logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`); + this.configurationFile = path.join( + path.resolve(__dirname, '../'), + 'assets', + 'configurations', + this.hashId + '.json' + ); + this.configuration = this.getConfiguration(); + delete this.stationInfo.Configuration; // Build connectors if needed const maxConnectors = this.getMaxNumberOfConnectors(); if (maxConnectors <= 0) { @@ -861,7 +898,7 @@ export default class ChargingStation { this.stationInfo.randomConnectors = true; } const connectorsConfigHash = crypto - .createHash('sha256') + .createHash(Constants.DEFAULT_HASH_ALGORITHM) .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()) .digest('hex'); const connectorsConfigChanged = @@ -918,6 +955,8 @@ export default class ChargingStation { this.wsConfiguredConnectionUrl = new URL( this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId ); + // OCPP parameters + this.initOcppParameters(); switch (this.getOcppVersion()) { case OCPPVersion.VERSION_16: this.ocppIncomingRequestService = @@ -931,8 +970,6 @@ export default class ChargingStation { this.handleUnsupportedVersion(this.getOcppVersion()); break; } - // OCPP parameters - this.initOcppParameters(); if (this.stationInfo.autoRegister) { this.bootNotificationResponse = { currentTime: new Date().toISOString(), @@ -943,7 +980,7 @@ export default class ChargingStation { this.stationInfo.powerDivider = this.getPowerDivider(); if (this.getEnableStatistics()) { this.performanceStatistics = PerformanceStatistics.getInstance( - this.id, + this.hashId, this.stationInfo.chargingStationId, this.wsConnectionUrl ); @@ -960,6 +997,11 @@ export default class ChargingStation { this.getConfiguredSupervisionUrl().href, { reboot: true } ); + } else if ( + !this.getSupervisionUrlOcppConfiguration() && + this.getConfigurationKey(this.getSupervisionUrlOcppKey()) + ) { + this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false }); } if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { this.addConfigurationKey( @@ -1025,7 +1067,11 @@ export default class ChargingStation { private getConfigurationFromFile(): ChargingStationConfiguration | null { let configuration: ChargingStationConfiguration = null; - if (this.configurationFile && fs.existsSync(this.configurationFile)) { + if ( + this.getOcppPersistentConfiguration() && + this.configurationFile && + fs.existsSync(this.configurationFile) + ) { try { configuration = JSON.parse( fs.readFileSync(this.configurationFile, 'utf8') @@ -1043,26 +1089,28 @@ export default class ChargingStation { } private saveConfiguration(): void { - if (this.configurationFile) { - try { - if (!fs.existsSync(path.dirname(this.configurationFile))) { - fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); + if (this.getOcppPersistentConfiguration()) { + if (this.configurationFile) { + try { + if (!fs.existsSync(path.dirname(this.configurationFile))) { + fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); + } + const fileDescriptor = fs.openSync(this.configurationFile, 'w'); + fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2)); + fs.closeSync(fileDescriptor); + } catch (error) { + FileUtils.handleFileException( + this.logPrefix(), + FileType.ChargingStationConfiguration, + this.configurationFile, + error as NodeJS.ErrnoException + ); } - const fileDescriptor = fs.openSync(this.configurationFile, 'w'); - fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2)); - fs.closeSync(fileDescriptor); - } catch (error) { - FileUtils.handleFileException( - this.logPrefix(), - FileType.ChargingStationConfiguration, - this.configurationFile, - error as NodeJS.ErrnoException + } else { + logger.error( + `${this.logPrefix()} Trying to save charging station configuration to undefined file` ); } - } else { - logger.error( - `${this.logPrefix()} Trying to save charging station configuration to undefined file` - ); } } @@ -1082,21 +1130,22 @@ export default class ChargingStation { // Send BootNotification let registrationRetryCount = 0; do { - this.bootNotificationResponse = (await this.ocppRequestService.sendMessageHandler( - RequestCommand.BOOT_NOTIFICATION, - { - chargePointModel: this.bootNotificationRequest.chargePointModel, - chargePointVendor: this.bootNotificationRequest.chargePointVendor, - chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber, - firmwareVersion: this.bootNotificationRequest.firmwareVersion, - chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber, - iccid: this.bootNotificationRequest.iccid, - imsi: this.bootNotificationRequest.imsi, - meterSerialNumber: this.bootNotificationRequest.meterSerialNumber, - meterType: this.bootNotificationRequest.meterType, - }, - { skipBufferingOnError: true } - )) as BootNotificationResponse; + this.bootNotificationResponse = + await this.ocppRequestService.sendMessageHandler( + RequestCommand.BOOT_NOTIFICATION, + { + chargePointModel: this.bootNotificationRequest.chargePointModel, + chargePointVendor: this.bootNotificationRequest.chargePointVendor, + chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber, + firmwareVersion: this.bootNotificationRequest.firmwareVersion, + chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber, + iccid: this.bootNotificationRequest.iccid, + imsi: this.bootNotificationRequest.imsi, + meterSerialNumber: this.bootNotificationRequest.meterSerialNumber, + meterType: this.bootNotificationRequest.meterType, + }, + { skipBufferingOnError: true } + ); if (!this.isInAcceptedState()) { this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; await Utils.sleep( @@ -1385,7 +1434,7 @@ export default class ChargingStation { private async startMessageSequence(): Promise { if (this.stationInfo.autoRegister) { - await this.ocppRequestService.sendMessageHandler( + await this.ocppRequestService.sendMessageHandler( RequestCommand.BOOT_NOTIFICATION, { chargePointModel: this.bootNotificationRequest.chargePointModel, @@ -1415,11 +1464,14 @@ export default class ChargingStation { this.getConnectorStatus(connectorId)?.bootStatus ) { // Send status in template at startup - await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: this.getConnectorStatus(connectorId).bootStatus, - errorCode: ChargePointErrorCode.NO_ERROR, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.STATUS_NOTIFICATION, + { + connectorId, + status: this.getConnectorStatus(connectorId).bootStatus, + errorCode: ChargePointErrorCode.NO_ERROR, + } + ); this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus; } else if ( @@ -1428,27 +1480,36 @@ export default class ChargingStation { this.getConnectorStatus(connectorId)?.bootStatus ) { // Send status in template after reset - await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: this.getConnectorStatus(connectorId).bootStatus, - errorCode: ChargePointErrorCode.NO_ERROR, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.STATUS_NOTIFICATION, + { + connectorId, + status: this.getConnectorStatus(connectorId).bootStatus, + errorCode: ChargePointErrorCode.NO_ERROR, + } + ); this.getConnectorStatus(connectorId).status = this.getConnectorStatus(connectorId).bootStatus; } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) { // Send previous status at template reload - await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: this.getConnectorStatus(connectorId).status, - errorCode: ChargePointErrorCode.NO_ERROR, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.STATUS_NOTIFICATION, + { + connectorId, + status: this.getConnectorStatus(connectorId).status, + errorCode: ChargePointErrorCode.NO_ERROR, + } + ); } else { // Send default status - await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: ChargePointStatus.AVAILABLE, - errorCode: ChargePointErrorCode.NO_ERROR, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.STATUS_NOTIFICATION, + { + connectorId, + status: ChargePointStatus.AVAILABLE, + errorCode: ChargePointErrorCode.NO_ERROR, + } + ); this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE; } } @@ -1495,18 +1556,24 @@ export default class ChargingStation { connectorId, this.getEnergyActiveImportRegisterByTransactionId(transactionId) ); - await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, { - connectorId, - transactionId, - meterValue: transactionEndMeterValue, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.METER_VALUES, + { + connectorId, + transactionId, + meterValue: transactionEndMeterValue, + } + ); } - await this.ocppRequestService.sendMessageHandler(RequestCommand.STOP_TRANSACTION, { - transactionId, - meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId), - idTag: this.getTransactionIdTag(transactionId), - reason, - }); + await this.ocppRequestService.sendMessageHandler( + RequestCommand.STOP_TRANSACTION, + { + transactionId, + meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId), + idTag: this.getTransactionIdTag(transactionId), + reason, + } + ); } } }