X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=9a8f468b37bee455378b890a2392a4e02a9dfefb;hb=ca47912d4ef0ca7608be49e62aadb6a931d74359;hp=5ce061e8ed64c988b607f3f6b494b0d30c0526ad;hpb=7671fa0be211e944f027ebd83f3a0ad64c2ef2d6;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 5ce061e8..9a8f468b 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -35,7 +35,6 @@ import { type BootNotificationRequest, type BootNotificationResponse, type CachedRequest, - type ChargingStationAutomaticTransactionGeneratorConfiguration, type ChargingStationConfiguration, type ChargingStationInfo, type ChargingStationOcppConfiguration, @@ -70,6 +69,7 @@ import { RequestCommand, type Response, StandardParametersKey, + type Status, type StatusNotificationRequest, type StatusNotificationResponse, StopTransactionReason, @@ -89,11 +89,16 @@ import { Configuration, Constants, DCElectricUtils, - ErrorUtils, - FileUtils, - MessageChannelUtils, Utils, + buildChargingStationAutomaticTransactionGeneratorConfiguration, + buildConnectorsStatus, + buildEvsesStatus, + buildStartedMessage, + buildStoppedMessage, + buildUpdatedMessage, + handleFileException, logger, + watchJsonFile, } from '../utils'; export class ChargingStation { @@ -158,11 +163,17 @@ export class ChargingStation { return new URL( `${ this.getSupervisionUrlOcppConfiguration() && - Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) + Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) && + Utils.isNotEmptyString( + ChargingStationConfigurationUtils.getConfigurationKey( + this, + this.getSupervisionUrlOcppKey() + )?.value + ) ? ChargingStationConfigurationUtils.getConfigurationKey( this, this.getSupervisionUrlOcppKey() - )?.value + ).value : this.configuredSupervisionUrl.href }/${this.stationInfo.chargingStationId}` ); @@ -636,7 +647,7 @@ export class ChargingStation { } this.openWSConnection(); // Monitor charging station template file - this.templateFileWatcher = FileUtils.watchJsonFile( + this.templateFileWatcher = watchJsonFile( this.templateFile, FileType.ChargingStationTemplate, this.logPrefix(), @@ -673,7 +684,7 @@ export class ChargingStation { } ); this.started = true; - parentPort?.postMessage(MessageChannelUtils.buildStartedMessage(this)); + parentPort?.postMessage(buildStartedMessage(this)); this.starting = false; } else { logger.warn(`${this.logPrefix()} Charging station is already starting...`); @@ -698,7 +709,7 @@ export class ChargingStation { delete this.bootNotificationResponse; this.started = false; this.saveConfiguration(); - parentPort?.postMessage(MessageChannelUtils.buildStoppedMessage(this)); + parentPort?.postMessage(buildStoppedMessage(this)); this.stopping = false; } else { logger.warn(`${this.logPrefix()} Charging station is already stopping...`); @@ -739,7 +750,7 @@ export class ChargingStation { terminateOpened: false, } ): void { - options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; + options = { handshakeTimeout: this.getConnectionTimeout() * 1000, ...options }; params = { ...{ closeOpened: false, terminateOpened: false }, ...params }; if (this.started === false && this.starting === false) { logger.warn( @@ -810,12 +821,29 @@ export class ChargingStation { public getAutomaticTransactionGeneratorConfiguration(): | AutomaticTransactionGeneratorConfiguration | undefined { + let automaticTransactionGeneratorConfiguration: + | AutomaticTransactionGeneratorConfiguration + | undefined; const automaticTransactionGeneratorConfigurationFromFile = this.getConfigurationFromFile()?.automaticTransactionGenerator; - if (automaticTransactionGeneratorConfigurationFromFile) { - return automaticTransactionGeneratorConfigurationFromFile; + if ( + this.getAutomaticTransactionGeneratorPersistentConfiguration() && + automaticTransactionGeneratorConfigurationFromFile + ) { + automaticTransactionGeneratorConfiguration = + automaticTransactionGeneratorConfigurationFromFile; + } else { + automaticTransactionGeneratorConfiguration = + this.getTemplateFromFile()?.AutomaticTransactionGenerator; } - return this.getTemplateFromFile()?.AutomaticTransactionGenerator; + return { + ...Constants.DEFAULT_ATG_CONFIGURATION, + ...automaticTransactionGeneratorConfiguration, + }; + } + + public getAutomaticTransactionGeneratorStatuses(): Status[] | undefined { + return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses; } public startAutomaticTransactionGenerator(connectorIds?: number[]): void { @@ -827,8 +855,8 @@ export class ChargingStation { } else { this.automaticTransactionGenerator?.start(); } - this.saveChargingStationAutomaticTransactionGeneratorConfiguration(); - parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + this.saveAutomaticTransactionGeneratorConfiguration(); + parentPort?.postMessage(buildUpdatedMessage(this)); } public stopAutomaticTransactionGenerator(connectorIds?: number[]): void { @@ -839,8 +867,8 @@ export class ChargingStation { } else { this.automaticTransactionGenerator?.stop(); } - this.saveChargingStationAutomaticTransactionGeneratorConfiguration(); - parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + this.saveAutomaticTransactionGeneratorConfiguration(); + parentPort?.postMessage(buildUpdatedMessage(this)); } public async stopTransactionOnConnector( @@ -931,7 +959,7 @@ export class ChargingStation { this.templateFileHash = template.templateHash; } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.templateFile, FileType.ChargingStationTemplate, error as NodeJS.ErrnoException, @@ -943,7 +971,7 @@ export class ChargingStation { private getStationInfoFromTemplate(): ChargingStationInfo { const stationTemplate: ChargingStationTemplate | undefined = this.getTemplateFromFile(); - ChargingStationUtils.checkTemplateFile(stationTemplate, this.logPrefix(), this.templateFile); + ChargingStationUtils.checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); ChargingStationUtils.warnTemplateKeysDeprecation( stationTemplate, this.logPrefix(), @@ -1050,6 +1078,10 @@ export class ChargingStation { return this.stationInfo?.stationInfoPersistentConfiguration ?? true; } + private getAutomaticTransactionGeneratorPersistentConfiguration(): boolean { + return this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration ?? true; + } + private handleUnsupportedVersion(version: OCPPVersion) { const errorMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`; logger.error(`${this.logPrefix()} ${errorMsg}`); @@ -1058,15 +1090,14 @@ export class ChargingStation { private initialize(): void { const stationTemplate = this.getTemplateFromFile(); - ChargingStationUtils.checkTemplateFile(stationTemplate, this.logPrefix(), this.templateFile); + ChargingStationUtils.checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); this.configurationFile = path.join( path.dirname(this.templateFile.replace('station-templates', 'configurations')), `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json` ); const chargingStationConfiguration = this.getConfigurationFromFile(); - const featureFlag = false; if ( - featureFlag && + chargingStationConfiguration?.stationInfo?.templateHash === stationTemplate?.templateHash && (chargingStationConfiguration?.connectorsStatus || chargingStationConfiguration?.evsesStatus) ) { this.initializeConnectorsOrEvsesFromFile(chargingStationConfiguration); @@ -1449,7 +1480,7 @@ export class ChargingStation { if (stationTemplate?.Evses) { const evsesConfigHash = crypto .createHash(Constants.DEFAULT_HASH_ALGORITHM) - .update(`${JSON.stringify(stationTemplate?.Evses)}`) + .update(JSON.stringify(stationTemplate?.Evses)) .digest('hex'); const evsesConfigChanged = this.evses?.size !== 0 && this.evsesConfigurationHash !== evsesConfigHash; @@ -1493,7 +1524,7 @@ export class ChargingStation { private getConfigurationFromFile(): ChargingStationConfiguration | undefined { let configuration: ChargingStationConfiguration | undefined; - if (this.configurationFile && fs.existsSync(this.configurationFile)) { + if (Utils.isNotEmptyString(this.configurationFile) && fs.existsSync(this.configurationFile)) { try { if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { configuration = this.sharedLRUCache.getChargingStationConfiguration( @@ -1510,7 +1541,7 @@ export class ChargingStation { this.configurationFileHash = configuration.configurationHash; } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, @@ -1521,18 +1552,10 @@ export class ChargingStation { return configuration; } - private saveChargingStationAutomaticTransactionGeneratorConfiguration( - stationTemplate?: ChargingStationTemplate - ): void { - this.saveConfiguration({ - automaticTransactionGenerator: (stationTemplate ?? this.getTemplateFromFile()) - .AutomaticTransactionGenerator, - ...(!Utils.isNullOrUndefined(this.automaticTransactionGenerator?.connectorsStatus) && { - automaticTransactionGeneratorStatuses: [ - ...this.automaticTransactionGenerator.connectorsStatus.values(), - ], - }), - }); + private saveAutomaticTransactionGeneratorConfiguration(): void { + if (this.getAutomaticTransactionGeneratorPersistentConfiguration()) { + this.saveConfiguration(); + } } private saveConnectorsStatus() { @@ -1543,10 +1566,8 @@ export class ChargingStation { this.saveConfiguration(); } - private saveConfiguration( - chargingStationAutomaticTransactionGeneratorConfiguration?: ChargingStationAutomaticTransactionGeneratorConfiguration - ): void { - if (this.configurationFile) { + private saveConfiguration(): void { + if (Utils.isNotEmptyString(this.configurationFile)) { try { if (!fs.existsSync(path.dirname(this.configurationFile))) { fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); @@ -1555,39 +1576,44 @@ export class ChargingStation { Utils.cloneObject(this.getConfigurationFromFile()) ?? {}; if (this.getStationInfoPersistentConfiguration() && this.stationInfo) { configurationData.stationInfo = this.stationInfo; + } else { + delete configurationData.stationInfo; } if (this.getOcppPersistentConfiguration() && this.ocppConfiguration?.configurationKey) { configurationData.configurationKey = this.ocppConfiguration.configurationKey; + } else { + delete configurationData.configurationKey; } - if (chargingStationAutomaticTransactionGeneratorConfiguration) { - configurationData = merge( - configurationData, - chargingStationAutomaticTransactionGeneratorConfiguration - ); + configurationData = merge( + configurationData, + buildChargingStationAutomaticTransactionGeneratorConfiguration(this) + ); + if ( + !this.getAutomaticTransactionGeneratorPersistentConfiguration() || + !this.getAutomaticTransactionGeneratorConfiguration() + ) { + delete configurationData.automaticTransactionGenerator; } if (this.connectors.size > 0) { - configurationData.connectorsStatus = [...this.connectors.values()].map( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - ({ transactionSetInterval, ...connectorStatusRest }) => connectorStatusRest - ); + configurationData.connectorsStatus = buildConnectorsStatus(this); + } else { + delete configurationData.connectorsStatus; } if (this.evses.size > 0) { - configurationData.evsesStatus = [...this.evses.values()].map((evseStatus) => { - const status = { - ...evseStatus, - connectorsStatus: [...evseStatus.connectors.values()].map( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - ({ transactionSetInterval, ...connectorStatusRest }) => connectorStatusRest - ), - }; - delete status.connectors; - return status as EvseStatusConfiguration; - }); + configurationData.evsesStatus = buildEvsesStatus(this); + } else { + delete configurationData.evsesStatus; } delete configurationData.configurationHash; const configurationHash = crypto .createHash(Constants.DEFAULT_HASH_ALGORITHM) - .update(JSON.stringify(configurationData)) + .update( + JSON.stringify({ + stationInfo: configurationData.stationInfo, + configurationKey: configurationData.configurationKey, + automaticTransactionGenerator: configurationData.automaticTransactionGenerator, + } as ChargingStationConfiguration) + ) .digest('hex'); if (this.configurationFileHash !== configurationHash) { AsyncLock.acquire(AsyncLockType.configuration) @@ -1604,7 +1630,7 @@ export class ChargingStation { this.configurationFileHash = configurationHash; }) .catch((error) => { - ErrorUtils.handleFileException( + handleFileException( this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, @@ -1622,7 +1648,7 @@ export class ChargingStation { ); } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, @@ -1641,9 +1667,11 @@ export class ChargingStation { } private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined { - if (this.getOcppPersistentConfiguration() === true) { - return { configurationKey: this.getConfigurationFromFile()?.configurationKey }; + const configurationKey = this.getConfigurationFromFile()?.configurationKey; + if (this.getOcppPersistentConfiguration() === true && configurationKey) { + return { configurationKey }; } + return undefined; } private getOcppConfiguration(): ChargingStationOcppConfiguration | undefined { @@ -1671,11 +1699,11 @@ export class ChargingStation { skipBufferingOnError: true, }); if (this.isRegistered() === false) { - this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; + this.getRegistrationMaxRetries() !== -1 && ++registrationRetryCount; await Utils.sleep( this?.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 - : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL + : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL ); } } while ( @@ -1695,7 +1723,7 @@ export class ChargingStation { } this.wsConnectionRestarted = false; this.autoReconnectRetryCount = 0; - parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(buildUpdatedMessage(this)); } else { logger.warn( `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` @@ -1725,7 +1753,7 @@ export class ChargingStation { this.started === true && (await this.reconnect()); break; } - parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(buildUpdatedMessage(this)); } private getCachedRequest(messageType: MessageType, messageId: string): CachedRequest | undefined { @@ -1835,7 +1863,7 @@ export class ChargingStation { logger.error(`${this.logPrefix()} ${errorMsg}`); throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg); } - parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(buildUpdatedMessage(this)); } else { throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, { request, @@ -2168,6 +2196,7 @@ export class ChargingStation { } private getConfiguredSupervisionUrl(): URL { + let configuredSupervisionUrl: string; const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls(); if (Utils.isNotEmptyArray(supervisionUrls)) { let configuredSupervisionUrlIndex: number; @@ -2189,9 +2218,16 @@ export class ChargingStation { configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; break; } - return new URL(supervisionUrls[configuredSupervisionUrlIndex]); + configuredSupervisionUrl = supervisionUrls[configuredSupervisionUrlIndex]; + } else { + configuredSupervisionUrl = supervisionUrls as string; + } + if (Utils.isNotEmptyString(configuredSupervisionUrl)) { + return new URL(configuredSupervisionUrl); } - return new URL(supervisionUrls as string); + const errorMsg = 'No supervision url(s) configured'; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(`${errorMsg}`); } private stopHeartbeat(): void { @@ -2225,7 +2261,7 @@ export class ChargingStation { this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1 ) { - this.autoReconnectRetryCount++; + ++this.autoReconnectRetryCount; const reconnectDelay = this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000;