X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=b3d4bdd98016cbf5d35288c15bff552417859497;hb=d5575b174bef0e79d2a600ae24be2789d6cf3451;hp=645c3f736b004be126891afc3f8bb8b2318c85dc;hpb=56d09fd7cdb49418af30cef6b9a47ea5007fb044;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 645c3f73..b3d4bdd9 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -10,11 +10,11 @@ import merge from 'just-merge'; import WebSocket, { type RawData } from 'ws'; import { - AuthorizedTagsCache, AutomaticTransactionGenerator, ChargingStationConfigurationUtils, ChargingStationUtils, ChargingStationWorkerBroadcastChannel, + IdTagsCache, MessageChannelUtils, SharedLRUCache, } from './internal'; @@ -47,12 +47,13 @@ import { type ChargingStationOcppConfiguration, type ChargingStationTemplate, ConnectorPhaseRotation, - ConnectorStatus, + type ConnectorStatus, ConnectorStatusEnum, CurrentType, type ErrorCallback, type ErrorResponse, ErrorType, + type EvseStatus, FileType, FirmwareStatus, type FirmwareStatusNotificationRequest, @@ -74,7 +75,6 @@ import { RegistrationStatusEnumType, RequestCommand, type Response, - type ResponseCallback, StandardParametersKey, type StatusNotificationRequest, type StatusNotificationResponse, @@ -104,11 +104,12 @@ export class ChargingStation { public stationInfo!: ChargingStationInfo; public started: boolean; public starting: boolean; - public authorizedTagsCache: AuthorizedTagsCache; + public idTagsCache: IdTagsCache; public automaticTransactionGenerator!: AutomaticTransactionGenerator | undefined; public ocppConfiguration!: ChargingStationOcppConfiguration | undefined; public wsConnection!: WebSocket | null; public readonly connectors: Map; + public readonly evses: Map; public readonly requests: Map; public performanceStatistics!: PerformanceStatistics | undefined; public heartbeatSetInterval!: NodeJS.Timeout; @@ -120,10 +121,10 @@ export class ChargingStation { private configurationFile!: string; private configurationFileHash!: string; private connectorsConfigurationHash!: string; + private evsesConfigurationHash!: string; private ocppIncomingRequestService!: OCPPIncomingRequestService; private readonly messageBuffer: Set; private configuredSupervisionUrl!: URL; - private configuredSupervisionUrlIndex!: number; private wsConnectionRestarted: boolean; private autoReconnectRetryCount: number; private templateFileWatcher!: fs.FSWatcher | undefined; @@ -140,10 +141,11 @@ export class ChargingStation { this.index = index; this.templateFile = templateFile; this.connectors = new Map(); + this.evses = new Map(); this.requests = new Map(); this.messageBuffer = new Set(); this.sharedLRUCache = SharedLRUCache.getInstance(); - this.authorizedTagsCache = AuthorizedTagsCache.getInstance(); + this.idTagsCache = IdTagsCache.getInstance(); this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this); this.initialize(); @@ -152,7 +154,8 @@ export class ChargingStation { private get wsConnectionUrl(): URL { return new URL( `${ - this.getSupervisionUrlOcppConfiguration() + this.getSupervisionUrlOcppConfiguration() && + Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) ? ChargingStationConfigurationUtils.getConfigurationKey( this, this.getSupervisionUrlOcppKey() @@ -165,20 +168,17 @@ export class ChargingStation { public logPrefix = (): string => { return Utils.logPrefix( ` ${ - (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) && - this?.stationInfo?.chargingStationId) ?? - ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) ?? - '' + (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) + ? this?.stationInfo?.chargingStationId + : ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())) ?? + 'Error at building log prefix' } |` ); }; - public hasAuthorizedTags(): boolean { - return Utils.isNotEmptyArray( - this.authorizedTagsCache.getAuthorizedTags( - ChargingStationUtils.getAuthorizationFile(this.stationInfo) - ) - ); + public hasIdTags(): boolean { + const idTagsFile = ChargingStationUtils.getIdTagsFile(this.stationInfo); + return Utils.isNotEmptyArray(this.idTagsCache.getIdTags(idTagsFile)); } public getEnableStatistics(): boolean { @@ -237,11 +237,11 @@ export class ChargingStation { } public isChargingStationAvailable(): boolean { - return this.getConnectorStatus(0)?.availability === AvailabilityType.OPERATIVE; + return this.getConnectorStatus(0)?.availability === AvailabilityType.Operative; } public isConnectorAvailable(id: number): boolean { - return id > 0 && this.getConnectorStatus(id)?.availability === AvailabilityType.OPERATIVE; + return id > 0 && this.getConnectorStatus(id)?.availability === AvailabilityType.Operative; } public getNumberOfConnectors(): number { @@ -387,12 +387,49 @@ export class ChargingStation { return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; } - public startHeartbeat(): void { + public getHeartbeatInterval(): number { + const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.HeartbeatInterval + ); + if (HeartbeatInterval) { + return Utils.convertToInt(HeartbeatInterval.value) * 1000; + } + const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.HeartBeatInterval + ); + if (HeartBeatInterval) { + return Utils.convertToInt(HeartBeatInterval.value) * 1000; + } + this.stationInfo?.autoRegister === false && + logger.warn( + `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ + Constants.DEFAULT_HEARTBEAT_INTERVAL + }` + ); + return Constants.DEFAULT_HEARTBEAT_INTERVAL; + } + + public setSupervisionUrl(url: string): void { if ( - this.getHeartbeatInterval() && - this.getHeartbeatInterval() > 0 && - !this.heartbeatSetInterval + this.getSupervisionUrlOcppConfiguration() && + Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) ) { + ChargingStationConfigurationUtils.setConfigurationKeyValue( + this, + this.getSupervisionUrlOcppKey(), + url + ); + } else { + this.stationInfo.supervisionUrls = url; + this.saveStationInfo(); + this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); + } + } + + public startHeartbeat(): void { + if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) { this.heartbeatSetInterval = setInterval(() => { this.ocppRequestService .requestHandler(this, RequestCommand.HEARTBEAT) @@ -416,11 +453,7 @@ export class ChargingStation { ); } else { logger.error( - `${this.logPrefix()} Heartbeat interval set to ${ - this.getHeartbeatInterval() - ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) - : this.getHeartbeatInterval() - }, not starting the heartbeat` + `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat` ); } } @@ -442,19 +475,19 @@ export class ChargingStation { public startMeterValues(connectorId: number, interval: number): void { if (connectorId === 0) { logger.error( - `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}` + `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}` ); return; } if (!this.getConnectorStatus(connectorId)) { logger.error( - `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}` + `${this.logPrefix()} Trying to start MeterValues on non existing connector id ${connectorId.toString()}` ); return; } if (this.getConnectorStatus(connectorId)?.transactionStarted === false) { logger.error( - `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started` + `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction started` ); return; } else if ( @@ -462,7 +495,7 @@ export class ChargingStation { Utils.isNullOrUndefined(this.getConnectorStatus(connectorId)?.transactionId) ) { logger.error( - `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id` + `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id` ); return; } @@ -496,13 +529,17 @@ export class ChargingStation { logger.error( `${this.logPrefix()} Charging station ${ StandardParametersKey.MeterValueSampleInterval - } configuration set to ${ - interval ? Utils.formatDurationMilliSeconds(interval) : interval - }, not sending MeterValues` + } configuration set to ${interval}, not sending MeterValues` ); } } + public stopMeterValues(connectorId: number) { + if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { + clearInterval(this.getConnectorStatus(connectorId)?.transactionSetInterval); + } + } + public start(): void { if (this.started === false) { if (this.starting === false) { @@ -598,21 +635,6 @@ export class ChargingStation { } } - public resetConnectorStatus(connectorId: number): void { - this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; - this.getConnectorStatus(connectorId).idTagAuthorized = false; - this.getConnectorStatus(connectorId).transactionRemoteStarted = false; - this.getConnectorStatus(connectorId).transactionStarted = false; - delete this.getConnectorStatus(connectorId)?.localAuthorizeIdTag; - delete this.getConnectorStatus(connectorId)?.authorizeIdTag; - delete this.getConnectorStatus(connectorId)?.transactionId; - delete this.getConnectorStatus(connectorId)?.transactionIdTag; - this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; - delete this.getConnectorStatus(connectorId)?.transactionBeginMeterValue; - this.stopMeterValues(connectorId); - parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); - } - public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean | undefined { return ChargingStationConfigurationUtils.getConfigurationKey( this, @@ -625,7 +647,7 @@ export class ChargingStation { } public openWSConnection( - options: WsOptions = this.stationInfo?.wsOptions ?? Constants.EMPTY_OBJECT, + options: WsOptions = this.stationInfo?.wsOptions ?? {}, params: { closeOpened?: boolean; terminateOpened?: boolean } = { closeOpened: false, terminateOpened: false, @@ -769,7 +791,7 @@ export class ChargingStation { private flushMessageBuffer(): void { if (this.messageBuffer.size > 0) { - this.messageBuffer.forEach((message) => { + for (const message of this.messageBuffer.values()) { let beginId: string; let commandName: RequestCommand; const [messageType] = JSON.parse(message) as OutgoingRequest | Response | ErrorResponse; @@ -786,7 +808,7 @@ export class ChargingStation { )} payload sent: ${message}` ); this.messageBuffer.delete(message); - }); + } } } @@ -839,18 +861,10 @@ export class ChargingStation { logger.error(`${this.logPrefix()} ${errorMsg}`); throw new BaseError(errorMsg); } - // Deprecation template keys section - ChargingStationUtils.warnDeprecatedTemplateKey( - stationTemplate, - 'supervisionUrl', + ChargingStationUtils.warnTemplateKeysDeprecation( this.templateFile, - this.logPrefix(), - "Use 'supervisionUrls' instead" - ); - ChargingStationUtils.convertDeprecatedTemplateKey( stationTemplate, - 'supervisionUrl', - 'supervisionUrls' + this.logPrefix() ); const stationInfo: ChargingStationInfo = ChargingStationUtils.stationTemplateToStationInfo(stationTemplate); @@ -894,39 +908,13 @@ export class ChargingStation { }, reset: true, }, - stationTemplate?.firmwareUpgrade ?? Constants.EMPTY_OBJECT + stationTemplate?.firmwareUpgrade ?? {} ); stationInfo.resetTime = !Utils.isNullOrUndefined(stationTemplate?.resetTime) ? stationTemplate.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; - const configuredMaxConnectors = - ChargingStationUtils.getConfiguredNumberOfConnectors(stationTemplate); - ChargingStationUtils.checkConfiguredMaxConnectors( - configuredMaxConnectors, - this.templateFile, - this.logPrefix() - ); - const templateMaxConnectors = - ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate); - ChargingStationUtils.checkTemplateMaxConnectors( - templateMaxConnectors, - this.templateFile, - this.logPrefix() - ); - if ( - configuredMaxConnectors > - (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && - !stationTemplate?.randomConnectors - ) { - logger.warn( - `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ - this.templateFile - }, forcing random connector configurations affectation` - ); - stationInfo.randomConnectors = true; - } - // Build connectors if needed (FIXME: should be factored out) - this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors); + // Initialize evses or connectors if needed (FIXME: should be factored out) + this.initializeConnectorsOrEvses(stationInfo); stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo); ChargingStationUtils.createStationInfoHash(stationInfo); return stationInfo; @@ -943,7 +931,10 @@ export class ChargingStation { private getStationInfo(): ChargingStationInfo { const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate(); const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile(); - // Priority: charging station info from template > charging station info from configuration file > charging station info attribute + // Priority: + // 1. charging station info from template + // 2. charging station info from configuration file + // 3. charging station info attribute if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) { return this.stationInfo; @@ -985,9 +976,28 @@ export class ChargingStation { `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json` ); this.stationInfo = this.getStationInfo(); + if ( + this.stationInfo.firmwareStatus === FirmwareStatus.Installing && + Utils.isNotEmptyString(this.stationInfo.firmwareVersion) && + Utils.isNotEmptyString(this.stationInfo.firmwareVersionPattern) + ) { + const patternGroup: number | undefined = + this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ?? + this.stationInfo.firmwareVersion?.split('.').length; + const match = this.stationInfo?.firmwareVersion + ?.match(new RegExp(this.stationInfo.firmwareVersionPattern)) + ?.slice(1, patternGroup + 1); + const patchLevelIndex = match.length - 1; + match[patchLevelIndex] = ( + Utils.convertToInt(match[patchLevelIndex]) + + this.stationInfo.firmwareUpgrade?.versionUpgrade?.step + ).toString(); + this.stationInfo.firmwareVersion = match?.join('.'); + } this.saveStationInfo(); - // Avoid duplication of connectors related information in RAM + // Avoid duplication of connectors or evses related information in RAM delete this.stationInfo?.Connectors; + delete this.stationInfo?.Evses; this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); if (this.getEnableStatistics() === true) { this.performanceStatistics = PerformanceStatistics.getInstance( @@ -1011,24 +1021,6 @@ export class ChargingStation { status: RegistrationStatusEnumType.ACCEPTED, }; } - if ( - this.stationInfo.firmwareStatus === FirmwareStatus.Installing && - Utils.isNotEmptyString(this.stationInfo.firmwareVersion) && - Utils.isNotEmptyString(this.stationInfo.firmwareVersionPattern) - ) { - const patternGroup: number | undefined = - this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ?? - this.stationInfo.firmwareVersion?.split('.').length; - const match = this.stationInfo?.firmwareVersion - ?.match(new RegExp(this.stationInfo.firmwareVersionPattern)) - ?.slice(1, patternGroup + 1); - const patchLevelIndex = match.length - 1; - match[patchLevelIndex] = ( - Utils.convertToInt(match[patchLevelIndex]) + - this.stationInfo.firmwareUpgrade?.versionUpgrade?.step - ).toString(); - this.stationInfo.firmwareVersion = match?.join('.'); - } } private initializeOcppServices(): void { @@ -1083,6 +1075,7 @@ export class ChargingStation { } if ( this.getSupervisionUrlOcppConfiguration() && + Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) && !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) ) { ChargingStationConfigurationUtils.addConfigurationKey( @@ -1093,6 +1086,7 @@ export class ChargingStation { ); } else if ( !this.getSupervisionUrlOcppConfiguration() && + Utils.isNotEmptyString(this.getSupervisionUrlOcppKey()) && ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) ) { ChargingStationConfigurationUtils.deleteConfigurationKey( @@ -1217,11 +1211,23 @@ export class ChargingStation { this.saveOcppConfiguration(); } - private initializeConnectors( - stationInfo: ChargingStationInfo, - configuredMaxConnectors: number, - templateMaxConnectors: number - ): void { + private initializeConnectorsOrEvses(stationInfo: ChargingStationInfo) { + if (stationInfo?.Connectors && !stationInfo?.Evses) { + this.initializeConnectors(stationInfo); + } else if (stationInfo?.Evses && !stationInfo?.Connectors) { + this.initializeEvses(stationInfo); + } else if (stationInfo?.Evses && stationInfo?.Connectors) { + const errorMsg = `Connectors and evses defined at the same time in template file ${this.templateFile}`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); + } else { + const errorMsg = `No connectors or evses defined in template file ${this.templateFile}`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); + } + } + + private initializeConnectors(stationInfo: ChargingStationInfo): void { if (!stationInfo?.Connectors && this.connectors.size === 0) { const logMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`; logger.error(`${this.logPrefix()} ${logMsg}`); @@ -1231,10 +1237,17 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no connector Id 0 configuration` + } with no connector id 0 configuration` ); } if (stationInfo?.Connectors) { + const configuredMaxConnectors = + ChargingStationUtils.getConfiguredNumberOfConnectors(stationInfo); + ChargingStationUtils.checkConfiguredMaxConnectors( + configuredMaxConnectors, + this.templateFile, + this.logPrefix() + ); const connectorsConfigHash = crypto .createHash(Constants.DEFAULT_HASH_ALGORITHM) .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`) @@ -1244,41 +1257,70 @@ export class ChargingStation { if (this.connectors?.size === 0 || connectorsConfigChanged) { connectorsConfigChanged && this.connectors.clear(); this.connectorsConfigurationHash = connectorsConfigHash; - // Add connector Id 0 - let lastConnector = '0'; - for (lastConnector in stationInfo?.Connectors) { - const connectorStatus = stationInfo?.Connectors[lastConnector]; - const lastConnectorId = Utils.convertToInt(lastConnector); - if ( - lastConnectorId === 0 && - this.getUseConnectorId0(stationInfo) === true && - connectorStatus - ) { - this.checkStationInfoConnectorStatus(lastConnectorId, connectorStatus); - this.connectors.set( - lastConnectorId, - Utils.cloneObject(connectorStatus) - ); - this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; - if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { - this.getConnectorStatus(lastConnectorId).chargingProfiles = []; - } + const connectorZeroStatus = stationInfo?.Connectors[0]; + // Add connector id 0 + if (connectorZeroStatus && this.getUseConnectorId0(stationInfo) === true) { + ChargingStationUtils.checkStationInfoConnectorStatus( + 0, + connectorZeroStatus, + this.logPrefix(), + this.templateFile + ); + this.connectors.set(0, Utils.cloneObject(connectorZeroStatus)); + this.getConnectorStatus(0).availability = AvailabilityType.Operative; + if (Utils.isUndefined(this.getConnectorStatus(0)?.chargingProfiles)) { + this.getConnectorStatus(0).chargingProfiles = []; } } - // Generate all connectors - if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { - for (let index = 1; index <= configuredMaxConnectors; index++) { - const randConnectorId = stationInfo?.randomConnectors - ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) - : index; - const connectorStatus = stationInfo?.Connectors[randConnectorId.toString()]; - this.checkStationInfoConnectorStatus(randConnectorId, connectorStatus); - this.connectors.set(index, Utils.cloneObject(connectorStatus)); - this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; - if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { - this.getConnectorStatus(index).chargingProfiles = []; + // Add remaining connectors + const templateMaxConnectors = ChargingStationUtils.getMaxNumberOfConnectors( + stationInfo.Connectors + ); + ChargingStationUtils.checkTemplateMaxConnectors( + templateMaxConnectors, + this.templateFile, + this.logPrefix() + ); + if ( + configuredMaxConnectors > + (stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && + !stationInfo?.randomConnectors + ) { + logger.warn( + `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ + this.templateFile + }, forcing random connector configurations affectation` + ); + stationInfo.randomConnectors = true; + } + const templateMaxAvailableConnectors = stationInfo?.Connectors[0] + ? templateMaxConnectors - 1 + : templateMaxConnectors; + if (templateMaxAvailableConnectors > 0) { + for (let connectorId = 1; connectorId <= configuredMaxConnectors; connectorId++) { + const templateConnectorId = stationInfo?.randomConnectors + ? Utils.getRandomInteger(templateMaxAvailableConnectors, 1) + : connectorId; + const connectorStatus = stationInfo?.Connectors[templateConnectorId]; + ChargingStationUtils.checkStationInfoConnectorStatus( + templateConnectorId, + connectorStatus, + this.logPrefix(), + this.templateFile + ); + this.connectors.set(connectorId, Utils.cloneObject(connectorStatus)); + this.getConnectorStatus(connectorId).availability = AvailabilityType.Operative; + if (Utils.isUndefined(this.getConnectorStatus(connectorId)?.chargingProfiles)) { + this.getConnectorStatus(connectorId).chargingProfiles = []; } + ChargingStationUtils.initializeConnectorsMapStatus(this.connectors, this.logPrefix()); } + } else { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no connectors configuration defined, cannot create connectors` + ); } } } else { @@ -1288,36 +1330,61 @@ export class ChargingStation { } with no connectors configuration defined, using already defined connectors` ); } - // Initialize transaction attributes on connectors - for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { - logger.warn( - `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${ - this.getConnectorStatus(connectorId)?.transactionId - }` - ); - } - if ( - connectorId > 0 && - (this.getConnectorStatus(connectorId)?.transactionStarted === undefined || - this.getConnectorStatus(connectorId)?.transactionStarted === null) - ) { - this.initializeConnectorStatus(connectorId); - } - } } - private checkStationInfoConnectorStatus( - connectorId: number, - connectorStatus: ConnectorStatus - ): void { - if (!Utils.isNullOrUndefined(connectorStatus?.status)) { + private initializeEvses(stationInfo: ChargingStationInfo): void { + if (!stationInfo?.Evses && this.evses.size === 0) { + const logMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`; + logger.error(`${this.logPrefix()} ${logMsg}`); + throw new BaseError(logMsg); + } + if (!stationInfo?.Evses[0]) { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with connector ${connectorId} status configuration defined, undefine it` + } with no evse id 0 configuration` ); - delete connectorStatus.status; + } + if (stationInfo?.Evses) { + const evsesConfigHash = crypto + .createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update(`${JSON.stringify(stationInfo?.Evses)}`) + .digest('hex'); + const evsesConfigChanged = + this.evses?.size !== 0 && this.evsesConfigurationHash !== evsesConfigHash; + if (this.evses?.size === 0 || evsesConfigChanged) { + evsesConfigChanged && this.evses.clear(); + this.evsesConfigurationHash = evsesConfigHash; + const templateMaxEvses = ChargingStationUtils.getMaxNumberOfEvses(stationInfo?.Evses); + if (templateMaxEvses > 0) { + for (const evse in stationInfo.Evses) { + this.evses.set(Utils.convertToInt(evse), { + connectors: ChargingStationUtils.buildConnectorsMap( + stationInfo?.Evses[evse]?.Connectors, + this.logPrefix(), + this.templateFile + ), + availability: AvailabilityType.Operative, + }); + ChargingStationUtils.initializeConnectorsMapStatus( + this.evses.get(Utils.convertToInt(evse))?.connectors, + this.logPrefix() + ); + } + } else { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no evses configuration defined, cannot create evses` + ); + } + } else { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no evses configuration defined, using already defined evses` + ); + } } } @@ -1358,7 +1425,7 @@ export class ChargingStation { fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); } const configurationData: ChargingStationConfiguration = - Utils.cloneObject(this.getConfigurationFromFile()) ?? Constants.EMPTY_OBJECT; + Utils.cloneObject(this.getConfigurationFromFile()) ?? {}; this.ocppConfiguration?.configurationKey && (configurationData.configurationKey = this.ocppConfiguration.configurationKey); this.stationInfo && (configurationData.stationInfo = this.stationInfo); @@ -1510,7 +1577,7 @@ export class ChargingStation { messageType )} is not an array`, undefined, - cachedRequest as unknown as JsonType + cachedRequest as JsonType ); } @@ -1824,15 +1891,7 @@ export class ChargingStation { // Set default status connectorStatus = ConnectorStatusEnum.Available; } - await this.ocppRequestService.requestHandler< - StatusNotificationRequest, - StatusNotificationResponse - >( - this, - RequestCommand.STATUS_NOTIFICATION, - OCPPServiceUtils.buildStatusNotificationRequest(this, connectorId, connectorStatus) - ); - this.getConnectorStatus(connectorId).status = connectorStatus; + await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorStatus); } if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) { await this.ocppRequestService.requestHandler< @@ -1914,11 +1973,7 @@ export class ChargingStation { ); } else { logger.error( - `${this.logPrefix()} WebSocket ping interval set to ${ - webSocketPingInterval - ? Utils.formatDurationSeconds(webSocketPingInterval) - : webSocketPingInterval - }, not starting the WebSocket ping` + `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping` ); } } @@ -1926,17 +1981,17 @@ export class ChargingStation { private stopWebSocketPing(): void { if (this.webSocketPingSetInterval) { clearInterval(this.webSocketPingSetInterval); + delete this.webSocketPingSetInterval; } } private getConfiguredSupervisionUrl(): URL { const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls(); if (Utils.isNotEmptyArray(supervisionUrls)) { + let configuredSupervisionUrlIndex: number; switch (Configuration.getSupervisionUrlDistribution()) { case SupervisionUrlDistribution.RANDOM: - this.configuredSupervisionUrlIndex = Math.floor( - Utils.secureRandom() * supervisionUrls.length - ); + configuredSupervisionUrlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length); break; case SupervisionUrlDistribution.ROUND_ROBIN: case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY: @@ -1949,41 +2004,18 @@ export class ChargingStation { SupervisionUrlDistribution.CHARGING_STATION_AFFINITY }` ); - this.configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; + configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; break; } - return new URL(supervisionUrls[this.configuredSupervisionUrlIndex]); + return new URL(supervisionUrls[configuredSupervisionUrlIndex]); } return new URL(supervisionUrls as string); } - private getHeartbeatInterval(): number { - const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.HeartbeatInterval - ); - if (HeartbeatInterval) { - return Utils.convertToInt(HeartbeatInterval.value) * 1000; - } - const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.HeartBeatInterval - ); - if (HeartBeatInterval) { - return Utils.convertToInt(HeartBeatInterval.value) * 1000; - } - this.stationInfo?.autoRegister === false && - logger.warn( - `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ - Constants.DEFAULT_HEARTBEAT_INTERVAL - }` - ); - return Constants.DEFAULT_HEARTBEAT_INTERVAL; - } - private stopHeartbeat(): void { if (this.heartbeatSetInterval) { clearInterval(this.heartbeatSetInterval); + delete this.heartbeatSetInterval; } } @@ -1994,12 +2026,6 @@ export class ChargingStation { } } - private stopMeterValues(connectorId: number) { - if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { - clearInterval(this.getConnectorStatus(connectorId)?.transactionSetInterval); - } - } - private getReconnectExponentialDelay(): boolean { return this.stationInfo?.reconnectExponentialDelay ?? false; } @@ -2038,7 +2064,7 @@ export class ChargingStation { ); this.openWSConnection( { - ...(this.stationInfo?.wsOptions ?? Constants.EMPTY_OBJECT), + ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout, }, { closeOpened: true } @@ -2058,13 +2084,4 @@ export class ChargingStation { | undefined { return this.getTemplateFromFile()?.AutomaticTransactionGenerator; } - - private initializeConnectorStatus(connectorId: number): void { - this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; - this.getConnectorStatus(connectorId).idTagAuthorized = false; - this.getConnectorStatus(connectorId).transactionRemoteStarted = false; - this.getConnectorStatus(connectorId).transactionStarted = false; - this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0; - this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; - } }