X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=75094ceb104f538d92d1882c5145b3cf18fd664e;hb=6f6652de09ebe70ec3bd20921cc1741c32be4b34;hp=ebd77f83ac54a4d5303712ffcd69a5f78705e81c;hpb=3a33b6a907a44aabd721d3c63e6c5984f4f60c28;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index ebd77f83..75094ceb 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -38,6 +38,7 @@ import Configuration from '../utils/Configuration'; import { ConnectorStatus } from '../types/ConnectorStatus'; import Constants from '../utils/Constants'; import { ErrorType } from '../types/ocpp/ErrorType'; +import { FileType } from '../types/FileType'; import FileUtils from '../utils/FileUtils'; import { JsonType } from '../types/JsonType'; import { MessageType } from '../types/ocpp/MessageType'; @@ -74,6 +75,7 @@ export default class ChargingStation { public heartbeatSetInterval!: NodeJS.Timeout; public ocppRequestService!: OCPPRequestService; private readonly index: number; + private configurationFile!: string; private bootNotificationRequest!: BootNotificationRequest; private bootNotificationResponse!: BootNotificationResponse | null; private connectorsConfigurationHash!: string; @@ -255,29 +257,33 @@ export default class ChargingStation { return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false; } - public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { - if (this.getMeteringPerTransaction()) { - for (const connectorId of this.connectors.keys()) { - if ( - connectorId > 0 && - this.getConnectorStatus(connectorId).transactionId === transactionId - ) { - return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue; - } - } - } + public getConnectorIdByTransactionId(transactionId: number): number | undefined { for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { - return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue; + if ( + connectorId > 0 && + this.getConnectorStatus(connectorId)?.transactionId === transactionId + ) { + return connectorId; } } } + public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { + const transactionConnectorStatus = this.getConnectorStatus( + this.getConnectorIdByTransactionId(transactionId) + ); + if (this.getMeteringPerTransaction()) { + return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue; + } + return transactionConnectorStatus?.energyActiveImportRegisterValue; + } + public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined { + const connectorStatus = this.getConnectorStatus(connectorId); if (this.getMeteringPerTransaction()) { - return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue; + return connectorStatus?.transactionEnergyActiveImportRegisterValue; } - return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue; + return connectorStatus?.energyActiveImportRegisterValue; } public getAuthorizeRemoteTxRequests(): boolean { @@ -487,9 +493,57 @@ export default class ChargingStation { } this.openWSConnection(); // Monitor authorization file - this.startAuthorizationFileMonitoring(); - // Monitor station template file - this.startStationTemplateFileMonitoring(); + FileUtils.watchJsonFile( + this.logPrefix(), + FileType.Authorization, + this.getAuthorizationFile(), + this.authorizedTags + ); + // Monitor charging station template file + FileUtils.watchJsonFile( + this.logPrefix(), + FileType.ChargingStationTemplate, + this.stationTemplateFile, + null, + (event, filename): void => { + if (filename && event === 'change') { + try { + logger.debug( + `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ + this.stationTemplateFile + } file have changed, reload` + ); + // Initialize + this.initialize(); + // Restart the ATG + if ( + !this.stationInfo.AutomaticTransactionGenerator.enable && + this.automaticTransactionGenerator + ) { + this.automaticTransactionGenerator.stop(); + } + this.startAutomaticTransactionGenerator(); + if (this.getEnableStatistics()) { + this.performanceStatistics.restart(); + } else { + this.performanceStatistics.stop(); + } + // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed + } catch (error) { + logger.error( + `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`, + error + ); + } + } + } + ); + FileUtils.watchJsonFile( + this.logPrefix(), + FileType.ChargingStationConfiguration, + this.configurationFile, + this.configuration + ); // Handle WebSocket message this.wsConnection.on( 'message', @@ -563,12 +617,27 @@ export default class ChargingStation { readonly: false, visible: true, reboot: false, - } + }, + params: { overwrite?: boolean; save?: boolean } = { overwrite: false, save: false } ): void { - const keyFound = this.getConfigurationKey(key); + if (!options || Utils.isEmptyObject(options)) { + options = { + readonly: false, + visible: true, + reboot: false, + }; + } const readonly = options.readonly; const visible = options.visible; const reboot = options.reboot; + let keyFound = this.getConfigurationKey(key); + if (keyFound && params?.overwrite) { + this.configuration.configurationKey.splice( + this.configuration.configurationKey.indexOf(keyFound), + 1 + ); + keyFound = undefined; + } if (!keyFound) { this.configuration.configurationKey.push({ key, @@ -577,6 +646,7 @@ export default class ChargingStation { visible, reboot, }); + params?.save && this.saveConfiguration(); } else { logger.error( `${this.logPrefix()} Trying to add an already existing configuration key: %j`, @@ -585,11 +655,16 @@ export default class ChargingStation { } } - public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void { - const keyFound = this.getConfigurationKey(key); + public setConfigurationKeyValue( + key: string | StandardParametersKey, + value: string, + caseInsensitive = false + ): void { + const keyFound = this.getConfigurationKey(key, caseInsensitive); if (keyFound) { const keyIndex = this.configuration.configurationKey.indexOf(keyFound); this.configuration.configurationKey[keyIndex].value = value; + this.saveConfiguration(); } else { logger.error( `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, @@ -653,14 +728,13 @@ export default class ChargingStation { // In case of multiple instances: add instance index to charging station id const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; const idSuffix = stationTemplate.nameSuffix ?? ''; + const idStr = '000000000' + this.index.toString(); return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + - ('000000000' + this.index.toString()).substr( - ('000000000' + this.index.toString()).length - 4 - ) + + idStr.substring(idStr.length - 4) + idSuffix; } @@ -668,15 +742,13 @@ export default class ChargingStation { let stationTemplateFromFile: ChargingStationTemplate; try { // Load template file - const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r'); stationTemplateFromFile = JSON.parse( - fs.readFileSync(fileDescriptor, 'utf8') + fs.readFileSync(this.stationTemplateFile, 'utf8') ) as ChargingStationTemplate; - fs.closeSync(fileDescriptor); } catch (error) { FileUtils.handleFileException( this.logPrefix(), - 'Template', + FileType.ChargingStationTemplate, this.stationTemplateFile, error as NodeJS.ErrnoException ); @@ -731,7 +803,13 @@ export default class ChargingStation { private initialize(): void { this.stationInfo = this.buildStationInfo(); - this.configuration = this.getTemplateChargingStationConfiguration(); + 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, @@ -878,7 +956,7 @@ export default class ChargingStation { ) ) { this.addConfigurationKey( - VendorDefaultParametersKey.ConnectionUrl, + this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl, this.getConfiguredSupervisionUrl().href, { reboot: true } ); @@ -892,7 +970,8 @@ export default class ChargingStation { this.addConfigurationKey( StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), - { readonly: true } + { readonly: true }, + { overwrite: true } ); if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { this.addConfigurationKey( @@ -937,6 +1016,62 @@ export default class ChargingStation { Constants.DEFAULT_CONNECTION_TIMEOUT.toString() ); } + this.saveConfiguration(); + } + + private getConfigurationFromTemplate(): ChargingStationConfiguration { + return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration); + } + + private getConfigurationFromFile(): ChargingStationConfiguration | null { + let configuration: ChargingStationConfiguration = null; + if (this.configurationFile && fs.existsSync(this.configurationFile)) { + try { + configuration = JSON.parse( + fs.readFileSync(this.configurationFile, 'utf8') + ) as ChargingStationConfiguration; + } catch (error) { + FileUtils.handleFileException( + this.logPrefix(), + FileType.ChargingStationConfiguration, + this.configurationFile, + error as NodeJS.ErrnoException + ); + } + } + return configuration; + } + + private saveConfiguration(): void { + 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 + ); + } + } else { + logger.error( + `${this.logPrefix()} Trying to save charging station configuration to undefined file` + ); + } + } + + private getConfiguration(): ChargingStationConfiguration { + let configuration: ChargingStationConfiguration = this.getConfigurationFromFile(); + if (!configuration) { + configuration = this.getConfigurationFromTemplate(); + } + return configuration; } private async onOpen(): Promise { @@ -954,6 +1089,11 @@ export default class ChargingStation { 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; @@ -1133,10 +1273,6 @@ export default class ChargingStation { logger.error(this.logPrefix() + ' WebSocket error: %j', error); } - private getTemplateChargingStationConfiguration(): ChargingStationConfiguration { - return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration); - } - private getAuthorizationFile(): string | undefined { return ( this.stationInfo.authorizationFile && @@ -1154,13 +1290,11 @@ export default class ChargingStation { if (authorizationFile) { try { // Load authorization file - const fileDescriptor = fs.openSync(authorizationFile, 'r'); - authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[]; - fs.closeSync(fileDescriptor); + authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[]; } catch (error) { FileUtils.handleFileException( this.logPrefix(), - 'Authorization', + FileType.Authorization, authorizationFile, error as NodeJS.ErrnoException ); @@ -1258,6 +1392,11 @@ export default class ChargingStation { 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 } ); @@ -1541,89 +1680,6 @@ export default class ChargingStation { } } - private startAuthorizationFileMonitoring(): void { - const authorizationFile = this.getAuthorizationFile(); - if (authorizationFile) { - try { - fs.watch(authorizationFile, (event, filename) => { - if (filename && event === 'change') { - try { - logger.debug( - this.logPrefix() + - ' Authorization file ' + - authorizationFile + - ' have changed, reload' - ); - // Initialize authorizedTags - this.authorizedTags = this.getAuthorizedTags(); - } catch (error) { - logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error); - } - } - }); - } catch (error) { - FileUtils.handleFileException( - this.logPrefix(), - 'Authorization', - authorizationFile, - error as NodeJS.ErrnoException - ); - } - } else { - logger.info( - this.logPrefix() + - ' No authorization file given in template file ' + - this.stationTemplateFile + - '. Not monitoring changes' - ); - } - } - - private startStationTemplateFileMonitoring(): void { - try { - fs.watch(this.stationTemplateFile, (event, filename): void => { - if (filename && event === 'change') { - try { - logger.debug( - this.logPrefix() + - ' Template file ' + - this.stationTemplateFile + - ' have changed, reload' - ); - // Initialize - this.initialize(); - // Restart the ATG - if ( - !this.stationInfo.AutomaticTransactionGenerator.enable && - this.automaticTransactionGenerator - ) { - this.automaticTransactionGenerator.stop(); - } - this.startAutomaticTransactionGenerator(); - if (this.getEnableStatistics()) { - this.performanceStatistics.restart(); - } else { - this.performanceStatistics.stop(); - } - // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed - } catch (error) { - logger.error( - this.logPrefix() + ' Charging station template file monitoring error: %j', - error - ); - } - } - }); - } catch (error) { - FileUtils.handleFileException( - this.logPrefix(), - 'Template', - this.stationTemplateFile, - error as NodeJS.ErrnoException - ); - } - } - private getReconnectExponentialDelay(): boolean | undefined { return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay