X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=a87ef6f2145bf6c89cd8a946bb27a593366290ee;hb=129fdda549b8c7dc7c43ec5893d14a1151ed61a9;hp=dd7cac5a4e51446d543affaa513db6fe906b140b;hpb=32de5a575189d226213641f5ee36004f8454cb50;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index dd7cac5a..bcd33ccf 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -1,206 +1,292 @@ -// Partial Copyright Jerome Benoit. 2021. All Rights Reserved. - -import crypto from 'crypto'; -import fs from 'fs'; -import path from 'path'; -import { URL } from 'url'; -import { parentPort } from 'worker_threads'; - -import WebSocket, { Data, MessageEvent, RawData } from 'ws'; - -import BaseError from '../exception/BaseError'; -import OCPPError from '../exception/OCPPError'; -import PerformanceStatistics from '../performance/PerformanceStatistics'; -import { AutomaticTransactionGeneratorConfiguration } from '../types/AutomaticTransactionGenerator'; -import ChargingStationConfiguration from '../types/ChargingStationConfiguration'; -import ChargingStationInfo from '../types/ChargingStationInfo'; -import ChargingStationOcppConfiguration from '../types/ChargingStationOcppConfiguration'; -import ChargingStationTemplate, { - CurrentType, - PowerUnits, - WsOptions, -} from '../types/ChargingStationTemplate'; -import { SupervisionUrlDistribution } from '../types/ConfigurationData'; -import { ConnectorStatus } from '../types/ConnectorStatus'; -import { FileType } from '../types/FileType'; -import { JsonType } from '../types/JsonType'; -import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode'; -import { ChargePointStatus } from '../types/ocpp/ChargePointStatus'; -import { ChargingProfile, ChargingRateUnitType } from '../types/ocpp/ChargingProfile'; +// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. + +import { createHash } from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import { type FSWatcher, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { URL } from 'node:url'; +import { parentPort } from 'node:worker_threads'; + +import { millisecondsToSeconds, secondsToMilliseconds } from 'date-fns'; +import merge from 'just-merge'; +import { type RawData, WebSocket } from 'ws'; + +import { AutomaticTransactionGenerator } from './AutomaticTransactionGenerator'; +import { ChargingStationWorkerBroadcastChannel } from './broadcast-channel/ChargingStationWorkerBroadcastChannel'; import { - ConnectorPhaseRotation, - StandardParametersKey, - SupportedFeatureProfiles, - VendorDefaultParametersKey, -} from '../types/ocpp/Configuration'; -import { ErrorType } from '../types/ocpp/ErrorType'; -import { MessageType } from '../types/ocpp/MessageType'; -import { MeterValue, MeterValueMeasurand } from '../types/ocpp/MeterValues'; -import { OCPPVersion } from '../types/ocpp/OCPPVersion'; + addConfigurationKey, + deleteConfigurationKey, + getConfigurationKey, + setConfigurationKeyValue, +} from './ConfigurationKeyUtils'; import { - AvailabilityType, - BootNotificationRequest, - CachedRequest, - HeartbeatRequest, - IncomingRequest, - IncomingRequestCommand, - MeterValuesRequest, - RequestCommand, - StatusNotificationRequest, -} from '../types/ocpp/Requests'; + buildConnectorsMap, + checkChargingStation, + checkConnectorsConfiguration, + checkStationInfoConnectorStatus, + checkTemplate, + createBootNotificationRequest, + createSerialNumber, + getAmperageLimitationUnitDivider, + getBootConnectorStatus, + getChargingStationConnectorChargingProfilesPowerLimit, + getChargingStationId, + getDefaultVoltageOut, + getHashId, + getIdTagsFile, + getMaxNumberOfEvses, + getNumberOfReservableConnectors, + getPhaseRotationValue, + hasFeatureProfile, + hasReservationExpired, + initializeConnectorsMapStatus, + propagateSerialNumber, + removeExpiredReservations, + stationTemplateToStationInfo, + warnTemplateKeysDeprecation, +} from './Helpers'; +import { IdTagsCache } from './IdTagsCache'; import { - BootNotificationResponse, - ErrorResponse, - HeartbeatResponse, - MeterValuesResponse, - RegistrationStatus, - Response, - StatusNotificationResponse, -} from '../types/ocpp/Responses'; + OCPP16IncomingRequestService, + OCPP16RequestService, + OCPP16ResponseService, + OCPP16ServiceUtils, + OCPP20IncomingRequestService, + OCPP20RequestService, + OCPP20ResponseService, + type OCPPIncomingRequestService, + type OCPPRequestService, + OCPPServiceUtils, +} from './ocpp'; +import { SharedLRUCache } from './SharedLRUCache'; +import { BaseError, OCPPError } from '../exception'; +import { PerformanceStatistics } from '../performance'; import { - StartTransactionRequest, - StartTransactionResponse, + type AutomaticTransactionGeneratorConfiguration, + AvailabilityType, + type BootNotificationRequest, + type BootNotificationResponse, + type CachedRequest, + type ChargingStationConfiguration, + ChargingStationEvents, + type ChargingStationInfo, + type ChargingStationOcppConfiguration, + type ChargingStationTemplate, + type ConnectorStatus, + ConnectorStatusEnum, + CurrentType, + type ErrorCallback, + type ErrorResponse, + ErrorType, + type EvseStatus, + type EvseStatusConfiguration, + FileType, + FirmwareStatus, + type FirmwareStatusNotificationRequest, + type FirmwareStatusNotificationResponse, + type FirmwareUpgrade, + type HeartbeatRequest, + type HeartbeatResponse, + type IncomingRequest, + type IncomingRequestCommand, + type JsonType, + MessageType, + type MeterValue, + MeterValueMeasurand, + type MeterValuesRequest, + type MeterValuesResponse, + OCPPVersion, + type OutgoingRequest, + PowerUnits, + RegistrationStatusEnumType, + RequestCommand, + type Reservation, + type ReservationKey, + ReservationTerminationReason, + type Response, + StandardParametersKey, + type Status, + type StatusNotificationRequest, + type StatusNotificationResponse, StopTransactionReason, - StopTransactionRequest, - StopTransactionResponse, -} from '../types/ocpp/Transaction'; -import { ProcedureName } from '../types/UIProtocol'; -import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket'; -import { WorkerBroadcastChannelData } from '../types/WorkerBroadcastChannel'; -import Configuration from '../utils/Configuration'; -import Constants from '../utils/Constants'; -import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils'; -import FileUtils from '../utils/FileUtils'; -import logger from '../utils/Logger'; -import Utils from '../utils/Utils'; -import AuthorizedTagsCache from './AuthorizedTagsCache'; -import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; -import { ChargingStationConfigurationUtils } from './ChargingStationConfigurationUtils'; -import { ChargingStationUtils } from './ChargingStationUtils'; -import { MessageChannelUtils } from './MessageChannelUtils'; -import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService'; -import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService'; -import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService'; -import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils'; -import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService'; -import OCPPRequestService from './ocpp/OCPPRequestService'; -import SharedLRUCache from './SharedLRUCache'; -import WorkerBroadcastChannel from './WorkerBroadcastChannel'; - -export default class ChargingStation { - public hashId!: string; + type StopTransactionRequest, + type StopTransactionResponse, + SupervisionUrlDistribution, + SupportedFeatureProfiles, + VendorParametersKey, + type WSError, + WebSocketCloseEventStatusCode, + type WsOptions, +} from '../types'; +import { + ACElectricUtils, + AsyncLock, + AsyncLockType, + Configuration, + Constants, + DCElectricUtils, + buildChargingStationAutomaticTransactionGeneratorConfiguration, + buildConnectorsStatus, + buildEvsesStatus, + buildStartedMessage, + buildStoppedMessage, + buildUpdatedMessage, + cloneObject, + convertToBoolean, + convertToInt, + exponentialDelay, + formatDurationMilliSeconds, + formatDurationSeconds, + getRandomInteger, + getWebSocketCloseEventStatusString, + handleFileException, + isNotEmptyArray, + isNotEmptyString, + isNullOrUndefined, + isUndefined, + logPrefix, + logger, + min, + once, + roundTo, + secureRandom, + sleep, + watchJsonFile, +} from '../utils'; + +export class ChargingStation extends EventEmitter { + public readonly index: number; public readonly templateFile: string; - public authorizedTagsCache: AuthorizedTagsCache; - public stationInfo!: ChargingStationInfo; + public started: boolean; + public starting: boolean; + public idTagsCache: IdTagsCache; + public automaticTransactionGenerator!: AutomaticTransactionGenerator | undefined; + public ocppConfiguration!: ChargingStationOcppConfiguration | undefined; + public wsConnection: WebSocket | null; public readonly connectors: Map; - public ocppConfiguration!: ChargingStationOcppConfiguration; - public wsConnection!: WebSocket; + public readonly evses: Map; public readonly requests: Map; - public performanceStatistics!: PerformanceStatistics; - public heartbeatSetInterval!: NodeJS.Timeout; + public performanceStatistics!: PerformanceStatistics | undefined; + public heartbeatSetInterval?: NodeJS.Timeout; public ocppRequestService!: OCPPRequestService; - public bootNotificationResponse!: BootNotificationResponse | null; + public bootNotificationRequest!: BootNotificationRequest; + public bootNotificationResponse!: BootNotificationResponse | undefined; public powerDivider!: number; - private readonly index: number; + private internalStationInfo!: ChargingStationInfo; + private stopping: boolean; private configurationFile!: string; private configurationFileHash!: string; - private bootNotificationRequest!: BootNotificationRequest; private connectorsConfigurationHash!: string; + private evsesConfigurationHash!: string; + private automaticTransactionGeneratorConfiguration?: AutomaticTransactionGeneratorConfiguration; private ocppIncomingRequestService!: OCPPIncomingRequestService; private readonly messageBuffer: Set; private configuredSupervisionUrl!: URL; private wsConnectionRestarted: boolean; private autoReconnectRetryCount: number; - private stopped: boolean; - private templateFileWatcher!: fs.FSWatcher; + private templateFileWatcher!: FSWatcher | undefined; + private templateFileHash!: string; private readonly sharedLRUCache: SharedLRUCache; - private automaticTransactionGenerator!: AutomaticTransactionGenerator; - private webSocketPingSetInterval!: NodeJS.Timeout; - private workerBroadcastChannel: WorkerBroadcastChannel; + private webSocketPingSetInterval?: NodeJS.Timeout; + private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel; + private reservationExpirationSetInterval?: NodeJS.Timeout; constructor(index: number, templateFile: string) { - this.index = index; - this.templateFile = templateFile; - this.stopped = false; + super(); + this.started = false; + this.starting = false; + this.stopping = false; + this.wsConnection = null; this.wsConnectionRestarted = false; this.autoReconnectRetryCount = 0; - this.sharedLRUCache = SharedLRUCache.getInstance(); - this.authorizedTagsCache = AuthorizedTagsCache.getInstance(); + this.index = index; + this.templateFile = templateFile; this.connectors = new Map(); + this.evses = new Map(); this.requests = new Map(); this.messageBuffer = new Set(); - this.workerBroadcastChannel = new WorkerBroadcastChannel(); - - this.workerBroadcastChannel.onmessage = this.handleWorkerBroadcastChannelMessage.bind(this) as ( - message: MessageEvent - ) => void; + this.sharedLRUCache = SharedLRUCache.getInstance(); + this.idTagsCache = IdTagsCache.getInstance(); + this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this); + + this.on(ChargingStationEvents.started, () => { + parentPort?.postMessage(buildStartedMessage(this)); + }); + this.on(ChargingStationEvents.stopped, () => { + parentPort?.postMessage(buildStoppedMessage(this)); + }); + this.on(ChargingStationEvents.updated, () => { + parentPort?.postMessage(buildUpdatedMessage(this)); + }); this.initialize(); } + public get hasEvses(): boolean { + return this.connectors.size === 0 && this.evses.size > 0; + } + + public get stationInfo(): ChargingStationInfo { + return { + ...{ + enableStatistics: false, + remoteAuthorization: true, + currentOutType: CurrentType.AC, + mainVoltageMeterValues: true, + phaseLineToLineVoltageMeterValues: false, + customValueLimitationMeterValues: true, + ocppStrictCompliance: true, + outOfOrderEndMeterValues: false, + beginEndMeterValues: false, + meteringPerTransaction: true, + transactionDataMeterValues: false, + supervisionUrlOcppConfiguration: false, + supervisionUrlOcppKey: VendorParametersKey.ConnectionUrl, + ocppVersion: OCPPVersion.VERSION_16, + ocppPersistentConfiguration: true, + stationInfoPersistentConfiguration: true, + automaticTransactionGeneratorPersistentConfiguration: true, + autoReconnectMaxRetries: -1, + registrationMaxRetries: -1, + reconnectExponentialDelay: false, + stopTransactionsOnStopped: true, + }, + ...this.internalStationInfo, + }; + } + private get wsConnectionUrl(): URL { return new URL( - (this.getSupervisionUrlOcppConfiguration() - ? ChargingStationConfigurationUtils.getConfigurationKey( - this, - this.getSupervisionUrlOcppKey() - ).value - : this.configuredSupervisionUrl.href) + - '/' + - this.stationInfo.chargingStationId + `${ + this.stationInfo?.supervisionUrlOcppConfiguration && + isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) && + isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)?.value) + ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)!.value + : this.configuredSupervisionUrl.href + }/${this.stationInfo.chargingStationId}`, ); } - public logPrefix(): string { - return Utils.logPrefix( + public logPrefix = (): string => { + return logPrefix( ` ${ - this?.stationInfo?.chargingStationId ?? - ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) - } |` + (isNotEmptyString(this?.stationInfo?.chargingStationId) + ? this?.stationInfo?.chargingStationId + : getChargingStationId(this.index, this.getTemplateFromFile()!)) ?? + 'Error at building log prefix' + } |`, ); - } + }; - public getBootNotificationRequest(): BootNotificationRequest { - return this.bootNotificationRequest; + public hasIdTags(): boolean { + return isNotEmptyArray(this.idTagsCache.getIdTags(getIdTagsFile(this.stationInfo)!)); } - public getRandomIdTag(): string { - const authorizationFile = ChargingStationUtils.getAuthorizationFile(this.stationInfo); - const index = Math.floor( - Utils.secureRandom() * this.authorizedTagsCache.getAuthorizedTags(authorizationFile).length - ); - return this.authorizedTagsCache.getAuthorizedTags(authorizationFile)[index]; - } - - public hasAuthorizedTags(): boolean { - return !Utils.isEmptyArray( - this.authorizedTagsCache.getAuthorizedTags( - ChargingStationUtils.getAuthorizationFile(this.stationInfo) - ) - ); - } - - public getEnableStatistics(): boolean | undefined { - return !Utils.isUndefined(this.stationInfo.enableStatistics) - ? this.stationInfo.enableStatistics - : true; - } - - public getMayAuthorizeAtRemoteStart(): boolean | undefined { - return this.stationInfo.mayAuthorizeAtRemoteStart ?? true; - } - - public getPayloadSchemaValidation(): boolean | undefined { - return this.stationInfo.payloadSchemaValidation ?? true; - } - - public getNumberOfPhases(stationInfo?: ChargingStationInfo): number | undefined { + public getNumberOfPhases(stationInfo?: ChargingStationInfo): number { const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo; switch (this.getCurrentOutType(stationInfo)) { case CurrentType.AC: - return !Utils.isUndefined(localStationInfo.numberOfPhases) - ? localStationInfo.numberOfPhases - : 3; + return !isUndefined(localStationInfo.numberOfPhases) ? localStationInfo.numberOfPhases! : 3; case CurrentType.DC: return 0; } @@ -210,207 +296,260 @@ export default class ChargingStation { return this?.wsConnection?.readyState === WebSocket.OPEN; } - public getRegistrationStatus(): RegistrationStatus { + public getRegistrationStatus(): RegistrationStatusEnumType | undefined { return this?.bootNotificationResponse?.status; } - public isInUnknownState(): boolean { - return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status); + public inUnknownState(): boolean { + return isNullOrUndefined(this?.bootNotificationResponse?.status); } - public isInPendingState(): boolean { - return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING; + public inPendingState(): boolean { + return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.PENDING; } - public isInAcceptedState(): boolean { - return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; + public inAcceptedState(): boolean { + return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.ACCEPTED; } - public isInRejectedState(): boolean { - return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED; + public inRejectedState(): boolean { + return this?.bootNotificationResponse?.status === RegistrationStatusEnumType.REJECTED; } public isRegistered(): boolean { - return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState()); + return ( + this.inUnknownState() === false && + (this.inAcceptedState() === true || this.inPendingState() === true) + ); } public isChargingStationAvailable(): boolean { - return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE; - } - - public isConnectorAvailable(id: number): boolean { - return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE; + return this.getConnectorStatus(0)?.availability === AvailabilityType.Operative; } - public getNumberOfConnectors(): number { - return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size; + public hasConnector(connectorId: number): boolean { + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + if (evseStatus.connectors.has(connectorId)) { + return true; + } + } + return false; + } + return this.connectors.has(connectorId); } - public getConnectorStatus(id: number): ConnectorStatus { - return this.connectors.get(id); + public isConnectorAvailable(connectorId: number): boolean { + return ( + connectorId > 0 && + this.getConnectorStatus(connectorId)?.availability === AvailabilityType.Operative + ); } - public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType { - return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC; + public getNumberOfConnectors(): number { + if (this.hasEvses) { + let numberOfConnectors = 0; + for (const [evseId, evseStatus] of this.evses) { + if (evseId > 0) { + numberOfConnectors += evseStatus.connectors.size; + } + } + return numberOfConnectors; + } + return this.connectors.has(0) ? this.connectors.size - 1 : this.connectors.size; } - public getOcppStrictCompliance(): boolean { - return this.stationInfo?.ocppStrictCompliance ?? false; + public getNumberOfEvses(): number { + return this.evses.has(0) ? this.evses.size - 1 : this.evses.size; } - public getVoltageOut(stationInfo?: ChargingStationInfo): number | undefined { - const defaultVoltageOut = ChargingStationUtils.getDefaultVoltageOut( - this.getCurrentOutType(stationInfo), - this.templateFile, - this.logPrefix() - ); - const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo; - return !Utils.isUndefined(localStationInfo.voltageOut) - ? localStationInfo.voltageOut - : defaultVoltageOut; + public getConnectorStatus(connectorId: number): ConnectorStatus | undefined { + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + if (evseStatus.connectors.has(connectorId)) { + return evseStatus.connectors.get(connectorId); + } + } + return undefined; + } + return this.connectors.get(connectorId); } public getConnectorMaximumAvailablePower(connectorId: number): number { - let connectorAmperageLimitationPowerLimit: number; + let connectorAmperageLimitationPowerLimit: number | undefined; if ( - !Utils.isNullOrUndefined(this.getAmperageLimitation()) && - this.getAmperageLimitation() < this.stationInfo.maximumAmperage + !isNullOrUndefined(this.getAmperageLimitation()) && + this.getAmperageLimitation()! < this.stationInfo.maximumAmperage! ) { connectorAmperageLimitationPowerLimit = - (this.getCurrentOutType() === CurrentType.AC + (this.stationInfo?.currentOutType === CurrentType.AC ? ACElectricUtils.powerTotal( this.getNumberOfPhases(), - this.getVoltageOut(), - this.getAmperageLimitation() * this.getNumberOfConnectors() + this.stationInfo.voltageOut!, + this.getAmperageLimitation()! * + (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()), ) - : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) / + : DCElectricUtils.power(this.stationInfo.voltageOut!, this.getAmperageLimitation()!)) / this.powerDivider; } - const connectorMaximumPower = this.getMaximumPower() / this.powerDivider; - const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId); - return Math.min( + const connectorMaximumPower = this.stationInfo.maximumPower! / this.powerDivider; + const connectorChargingProfilesPowerLimit = + getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId); + return min( isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower, - isNaN(connectorAmperageLimitationPowerLimit) + isNaN(connectorAmperageLimitationPowerLimit!) ? Infinity - : connectorAmperageLimitationPowerLimit, - isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit + : connectorAmperageLimitationPowerLimit!, + isNaN(connectorChargingProfilesPowerLimit!) ? Infinity : connectorChargingProfilesPowerLimit!, ); } public getTransactionIdTag(transactionId: number): string | undefined { - for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { - return this.getConnectorStatus(connectorId).transactionIdTag; + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + for (const connectorStatus of evseStatus.connectors.values()) { + if (connectorStatus.transactionId === transactionId) { + return connectorStatus.transactionIdTag; + } + } + } + } else { + for (const connectorId of this.connectors.keys()) { + if (this.getConnectorStatus(connectorId)?.transactionId === transactionId) { + return this.getConnectorStatus(connectorId)?.transactionIdTag; + } } } } - public getOutOfOrderEndMeterValues(): boolean { - return this.stationInfo?.outOfOrderEndMeterValues ?? false; - } - - public getBeginEndMeterValues(): boolean { - return this.stationInfo?.beginEndMeterValues ?? false; - } - - public getMeteringPerTransaction(): boolean { - return this.stationInfo?.meteringPerTransaction ?? true; - } - - public getTransactionDataMeterValues(): boolean { - return this.stationInfo?.transactionDataMeterValues ?? false; - } - - public getMainVoltageMeterValues(): boolean { - return this.stationInfo?.mainVoltageMeterValues ?? true; - } - - public getPhaseLineToLineVoltageMeterValues(): boolean { - return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false; - } - - public getCustomValueLimitationMeterValues(): boolean { - return this.stationInfo?.customValueLimitationMeterValues ?? true; + public getNumberOfRunningTransactions(): number { + let numberOfRunningTransactions = 0; + if (this.hasEvses) { + for (const [evseId, evseStatus] of this.evses) { + if (evseId === 0) { + continue; + } + for (const connectorStatus of evseStatus.connectors.values()) { + if (connectorStatus.transactionStarted === true) { + ++numberOfRunningTransactions; + } + } + } + } else { + for (const connectorId of this.connectors.keys()) { + if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { + ++numberOfRunningTransactions; + } + } + } + return numberOfRunningTransactions; } public getConnectorIdByTransactionId(transactionId: number): number | undefined { - for (const connectorId of this.connectors.keys()) { - if ( - connectorId > 0 && - this.getConnectorStatus(connectorId)?.transactionId === transactionId - ) { - return connectorId; + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + for (const [connectorId, connectorStatus] of evseStatus.connectors) { + if (connectorStatus.transactionId === transactionId) { + return connectorId; + } + } + } + } else { + for (const connectorId of this.connectors.keys()) { + if (this.getConnectorStatus(connectorId)?.transactionId === transactionId) { + return connectorId; + } } } } - public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { - const transactionConnectorStatus = this.getConnectorStatus( - this.getConnectorIdByTransactionId(transactionId) + public getEnergyActiveImportRegisterByTransactionId( + transactionId: number, + rounded = false, + ): number { + return this.getEnergyActiveImportRegister( + this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId)!)!, + rounded, ); - if (this.getMeteringPerTransaction()) { - return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue; - } - return transactionConnectorStatus?.energyActiveImportRegisterValue; } - public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined { - const connectorStatus = this.getConnectorStatus(connectorId); - if (this.getMeteringPerTransaction()) { - return connectorStatus?.transactionEnergyActiveImportRegisterValue; - } - return connectorStatus?.energyActiveImportRegisterValue; + public getEnergyActiveImportRegisterByConnectorId(connectorId: number, rounded = false): number { + return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId)!, rounded); } public getAuthorizeRemoteTxRequests(): boolean { - const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey( + const authorizeRemoteTxRequests = getConfigurationKey( this, - StandardParametersKey.AuthorizeRemoteTxRequests + StandardParametersKey.AuthorizeRemoteTxRequests, ); - return authorizeRemoteTxRequests - ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) - : false; + return authorizeRemoteTxRequests ? convertToBoolean(authorizeRemoteTxRequests.value) : false; } public getLocalAuthListEnabled(): boolean { - const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey( + const localAuthListEnabled = getConfigurationKey( this, - StandardParametersKey.LocalAuthListEnabled + StandardParametersKey.LocalAuthListEnabled, ); - return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; + return localAuthListEnabled ? convertToBoolean(localAuthListEnabled.value) : false; } - public startHeartbeat(): void { + public getHeartbeatInterval(): number { + const HeartbeatInterval = getConfigurationKey(this, StandardParametersKey.HeartbeatInterval); + if (HeartbeatInterval) { + return secondsToMilliseconds(convertToInt(HeartbeatInterval.value)); + } + const HeartBeatInterval = getConfigurationKey(this, StandardParametersKey.HeartBeatInterval); + if (HeartBeatInterval) { + return secondsToMilliseconds(convertToInt(HeartBeatInterval.value)); + } + 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.stationInfo?.supervisionUrlOcppConfiguration === true && + isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) ) { - // eslint-disable-next-line @typescript-eslint/no-misused-promises - this.heartbeatSetInterval = setInterval(async (): Promise => { - await this.ocppRequestService.requestHandler( - this, - RequestCommand.HEARTBEAT - ); + setConfigurationKeyValue(this, this.stationInfo.supervisionUrlOcppKey!, 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) + .catch((error) => { + logger.error( + `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`, + error, + ); + }); }, this.getHeartbeatInterval()); logger.info( - this.logPrefix() + - ' Heartbeat started every ' + - Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) + `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds( + this.getHeartbeatInterval(), + )}`, ); } else if (this.heartbeatSetInterval) { logger.info( - this.logPrefix() + - ' Heartbeat already started every ' + - Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) + `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds( + this.getHeartbeatInterval(), + )}`, ); } 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`, ); } } @@ -432,825 +571,1165 @@ export default 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}`, ); 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}`, ); return; } - if (!this.getConnectorStatus(connectorId)?.transactionStarted) { + 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 ( - this.getConnectorStatus(connectorId)?.transactionStarted && - !this.getConnectorStatus(connectorId)?.transactionId + this.getConnectorStatus(connectorId)?.transactionStarted === true && + 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; } if (interval > 0) { - // eslint-disable-next-line @typescript-eslint/no-misused-promises - this.getConnectorStatus(connectorId).transactionSetInterval = setInterval( - // eslint-disable-next-line @typescript-eslint/no-misused-promises - async (): Promise => { - // FIXME: Implement OCPP version agnostic helpers - const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue( - this, - connectorId, - this.getConnectorStatus(connectorId).transactionId, - interval - ); - await this.ocppRequestService.requestHandler( + this.getConnectorStatus(connectorId)!.transactionSetInterval = setInterval(() => { + // FIXME: Implement OCPP version agnostic helpers + const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue( + this, + connectorId, + this.getConnectorStatus(connectorId)!.transactionId!, + interval, + ); + this.ocppRequestService + .requestHandler( this, RequestCommand.METER_VALUES, { connectorId, - transactionId: this.getConnectorStatus(connectorId).transactionId, + transactionId: this.getConnectorStatus(connectorId)?.transactionId, meterValue: [meterValue], - } - ); - }, - interval - ); + }, + ) + .catch((error) => { + logger.error( + `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`, + error, + ); + }); + }, interval); } else { 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 start(): void { - if (this.getEnableStatistics()) { - this.performanceStatistics.start(); + public stopMeterValues(connectorId: number) { + if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { + clearInterval(this.getConnectorStatus(connectorId)?.transactionSetInterval); } - this.openWSConnection(); - // Monitor charging station template file - this.templateFileWatcher = FileUtils.watchJsonFile( - this.logPrefix(), - FileType.ChargingStationTemplate, - this.templateFile, - null, - (event, filename): void => { - if (filename && event === 'change') { - try { - logger.debug( - `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ - this.templateFile - } file have changed, reload` - ); - this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash); - // Initialize - this.initialize(); - // Restart the ATG - this.stopAutomaticTransactionGenerator(); - 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:`, - error - ); - } + } + + public start(): void { + if (this.started === false) { + if (this.starting === false) { + this.starting = true; + if (this.stationInfo?.enableStatistics === true) { + this.performanceStatistics?.start(); } + if (hasFeatureProfile(this, SupportedFeatureProfiles.Reservation)) { + this.startReservationExpirationSetInterval(); + } + this.openWSConnection(); + // Monitor charging station template file + this.templateFileWatcher = watchJsonFile( + this.templateFile, + FileType.ChargingStationTemplate, + this.logPrefix(), + undefined, + (event, filename): void => { + if (isNotEmptyString(filename) && event === 'change') { + try { + logger.debug( + `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ + this.templateFile + } file have changed, reload`, + ); + this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash); + // Initialize + this.initialize(); + this.idTagsCache.deleteIdTags(getIdTagsFile(this.stationInfo)!); + // Restart the ATG + this.stopAutomaticTransactionGenerator(); + delete this.automaticTransactionGeneratorConfiguration; + if (this.getAutomaticTransactionGeneratorConfiguration().enable === true) { + this.startAutomaticTransactionGenerator(); + } + if (this.stationInfo?.enableStatistics === true) { + 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:`, + error, + ); + } + } + }, + ); + this.started = true; + this.emit(ChargingStationEvents.started); + this.starting = false; + } else { + logger.warn(`${this.logPrefix()} Charging station is already starting...`); } - ); - parentPort.postMessage(MessageChannelUtils.buildStartedMessage(this)); - } - - public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise { - // Stop message sequence - await this.stopMessageSequence(reason); - for (const connectorId of this.connectors.keys()) { - if (connectorId > 0) { - await this.ocppRequestService.requestHandler< - StatusNotificationRequest, - StatusNotificationResponse - >(this, RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: ChargePointStatus.UNAVAILABLE, - errorCode: ChargePointErrorCode.NO_ERROR, - }); - this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE; - } + } else { + logger.warn(`${this.logPrefix()} Charging station is already started...`); } - this.closeWSConnection(); - if (this.getEnableStatistics()) { - this.performanceStatistics.stop(); + } + + public async stop(reason?: StopTransactionReason, stopTransactions?: boolean): Promise { + if (this.started === true) { + if (this.stopping === false) { + this.stopping = true; + await this.stopMessageSequence(reason, stopTransactions); + this.closeWSConnection(); + if (this.stationInfo?.enableStatistics === true) { + this.performanceStatistics?.stop(); + } + if (hasFeatureProfile(this, SupportedFeatureProfiles.Reservation)) { + this.stopReservationExpirationSetInterval(); + } + this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); + this.templateFileWatcher?.close(); + this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash); + delete this.bootNotificationResponse; + this.started = false; + this.saveConfiguration(); + this.emit(ChargingStationEvents.stopped); + this.stopping = false; + } else { + logger.warn(`${this.logPrefix()} Charging station is already stopping...`); + } + } else { + logger.warn(`${this.logPrefix()} Charging station is already stopped...`); } - this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); - this.templateFileWatcher.close(); - this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash); - this.bootNotificationResponse = null; - parentPort.postMessage(MessageChannelUtils.buildStoppedMessage(this)); - this.stopped = true; } public async reset(reason?: StopTransactionReason): Promise { await this.stop(reason); - await Utils.sleep(this.stationInfo.resetTime); + await sleep(this.stationInfo.resetTime!); this.initialize(); this.start(); } public saveOcppConfiguration(): void { - if (this.getOcppPersistentConfiguration()) { + if (this.stationInfo?.ocppPersistentConfiguration === true) { this.saveConfiguration(); } } - public getChargingProfilePowerLimit(connectorId: number): number | undefined { - let limit: number, matchingChargingProfile: ChargingProfile; - let chargingProfiles: ChargingProfile[] = []; - // Get charging profiles for connector and sort by stack level - chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort( - (a, b) => b.stackLevel - a.stackLevel - ); - // Get profiles on connector 0 - if (this.getConnectorStatus(0).chargingProfiles) { - chargingProfiles.push( - ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel) - ); + public bufferMessage(message: string): void { + this.messageBuffer.add(message); + } + + public openWSConnection( + options?: WsOptions, + params?: { closeOpened?: boolean; terminateOpened?: boolean }, + ): void { + options = { + handshakeTimeout: secondsToMilliseconds(this.getConnectionTimeout()), + ...this.stationInfo?.wsOptions, + ...options, + }; + params = { ...{ closeOpened: false, terminateOpened: false }, ...params }; + if (!checkChargingStation(this, this.logPrefix())) { + return; + } + if ( + !isNullOrUndefined(this.stationInfo.supervisionUser) && + !isNullOrUndefined(this.stationInfo.supervisionPassword) + ) { + options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; } - if (!Utils.isEmptyArray(chargingProfiles)) { - const result = ChargingStationUtils.getLimitFromChargingProfiles( - chargingProfiles, - Utils.logPrefix() + if (params?.closeOpened) { + this.closeWSConnection(); + } + if (params?.terminateOpened) { + this.terminateWSConnection(); + } + + if (this.isWebSocketConnectionOpened() === true) { + logger.warn( + `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`, ); - if (!Utils.isNullOrUndefined(result)) { - limit = result.limit; - matchingChargingProfile = result.matchingChargingProfile; - switch (this.getCurrentOutType()) { - case CurrentType.AC: - limit = - matchingChargingProfile.chargingSchedule.chargingRateUnit === - ChargingRateUnitType.WATT - ? limit - : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit); - break; - case CurrentType.DC: - limit = - matchingChargingProfile.chargingSchedule.chargingRateUnit === - ChargingRateUnitType.WATT - ? limit - : DCElectricUtils.power(this.getVoltageOut(), limit); - } + return; + } - const connectorMaximumPower = this.getMaximumPower() / this.powerDivider; - if (limit > connectorMaximumPower) { - logger.error( - `${this.logPrefix()} Charging profile id ${ - matchingChargingProfile.chargingProfileId - } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`, - this.getConnectorStatus(connectorId).chargingProfiles - ); - limit = connectorMaximumPower; - } + logger.info( + `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`, + ); + + this.wsConnection = new WebSocket( + this.wsConnectionUrl, + `ocpp${this.stationInfo?.ocppVersion}`, + options, + ); + + // Handle WebSocket message + this.wsConnection.on( + 'message', + this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void, + ); + // Handle WebSocket error + this.wsConnection.on( + 'error', + this.onError.bind(this) as (this: WebSocket, error: Error) => void, + ); + // Handle WebSocket close + this.wsConnection.on( + 'close', + this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void, + ); + // Handle WebSocket open + this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void); + // Handle WebSocket ping + this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void); + // Handle WebSocket pong + this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void); + } + + public closeWSConnection(): void { + if (this.isWebSocketConnectionOpened() === true) { + this.wsConnection?.close(); + this.wsConnection = null; + } + } + + public getAutomaticTransactionGeneratorConfiguration(): AutomaticTransactionGeneratorConfiguration { + if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration)) { + let automaticTransactionGeneratorConfiguration: + | AutomaticTransactionGeneratorConfiguration + | undefined; + const stationTemplate = this.getTemplateFromFile(); + const stationConfiguration = this.getConfigurationFromFile(); + if ( + this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration === true && + stationConfiguration?.stationInfo?.templateHash === stationTemplate?.templateHash && + stationConfiguration?.automaticTransactionGenerator + ) { + automaticTransactionGeneratorConfiguration = + stationConfiguration?.automaticTransactionGenerator; + } else { + automaticTransactionGeneratorConfiguration = stationTemplate?.AutomaticTransactionGenerator; } + this.automaticTransactionGeneratorConfiguration = { + ...Constants.DEFAULT_ATG_CONFIGURATION, + ...automaticTransactionGeneratorConfiguration, + }; } - return limit; + return this.automaticTransactionGeneratorConfiguration!; } - public setChargingProfile(connectorId: number, cp: ChargingProfile): void { - if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) { - logger.error( - `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization` + public getAutomaticTransactionGeneratorStatuses(): Status[] | undefined { + return this.getConfigurationFromFile()?.automaticTransactionGeneratorStatuses; + } + + public startAutomaticTransactionGenerator(connectorIds?: number[]): void { + this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this); + if (isNotEmptyArray(connectorIds)) { + for (const connectorId of connectorIds!) { + this.automaticTransactionGenerator?.startConnector(connectorId); + } + } else { + this.automaticTransactionGenerator?.start(); + } + this.saveAutomaticTransactionGeneratorConfiguration(); + this.emit(ChargingStationEvents.updated); + } + + public stopAutomaticTransactionGenerator(connectorIds?: number[]): void { + if (isNotEmptyArray(connectorIds)) { + for (const connectorId of connectorIds!) { + this.automaticTransactionGenerator?.stopConnector(connectorId); + } + } else { + this.automaticTransactionGenerator?.stop(); + } + this.saveAutomaticTransactionGeneratorConfiguration(); + this.emit(ChargingStationEvents.updated); + } + + public async stopTransactionOnConnector( + connectorId: number, + reason?: StopTransactionReason, + ): Promise { + const transactionId = this.getConnectorStatus(connectorId)?.transactionId; + if ( + this.stationInfo?.beginEndMeterValues === true && + this.stationInfo?.ocppStrictCompliance === true && + this.stationInfo?.outOfOrderEndMeterValues === false + ) { + // FIXME: Implement OCPP version agnostic helpers + const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( + this, + connectorId, + this.getEnergyActiveImportRegisterByTransactionId(transactionId!), + ); + await this.ocppRequestService.requestHandler( + this, + RequestCommand.METER_VALUES, + { + connectorId, + transactionId, + meterValue: [transactionEndMeterValue], + }, ); - this.getConnectorStatus(connectorId).chargingProfiles = []; } - if (!Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles)) { - logger.error( - `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization` + return this.ocppRequestService.requestHandler( + this, + RequestCommand.STOP_TRANSACTION, + { + transactionId, + meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId!, true), + ...(isNullOrUndefined(reason) && { reason }), + }, + ); + } + + public getReserveConnectorZeroSupported(): boolean { + return convertToBoolean( + getConfigurationKey(this, StandardParametersKey.ReserveConnectorZeroSupported)!.value, + ); + } + + public async addReservation(reservation: Reservation): Promise { + const reservationFound = this.getReservationBy('reservationId', reservation.reservationId); + if (!isUndefined(reservationFound)) { + await this.removeReservation( + reservationFound!, + ReservationTerminationReason.REPLACE_EXISTING, ); - this.getConnectorStatus(connectorId).chargingProfiles = []; - } - let cpReplaced = false; - if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { - this.getConnectorStatus(connectorId).chargingProfiles?.forEach( - (chargingProfile: ChargingProfile, index: number) => { - if ( - chargingProfile.chargingProfileId === cp.chargingProfileId || - (chargingProfile.stackLevel === cp.stackLevel && - chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose) - ) { - this.getConnectorStatus(connectorId).chargingProfiles[index] = cp; - cpReplaced = true; + } + this.getConnectorStatus(reservation.connectorId)!.reservation = reservation; + await OCPPServiceUtils.sendAndSetConnectorStatus( + this, + reservation.connectorId, + ConnectorStatusEnum.Reserved, + undefined, + { send: reservation.connectorId !== 0 }, + ); + } + + public async removeReservation( + reservation: Reservation, + reason: ReservationTerminationReason, + ): Promise { + const connector = this.getConnectorStatus(reservation.connectorId)!; + switch (reason) { + case ReservationTerminationReason.CONNECTOR_STATE_CHANGED: + case ReservationTerminationReason.TRANSACTION_STARTED: + delete connector.reservation; + break; + case ReservationTerminationReason.RESERVATION_CANCELED: + case ReservationTerminationReason.REPLACE_EXISTING: + case ReservationTerminationReason.EXPIRED: + await OCPPServiceUtils.sendAndSetConnectorStatus( + this, + reservation.connectorId, + ConnectorStatusEnum.Available, + undefined, + { send: reservation.connectorId !== 0 }, + ); + delete connector.reservation; + break; + default: + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions + throw new BaseError(`Unknown reservation termination reason '${reason}'`); + } + } + + public getReservationBy( + filterKey: ReservationKey, + value: number | string, + ): Reservation | undefined { + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + for (const connectorStatus of evseStatus.connectors.values()) { + if (connectorStatus?.reservation?.[filterKey] === value) { + return connectorStatus.reservation; } } - ); + } + } else { + for (const connectorStatus of this.connectors.values()) { + if (connectorStatus?.reservation?.[filterKey] === value) { + return connectorStatus.reservation; + } + } } - !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp); } - 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); + public isConnectorReservable( + reservationId: number, + idTag?: string, + connectorId?: number, + ): boolean { + const reservation = this.getReservationBy('reservationId', reservationId); + const reservationExists = !isUndefined(reservation) && !hasReservationExpired(reservation!); + if (arguments.length === 1) { + return !reservationExists; + } else if (arguments.length > 1) { + const userReservation = !isUndefined(idTag) + ? this.getReservationBy('idTag', idTag!) + : undefined; + const userReservationExists = + !isUndefined(userReservation) && !hasReservationExpired(userReservation!); + const notConnectorZero = isUndefined(connectorId) ? true : connectorId! > 0; + const freeConnectorsAvailable = this.getNumberOfReservableConnectors() > 0; + return ( + !reservationExists && !userReservationExists && notConnectorZero && freeConnectorsAvailable + ); + } + return false; } - public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) { - return ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.SupportedFeatureProfiles - )?.value.includes(featureProfile); + private startReservationExpirationSetInterval(customInterval?: number): void { + const interval = customInterval ?? Constants.DEFAULT_RESERVATION_EXPIRATION_INTERVAL; + if (interval > 0) { + logger.info( + `${this.logPrefix()} Reservation expiration date checks started every ${formatDurationMilliSeconds( + interval, + )}`, + ); + this.reservationExpirationSetInterval = setInterval((): void => { + removeExpiredReservations(this).catch(Constants.EMPTY_FUNCTION); + }, interval); + } } - public bufferMessage(message: string): void { - this.messageBuffer.add(message); + private stopReservationExpirationSetInterval(): void { + if (!isNullOrUndefined(this.reservationExpirationSetInterval)) { + clearInterval(this.reservationExpirationSetInterval); + } } - private flushMessageBuffer() { - if (this.messageBuffer.size > 0) { - this.messageBuffer.forEach((message) => { - // TODO: evaluate the need to track performance - this.wsConnection.send(message); - this.messageBuffer.delete(message); - }); + // private restartReservationExpiryDateSetInterval(): void { + // this.stopReservationExpirationSetInterval(); + // this.startReservationExpirationSetInterval(); + // } + + private getNumberOfReservableConnectors(): number { + let numberOfReservableConnectors = 0; + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + numberOfReservableConnectors += getNumberOfReservableConnectors(evseStatus.connectors); + } + } else { + numberOfReservableConnectors = getNumberOfReservableConnectors(this.connectors); } + return numberOfReservableConnectors - this.getNumberOfReservationsOnConnectorZero(); } - private getSupervisionUrlOcppConfiguration(): boolean { - return this.stationInfo.supervisionUrlOcppConfiguration ?? false; + private getNumberOfReservationsOnConnectorZero(): number { + if ( + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + (this.hasEvses && this.evses.get(0)?.connectors.get(0)?.reservation) || + (!this.hasEvses && this.connectors.get(0)?.reservation) + ) { + return 1; + } + return 0; } - private getSupervisionUrlOcppKey(): string { - return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; + private flushMessageBuffer(): void { + if (this.messageBuffer.size > 0) { + for (const message of this.messageBuffer.values()) { + let beginId: string | undefined; + let commandName: RequestCommand | undefined; + const [messageType] = JSON.parse(message) as OutgoingRequest | Response | ErrorResponse; + const isRequest = messageType === MessageType.CALL_MESSAGE; + if (isRequest) { + [, , commandName] = JSON.parse(message) as OutgoingRequest; + beginId = PerformanceStatistics.beginMeasure(commandName); + } + this.wsConnection?.send(message); + isRequest && PerformanceStatistics.endMeasure(commandName!, beginId!); + logger.debug( + `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString( + messageType, + )} payload sent: ${message}`, + ); + this.messageBuffer.delete(message); + } + } } - private getTemplateFromFile(): ChargingStationTemplate | null { - let template: ChargingStationTemplate = null; + private getTemplateFromFile(): ChargingStationTemplate | undefined { + let template: ChargingStationTemplate | undefined; try { - if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) { - template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash); + if (this.sharedLRUCache.hasChargingStationTemplate(this.templateFileHash)) { + template = this.sharedLRUCache.getChargingStationTemplate(this.templateFileHash); } else { const measureId = `${FileType.ChargingStationTemplate} read`; const beginId = PerformanceStatistics.beginMeasure(measureId); - template = JSON.parse( - fs.readFileSync(this.templateFile, 'utf8') - ) as ChargingStationTemplate; + template = JSON.parse(readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate; PerformanceStatistics.endMeasure(measureId, beginId); - template.templateHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) + template.templateHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) .update(JSON.stringify(template)) .digest('hex'); this.sharedLRUCache.setChargingStationTemplate(template); + this.templateFileHash = template.templateHash; } } catch (error) { - FileUtils.handleFileException( - this.logPrefix(), - FileType.ChargingStationTemplate, + handleFileException( this.templateFile, - error as NodeJS.ErrnoException + FileType.ChargingStationTemplate, + error as NodeJS.ErrnoException, + this.logPrefix(), ); } return template; } private getStationInfoFromTemplate(): ChargingStationInfo { - const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile(); - if (Utils.isNullOrUndefined(stationTemplate)) { - const errorMsg = 'Failed to read charging station template file'; - logger.error(`${this.logPrefix()} ${errorMsg}`); - throw new BaseError(errorMsg); - } - if (Utils.isEmptyObject(stationTemplate)) { - const errorMsg = `Empty charging station information from template file ${this.templateFile}`; - logger.error(`${this.logPrefix()} ${errorMsg}`); - throw new BaseError(errorMsg); - } - // Deprecation template keys section - ChargingStationUtils.warnDeprecatedTemplateKey( - stationTemplate, - 'supervisionUrl', - this.templateFile, - this.logPrefix(), - "Use 'supervisionUrls' instead" - ); - ChargingStationUtils.convertDeprecatedTemplateKey( - stationTemplate, - 'supervisionUrl', - 'supervisionUrls' - ); - const stationInfo: ChargingStationInfo = - ChargingStationUtils.stationTemplateToStationInfo(stationTemplate); - stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId( - this.index, - stationTemplate - ); - ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo); - if (!Utils.isEmptyArray(stationTemplate.power)) { + const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile()!; + checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); + const warnTemplateKeysDeprecationOnce = once(warnTemplateKeysDeprecation, this); + warnTemplateKeysDeprecationOnce(stationTemplate, this.logPrefix(), this.templateFile); + if (stationTemplate?.Connectors) { + checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile); + } + const stationInfo: ChargingStationInfo = stationTemplateToStationInfo(stationTemplate); + stationInfo.hashId = getHashId(this.index, stationTemplate); + stationInfo.chargingStationId = getChargingStationId(this.index, stationTemplate); + stationInfo.ocppVersion = stationTemplate?.ocppVersion ?? OCPPVersion.VERSION_16; + createSerialNumber(stationTemplate, stationInfo); + stationInfo.voltageOut = this.getVoltageOut(stationInfo); + if (isNotEmptyArray(stationTemplate?.power)) { stationTemplate.power = stationTemplate.power as number[]; - const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length); + const powerArrayRandomIndex = Math.floor(secureRandom() * stationTemplate.power.length); stationInfo.maximumPower = - stationTemplate.powerUnit === PowerUnits.KILO_WATT + stationTemplate?.powerUnit === PowerUnits.KILO_WATT ? stationTemplate.power[powerArrayRandomIndex] * 1000 : stationTemplate.power[powerArrayRandomIndex]; } else { - stationTemplate.power = stationTemplate.power as number; + stationTemplate.power = stationTemplate?.power as number; stationInfo.maximumPower = - stationTemplate.powerUnit === PowerUnits.KILO_WATT + stationTemplate?.powerUnit === PowerUnits.KILO_WATT ? stationTemplate.power * 1000 : stationTemplate.power; } - stationInfo.resetTime = stationTemplate.resetTime - ? stationTemplate.resetTime * 1000 - : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; - const configuredMaxConnectors = ChargingStationUtils.getConfiguredNumberOfConnectors( - this.index, - stationTemplate - ); - ChargingStationUtils.checkConfiguredMaxConnectors( - configuredMaxConnectors, - this.templateFile, - Utils.logPrefix() - ); - const templateMaxConnectors = - ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate); - ChargingStationUtils.checkTemplateMaxConnectors( - templateMaxConnectors, - this.templateFile, - Utils.logPrefix() - ); + stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo); + stationInfo.firmwareVersionPattern = + stationTemplate?.firmwareVersionPattern ?? Constants.SEMVER_PATTERN; if ( - configuredMaxConnectors > - (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && - !stationTemplate?.randomConnectors + isNotEmptyString(stationInfo.firmwareVersion) && + new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion!) === false ) { logger.warn( - `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ + `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${ this.templateFile - }, forcing random connector configurations affectation` + } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`, ); - stationInfo.randomConnectors = true; } - // Build connectors if needed (FIXME: should be factored out) - this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors); - stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo); - ChargingStationUtils.createStationInfoHash(stationInfo); + stationInfo.firmwareUpgrade = merge( + { + versionUpgrade: { + step: 1, + }, + reset: true, + }, + stationTemplate?.firmwareUpgrade ?? {}, + ); + stationInfo.resetTime = !isNullOrUndefined(stationTemplate?.resetTime) + ? secondsToMilliseconds(stationTemplate.resetTime!) + : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; return stationInfo; } - private getStationInfoFromFile(): ChargingStationInfo | null { - let stationInfo: ChargingStationInfo = null; - this.getStationInfoPersistentConfiguration() && - (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null); - stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo); + private getStationInfoFromFile(): ChargingStationInfo | undefined { + let stationInfo: ChargingStationInfo | undefined; + if (this.stationInfo?.stationInfoPersistentConfiguration === true) { + stationInfo = this.getConfigurationFromFile()?.stationInfo; + if (stationInfo) { + delete stationInfo?.infoHash; + } + } return stationInfo; } private getStationInfo(): ChargingStationInfo { const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate(); - const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile(); - // Priority: charging station info from template > charging station info from configuration file > charging station info attribute + const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile(); + // Priority: + // 1. charging station info from template + // 2. charging station info from configuration file if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { - if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) { - return this.stationInfo; - } - return stationInfoFromFile; + return stationInfoFromFile!; } stationInfoFromFile && - ChargingStationUtils.propagateSerialNumber( - this.getTemplateFromFile(), + propagateSerialNumber( + this.getTemplateFromFile()!, stationInfoFromFile, - stationInfoFromTemplate + stationInfoFromTemplate, ); return stationInfoFromTemplate; } private saveStationInfo(): void { - if (this.getStationInfoPersistentConfiguration()) { + if (this.stationInfo?.stationInfoPersistentConfiguration === true) { this.saveConfiguration(); } } - private getOcppVersion(): OCPPVersion { - return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; - } - - private getOcppPersistentConfiguration(): boolean { - return this.stationInfo?.ocppPersistentConfiguration ?? true; - } - - private getStationInfoPersistentConfiguration(): boolean { - return this.stationInfo?.stationInfoPersistentConfiguration ?? true; - } - - private handleUnsupportedVersion(version: OCPPVersion) { - const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${ - this.templateFile - }`; - logger.error(errMsg); - throw new Error(errMsg); + private handleUnsupportedVersion(version: OCPPVersion | undefined) { + const errorMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); } private initialize(): void { - this.hashId = ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile()); - logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`); - this.configurationFile = path.join( - path.dirname(this.templateFile.replace('station-templates', 'configurations')), - this.hashId + '.json' + const stationTemplate = this.getTemplateFromFile()!; + checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); + this.configurationFile = join( + dirname(this.templateFile.replace('station-templates', 'configurations')), + `${getHashId(this.index, stationTemplate)}.json`, ); - this.stationInfo = this.getStationInfo(); + const stationConfiguration = this.getConfigurationFromFile(); + if ( + stationConfiguration?.stationInfo?.templateHash === stationTemplate?.templateHash && + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + (stationConfiguration?.connectorsStatus || stationConfiguration?.evsesStatus) + ) { + this.initializeConnectorsOrEvsesFromFile(stationConfiguration); + } else { + this.initializeConnectorsOrEvsesFromTemplate(stationTemplate); + } + this.internalStationInfo = this.getStationInfo(); + if ( + this.stationInfo.firmwareStatus === FirmwareStatus.Installing && + isNotEmptyString(this.stationInfo.firmwareVersion) && + 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] = ( + convertToInt(match[patchLevelIndex]) + + this.stationInfo.firmwareUpgrade!.versionUpgrade!.step! + ).toString(); + this.stationInfo.firmwareVersion = match?.join('.'); + } this.saveStationInfo(); - // Avoid duplication of connectors related information in RAM - this.stationInfo?.Connectors && delete this.stationInfo.Connectors; this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); - if (this.getEnableStatistics()) { + if (this.stationInfo?.enableStatistics === true) { this.performanceStatistics = PerformanceStatistics.getInstance( - this.hashId, - this.stationInfo.chargingStationId, - this.configuredSupervisionUrl + this.stationInfo.hashId, + this.stationInfo.chargingStationId!, + this.configuredSupervisionUrl, ); } - this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest( - this.stationInfo - ); + this.bootNotificationRequest = createBootNotificationRequest(this.stationInfo); this.powerDivider = this.getPowerDivider(); // OCPP configuration this.ocppConfiguration = this.getOcppConfiguration(); this.initializeOcppConfiguration(); - switch (this.getOcppVersion()) { + this.initializeOcppServices(); + this.once(ChargingStationEvents.accepted, () => { + this.startMessageSequence().catch((error) => { + logger.error(`${this.logPrefix()} Error while starting the message sequence:`, error); + }); + }); + if (this.stationInfo?.autoRegister === true) { + this.bootNotificationResponse = { + currentTime: new Date(), + interval: millisecondsToSeconds(this.getHeartbeatInterval()), + status: RegistrationStatusEnumType.ACCEPTED, + }; + } + } + + private initializeOcppServices(): void { + const ocppVersion = this.stationInfo?.ocppVersion; + switch (ocppVersion) { case OCPPVersion.VERSION_16: this.ocppIncomingRequestService = OCPP16IncomingRequestService.getInstance(); this.ocppRequestService = OCPP16RequestService.getInstance( - OCPP16ResponseService.getInstance() + OCPP16ResponseService.getInstance(), + ); + break; + case OCPPVersion.VERSION_20: + case OCPPVersion.VERSION_201: + this.ocppIncomingRequestService = + OCPP20IncomingRequestService.getInstance(); + this.ocppRequestService = OCPP20RequestService.getInstance( + OCPP20ResponseService.getInstance(), ); break; default: - this.handleUnsupportedVersion(this.getOcppVersion()); + this.handleUnsupportedVersion(ocppVersion); break; } - if (this.stationInfo?.autoRegister) { - this.bootNotificationResponse = { - currentTime: new Date().toISOString(), - interval: this.getHeartbeatInterval() / 1000, - status: RegistrationStatus.ACCEPTED, - }; - } } private initializeOcppConfiguration(): void { - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.HeartbeatInterval - ) - ) { - ChargingStationConfigurationUtils.addConfigurationKey( - this, - StandardParametersKey.HeartbeatInterval, - '0' - ); + if (!getConfigurationKey(this, StandardParametersKey.HeartbeatInterval)) { + addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0'); } - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.HeartBeatInterval - ) - ) { - ChargingStationConfigurationUtils.addConfigurationKey( - this, - StandardParametersKey.HeartBeatInterval, - '0', - { visible: false } - ); + if (!getConfigurationKey(this, StandardParametersKey.HeartBeatInterval)) { + addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false }); } if ( - this.getSupervisionUrlOcppConfiguration() && - !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) + this.stationInfo?.supervisionUrlOcppConfiguration && + isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) && + !getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!) ) { - ChargingStationConfigurationUtils.addConfigurationKey( + addConfigurationKey( this, - this.getSupervisionUrlOcppKey(), + this.stationInfo.supervisionUrlOcppKey!, this.configuredSupervisionUrl.href, - { reboot: true } + { reboot: true }, ); } else if ( - !this.getSupervisionUrlOcppConfiguration() && - ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) + !this.stationInfo?.supervisionUrlOcppConfiguration && + isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) && + getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!) ) { - ChargingStationConfigurationUtils.deleteConfigurationKey( - this, - this.getSupervisionUrlOcppKey(), - { save: false } - ); + deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!, { save: false }); } if ( - this.stationInfo.amperageLimitationOcppKey && - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - this.stationInfo.amperageLimitationOcppKey - ) + isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && + !getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) ) { - ChargingStationConfigurationUtils.addConfigurationKey( + addConfigurationKey( this, - this.stationInfo.amperageLimitationOcppKey, + this.stationInfo.amperageLimitationOcppKey!, ( - this.stationInfo.maximumAmperage * - ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo) - ).toString() + this.stationInfo.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo) + ).toString(), ); } - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.SupportedFeatureProfiles - ) - ) { - ChargingStationConfigurationUtils.addConfigurationKey( + if (!getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)) { + addConfigurationKey( this, StandardParametersKey.SupportedFeatureProfiles, - `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}` + `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`, ); } - ChargingStationConfigurationUtils.addConfigurationKey( + addConfigurationKey( this, StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), { readonly: true }, - { overwrite: true } + { overwrite: true }, ); - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.MeterValuesSampledData - ) - ) { - ChargingStationConfigurationUtils.addConfigurationKey( + if (!getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData)) { + addConfigurationKey( this, StandardParametersKey.MeterValuesSampledData, - MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER + MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, ); } - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.ConnectorPhaseRotation - ) - ) { - const connectorPhaseRotation = []; - for (const connectorId of this.connectors.keys()) { - // AC/DC - if (connectorId === 0 && this.getNumberOfPhases() === 0) { - connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); - } else if (connectorId > 0 && this.getNumberOfPhases() === 0) { - connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); - // AC - } else if (connectorId > 0 && this.getNumberOfPhases() === 1) { - connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); - } else if (connectorId > 0 && this.getNumberOfPhases() === 3) { - connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); + if (!getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation)) { + const connectorsPhaseRotation: string[] = []; + if (this.hasEvses) { + for (const evseStatus of this.evses.values()) { + for (const connectorId of evseStatus.connectors.keys()) { + connectorsPhaseRotation.push( + getPhaseRotationValue(connectorId, this.getNumberOfPhases())!, + ); + } + } + } else { + for (const connectorId of this.connectors.keys()) { + connectorsPhaseRotation.push( + getPhaseRotationValue(connectorId, this.getNumberOfPhases())!, + ); } } - ChargingStationConfigurationUtils.addConfigurationKey( + addConfigurationKey( this, StandardParametersKey.ConnectorPhaseRotation, - connectorPhaseRotation.toString() + connectorsPhaseRotation.toString(), ); } - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.AuthorizeRemoteTxRequests - ) - ) { - ChargingStationConfigurationUtils.addConfigurationKey( - this, - StandardParametersKey.AuthorizeRemoteTxRequests, - 'true' - ); + if (!getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests)) { + addConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); } if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.LocalAuthListEnabled - ) && - ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.SupportedFeatureProfiles - )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement) - ) { - ChargingStationConfigurationUtils.addConfigurationKey( - this, - StandardParametersKey.LocalAuthListEnabled, - 'false' - ); - } - if ( - !ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.ConnectionTimeOut + !getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled) && + getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)?.value?.includes( + SupportedFeatureProfiles.LocalAuthListManagement, ) ) { - ChargingStationConfigurationUtils.addConfigurationKey( + addConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled, 'false'); + } + if (!getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) { + addConfigurationKey( this, StandardParametersKey.ConnectionTimeOut, - Constants.DEFAULT_CONNECTION_TIMEOUT.toString() + Constants.DEFAULT_CONNECTION_TIMEOUT.toString(), ); } this.saveOcppConfiguration(); } - private initializeConnectors( - stationInfo: ChargingStationInfo, - configuredMaxConnectors: number, - templateMaxConnectors: number - ): void { - if (!stationInfo?.Connectors && this.connectors.size === 0) { - const logMsg = `${this.logPrefix()} No already defined connectors and charging station information from template ${ - this.templateFile - } with no connectors configuration defined`; - logger.error(logMsg); - throw new BaseError(logMsg); - } - if (!stationInfo?.Connectors[0]) { + private initializeConnectorsOrEvsesFromFile(configuration: ChargingStationConfiguration): void { + if (configuration?.connectorsStatus && !configuration?.evsesStatus) { + for (const [connectorId, connectorStatus] of configuration.connectorsStatus.entries()) { + this.connectors.set(connectorId, cloneObject(connectorStatus)); + } + } else if (configuration?.evsesStatus && !configuration?.connectorsStatus) { + for (const [evseId, evseStatusConfiguration] of configuration.evsesStatus.entries()) { + const evseStatus = cloneObject(evseStatusConfiguration); + delete evseStatus.connectorsStatus; + this.evses.set(evseId, { + ...(evseStatus as EvseStatus), + connectors: new Map( + evseStatusConfiguration.connectorsStatus!.map((connectorStatus, connectorId) => [ + connectorId, + connectorStatus, + ]), + ), + }); + } + } else if (configuration?.evsesStatus && configuration?.connectorsStatus) { + const errorMsg = `Connectors and evses defined at the same time in configuration file ${this.configurationFile}`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); + } else { + const errorMsg = `No connectors or evses defined in configuration file ${this.configurationFile}`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); + } + } + + private initializeConnectorsOrEvsesFromTemplate(stationTemplate: ChargingStationTemplate) { + if (stationTemplate?.Connectors && !stationTemplate?.Evses) { + this.initializeConnectorsFromTemplate(stationTemplate); + } else if (stationTemplate?.Evses && !stationTemplate?.Connectors) { + this.initializeEvsesFromTemplate(stationTemplate); + } else if (stationTemplate?.Evses && stationTemplate?.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 initializeConnectorsFromTemplate(stationTemplate: ChargingStationTemplate): void { + if (!stationTemplate?.Connectors && this.connectors.size === 0) { + const errorMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); + } + if (!stationTemplate?.Connectors?.[0]) { 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 connectorsConfigHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) - .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString()) + if (stationTemplate?.Connectors) { + const { configuredMaxConnectors, templateMaxConnectors, templateMaxAvailableConnectors } = + checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile); + const connectorsConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update( + `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`, + ) .digest('hex'); const connectorsConfigChanged = this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; 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 lastConnectorId = Utils.convertToInt(lastConnector); - if ( - lastConnectorId === 0 && - this.getUseConnectorId0(stationInfo) && - stationInfo?.Connectors[lastConnector] - ) { - this.connectors.set( - lastConnectorId, - Utils.cloneObject(stationInfo?.Connectors[lastConnector]) - ); - this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; - if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { - this.getConnectorStatus(lastConnectorId).chargingProfiles = []; + if (templateMaxConnectors > 0) { + for (let connectorId = 0; connectorId <= configuredMaxConnectors; connectorId++) { + if ( + connectorId === 0 && + (!stationTemplate?.Connectors?.[connectorId] || + this.getUseConnectorId0(stationTemplate) === false) + ) { + continue; } - } - } - // 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; - this.connectors.set( - index, - Utils.cloneObject(stationInfo?.Connectors[randConnectorId]) + const templateConnectorId = + connectorId > 0 && stationTemplate?.randomConnectors + ? getRandomInteger(templateMaxAvailableConnectors, 1) + : connectorId; + const connectorStatus = stationTemplate?.Connectors[templateConnectorId]; + checkStationInfoConnectorStatus( + templateConnectorId, + connectorStatus, + this.logPrefix(), + this.templateFile, ); - this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; - if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { - this.getConnectorStatus(index).chargingProfiles = []; - } + this.connectors.set(connectorId, cloneObject(connectorStatus)); } + initializeConnectorsMapStatus(this.connectors, this.logPrefix()); + this.saveConnectorsStatus(); + } else { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no connectors configuration defined, cannot create connectors`, + ); } } } else { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no connectors configuration defined, using already defined connectors` + } with no connectors configuration defined, using already defined connectors`, + ); + } + } + + private initializeEvsesFromTemplate(stationTemplate: ChargingStationTemplate): void { + if (!stationTemplate?.Evses && this.evses.size === 0) { + const errorMsg = `No already defined evses and charging station information from template ${this.templateFile} with no evses configuration defined`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(errorMsg); + } + if (!stationTemplate?.Evses?.[0]) { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no evse id 0 configuration`, ); } - // Initialize transaction attributes on connectors - for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) { - this.initializeConnectorStatus(connectorId); + if (!stationTemplate?.Evses?.[0]?.Connectors?.[0]) { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with evse id 0 with no connector id 0 configuration`, + ); + } + if (Object.keys(stationTemplate?.Evses?.[0]?.Connectors as object).length > 1) { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with evse id 0 with more than one connector configuration, only connector id 0 configuration will be used`, + ); + } + if (stationTemplate?.Evses) { + const evsesConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update(JSON.stringify(stationTemplate?.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 = getMaxNumberOfEvses(stationTemplate?.Evses); + if (templateMaxEvses > 0) { + for (const evseKey in stationTemplate.Evses) { + const evseId = convertToInt(evseKey); + this.evses.set(evseId, { + connectors: buildConnectorsMap( + stationTemplate?.Evses[evseKey]?.Connectors, + this.logPrefix(), + this.templateFile, + ), + availability: AvailabilityType.Operative, + }); + initializeConnectorsMapStatus(this.evses.get(evseId)!.connectors, this.logPrefix()); + } + this.saveEvsesStatus(); + } 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`, + ); } } - private getConfigurationFromFile(): ChargingStationConfiguration | null { - let configuration: ChargingStationConfiguration = null; - if (this.configurationFile && fs.existsSync(this.configurationFile)) { + private getConfigurationFromFile(): ChargingStationConfiguration | undefined { + let configuration: ChargingStationConfiguration | undefined; + if (isNotEmptyString(this.configurationFile) && existsSync(this.configurationFile)) { try { if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { configuration = this.sharedLRUCache.getChargingStationConfiguration( - this.configurationFileHash + this.configurationFileHash, ); } else { const measureId = `${FileType.ChargingStationConfiguration} read`; const beginId = PerformanceStatistics.beginMeasure(measureId); configuration = JSON.parse( - fs.readFileSync(this.configurationFile, 'utf8') + readFileSync(this.configurationFile, 'utf8'), ) as ChargingStationConfiguration; PerformanceStatistics.endMeasure(measureId, beginId); - this.configurationFileHash = configuration.configurationHash; this.sharedLRUCache.setChargingStationConfiguration(configuration); + this.configurationFileHash = configuration.configurationHash!; } } catch (error) { - FileUtils.handleFileException( - this.logPrefix(), - FileType.ChargingStationConfiguration, + handleFileException( this.configurationFile, - error as NodeJS.ErrnoException + FileType.ChargingStationConfiguration, + error as NodeJS.ErrnoException, + this.logPrefix(), ); } } return configuration; } + private saveAutomaticTransactionGeneratorConfiguration(): void { + if (this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration === true) { + this.saveConfiguration(); + } + } + + private saveConnectorsStatus() { + this.saveConfiguration(); + } + + private saveEvsesStatus() { + this.saveConfiguration(); + } + private saveConfiguration(): void { - if (this.configurationFile) { + if (isNotEmptyString(this.configurationFile)) { try { - if (!fs.existsSync(path.dirname(this.configurationFile))) { - fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); + if (!existsSync(dirname(this.configurationFile))) { + mkdirSync(dirname(this.configurationFile), { recursive: true }); + } + let configurationData: ChargingStationConfiguration = this.getConfigurationFromFile() + ? cloneObject(this.getConfigurationFromFile()!) + : {}; + if (this.stationInfo?.stationInfoPersistentConfiguration === true && this.stationInfo) { + configurationData.stationInfo = this.stationInfo; + } else { + delete configurationData.stationInfo; + } + if ( + this.stationInfo?.ocppPersistentConfiguration === true && + this.ocppConfiguration?.configurationKey + ) { + configurationData.configurationKey = this.ocppConfiguration.configurationKey; + } else { + delete configurationData.configurationKey; + } + configurationData = merge( + configurationData, + buildChargingStationAutomaticTransactionGeneratorConfiguration(this), + ); + if ( + !this.stationInfo?.automaticTransactionGeneratorPersistentConfiguration || + !this.getAutomaticTransactionGeneratorConfiguration() + ) { + delete configurationData.automaticTransactionGenerator; + } + if (this.connectors.size > 0) { + configurationData.connectorsStatus = buildConnectorsStatus(this); + } else { + delete configurationData.connectorsStatus; + } + if (this.evses.size > 0) { + configurationData.evsesStatus = buildEvsesStatus(this); + } else { + delete configurationData.evsesStatus; } - const configurationData: ChargingStationConfiguration = - this.getConfigurationFromFile() ?? {}; - this.ocppConfiguration?.configurationKey && - (configurationData.configurationKey = this.ocppConfiguration.configurationKey); - this.stationInfo && (configurationData.stationInfo = this.stationInfo); delete configurationData.configurationHash; - const configurationHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) - .update(JSON.stringify(configurationData)) + const configurationHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update( + JSON.stringify({ + stationInfo: configurationData.stationInfo, + configurationKey: configurationData.configurationKey, + automaticTransactionGenerator: configurationData.automaticTransactionGenerator, + ...(this.connectors.size > 0 && { + connectorsStatus: configurationData.connectorsStatus, + }), + ...(this.evses.size > 0 && { evsesStatus: configurationData.evsesStatus }), + } as ChargingStationConfiguration), + ) .digest('hex'); if (this.configurationFileHash !== configurationHash) { - configurationData.configurationHash = configurationHash; - const measureId = `${FileType.ChargingStationConfiguration} write`; - const beginId = PerformanceStatistics.beginMeasure(measureId); - const fileDescriptor = fs.openSync(this.configurationFile, 'w'); - fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); - fs.closeSync(fileDescriptor); - PerformanceStatistics.endMeasure(measureId, beginId); - this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); - this.configurationFileHash = configurationHash; - this.sharedLRUCache.setChargingStationConfiguration(configurationData); + AsyncLock.runExclusive(AsyncLockType.configuration, () => { + configurationData.configurationHash = configurationHash; + const measureId = `${FileType.ChargingStationConfiguration} write`; + const beginId = PerformanceStatistics.beginMeasure(measureId); + writeFileSync( + this.configurationFile, + JSON.stringify(configurationData, undefined, 2), + 'utf8', + ); + PerformanceStatistics.endMeasure(measureId, beginId); + this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); + this.sharedLRUCache.setChargingStationConfiguration(configurationData); + this.configurationFileHash = configurationHash; + }).catch((error) => { + handleFileException( + this.configurationFile, + FileType.ChargingStationConfiguration, + error as NodeJS.ErrnoException, + this.logPrefix(), + ); + }); } else { logger.debug( `${this.logPrefix()} Not saving unchanged charging station configuration file ${ this.configurationFile - }` + }`, ); } } catch (error) { - FileUtils.handleFileException( - this.logPrefix(), - FileType.ChargingStationConfiguration, + handleFileException( this.configurationFile, - error as NodeJS.ErrnoException + FileType.ChargingStationConfiguration, + error as NodeJS.ErrnoException, + this.logPrefix(), ); } } else { logger.error( - `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file` + `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`, ); } } - private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null { - return this.getTemplateFromFile()?.Configuration ?? null; + private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | undefined { + return this.getTemplateFromFile()?.Configuration; } - private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null { - let configuration: ChargingStationConfiguration = null; - if (this.getOcppPersistentConfiguration()) { - const configurationFromFile = this.getConfigurationFromFile(); - configuration = configurationFromFile?.configurationKey && configurationFromFile; + private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined { + const configurationKey = this.getConfigurationFromFile()?.configurationKey; + if (this.stationInfo?.ocppPersistentConfiguration === true && configurationKey) { + return { configurationKey }; } - configuration && delete configuration.stationInfo; - return configuration; + return undefined; } - private getOcppConfiguration(): ChargingStationOcppConfiguration | null { - let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile(); + private getOcppConfiguration(): ChargingStationOcppConfiguration | undefined { + let ocppConfiguration: ChargingStationOcppConfiguration | undefined = + this.getOcppConfigurationFromFile(); if (!ocppConfiguration) { ocppConfiguration = this.getOcppConfigurationFromTemplate(); } @@ -1258,547 +1737,501 @@ export default class ChargingStation { } private async onOpen(): Promise { - if (this.isWebSocketConnectionOpened()) { + if (this.isWebSocketConnectionOpened() === true) { logger.info( - `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded` + `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`, ); - if (!this.isRegistered()) { + let registrationRetryCount = 0; + if (this.isRegistered() === false) { // Send BootNotification - let registrationRetryCount = 0; do { this.bootNotificationResponse = await this.ocppRequestService.requestHandler< BootNotificationRequest, BootNotificationResponse - >( - this, - 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.isRegistered()) { - this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; - await Utils.sleep( - this.bootNotificationResponse?.interval - ? this.bootNotificationResponse.interval * 1000 - : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL + >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, { + skipBufferingOnError: true, + }); + if (this.isRegistered() === false) { + this.stationInfo?.registrationMaxRetries !== -1 && ++registrationRetryCount; + await sleep( + this?.bootNotificationResponse?.interval + ? secondsToMilliseconds(this.bootNotificationResponse.interval) + : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL, ); } } while ( - !this.isRegistered() && - (registrationRetryCount <= this.getRegistrationMaxRetries() || - this.getRegistrationMaxRetries() === -1) + this.isRegistered() === false && + (registrationRetryCount <= this.stationInfo.registrationMaxRetries! || + this.stationInfo?.registrationMaxRetries === -1) ); } - if (this.isRegistered()) { - if (this.isInAcceptedState()) { - await this.startMessageSequence(); - this.wsConnectionRestarted && this.flushMessageBuffer(); + if (this.isRegistered() === true) { + this.emit(ChargingStationEvents.registered); + if (this.inAcceptedState() === true) { + this.emit(ChargingStationEvents.accepted); } } else { logger.error( - `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})` + `${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${this + .stationInfo?.registrationMaxRetries})`, ); } - this.stopped && (this.stopped = false); - this.autoReconnectRetryCount = 0; this.wsConnectionRestarted = false; + this.autoReconnectRetryCount = 0; + this.emit(ChargingStationEvents.updated); } else { logger.warn( - `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` + `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`, ); } } - private async onClose(code: number, reason: string): Promise { + private async onClose(code: number, reason: Buffer): Promise { switch (code) { // Normal close case WebSocketCloseEventStatusCode.CLOSE_NORMAL: case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: logger.info( - `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString( - code - )}' and reason '${reason}'` + `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString( + code, + )}' and reason '${reason.toString()}'`, ); this.autoReconnectRetryCount = 0; break; // Abnormal close default: logger.error( - `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString( - code - )}' and reason '${reason}'` + `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString( + code, + )}' and reason '${reason.toString()}'`, ); - await this.reconnect(code); + this.started === true && (await this.reconnect()); break; } + this.emit(ChargingStationEvents.updated); + } + + private getCachedRequest(messageType: MessageType, messageId: string): CachedRequest | undefined { + const cachedRequest = this.requests.get(messageId); + if (Array.isArray(cachedRequest) === true) { + return cachedRequest; + } + throw new OCPPError( + ErrorType.PROTOCOL_ERROR, + `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString( + messageType, + )} is not an array`, + undefined, + cachedRequest as JsonType, + ); + } + + private async handleIncomingMessage(request: IncomingRequest): Promise { + const [messageType, messageId, commandName, commandPayload] = request; + if (this.stationInfo?.enableStatistics === true) { + this.performanceStatistics?.addRequestStatistic(commandName, messageType); + } + logger.debug( + `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( + request, + )}`, + ); + // Process the message + await this.ocppIncomingRequestService.incomingRequestHandler( + this, + messageId, + commandName, + commandPayload, + ); + } + + private handleResponseMessage(response: Response): void { + const [messageType, messageId, commandPayload] = response; + if (this.requests.has(messageId) === false) { + // Error + throw new OCPPError( + ErrorType.INTERNAL_ERROR, + `Response for unknown message id ${messageId}`, + undefined, + commandPayload, + ); + } + // Respond + const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest( + messageType, + messageId, + )!; + logger.debug( + `${this.logPrefix()} << Command '${ + requestCommandName ?? Constants.UNKNOWN_COMMAND + }' received response payload: ${JSON.stringify(response)}`, + ); + responseCallback(commandPayload, requestPayload); + } + + private handleErrorMessage(errorResponse: ErrorResponse): void { + const [messageType, messageId, errorType, errorMessage, errorDetails] = errorResponse; + if (this.requests.has(messageId) === false) { + // Error + throw new OCPPError( + ErrorType.INTERNAL_ERROR, + `Error response for unknown message id ${messageId}`, + undefined, + { errorType, errorMessage, errorDetails }, + ); + } + const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!; + logger.debug( + `${this.logPrefix()} << Command '${ + requestCommandName ?? Constants.UNKNOWN_COMMAND + }' received error response payload: ${JSON.stringify(errorResponse)}`, + ); + errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)); } - private async onMessage(data: Data): Promise { - let messageType: number; - let messageId: string; - let commandName: IncomingRequestCommand; - let commandPayload: JsonType; - let errorType: ErrorType; - let errorMessage: string; - let errorDetails: JsonType; - let responseCallback: (payload: JsonType, requestPayload: JsonType) => void; - let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void; - let requestCommandName: RequestCommand | IncomingRequestCommand; - let requestPayload: JsonType; - let cachedRequest: CachedRequest; - let errMsg: string; + private async onMessage(data: RawData): Promise { + let request: IncomingRequest | Response | ErrorResponse | undefined; + let messageType: number | undefined; + let errorMsg: string; try { - const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; - if (Utils.isIterable(request)) { - [messageType, messageId] = request; + // eslint-disable-next-line @typescript-eslint/no-base-to-string + request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; + if (Array.isArray(request) === true) { + [messageType] = request; // Check the type of message switch (messageType) { // Incoming Message case MessageType.CALL_MESSAGE: - [, , commandName, commandPayload] = request as IncomingRequest; - if (this.getEnableStatistics()) { - this.performanceStatistics.addRequestStatistic(commandName, messageType); - } - logger.debug( - `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( - request - )}` - ); - // Process the message - await this.ocppIncomingRequestService.incomingRequestHandler( - this, - messageId, - commandName, - commandPayload - ); + await this.handleIncomingMessage(request as IncomingRequest); break; - // Outcome Message + // Response Message case MessageType.CALL_RESULT_MESSAGE: - [, , commandPayload] = request as Response; - if (!this.requests.has(messageId)) { - // Error - throw new OCPPError( - ErrorType.INTERNAL_ERROR, - `Response for unknown message id ${messageId}`, - null, - commandPayload - ); - } - // Respond - cachedRequest = this.requests.get(messageId); - if (Utils.isIterable(cachedRequest)) { - [responseCallback, , requestCommandName, requestPayload] = cachedRequest; - } else { - throw new OCPPError( - ErrorType.PROTOCOL_ERROR, - `Cached request for message id ${messageId} response is not iterable`, - null, - cachedRequest as unknown as JsonType - ); - } - logger.debug( - `${this.logPrefix()} << Command '${ - requestCommandName ?? 'unknown' - }' received response payload: ${JSON.stringify(request)}` - ); - responseCallback(commandPayload, requestPayload); + this.handleResponseMessage(request as Response); break; // Error Message case MessageType.CALL_ERROR_MESSAGE: - [, , errorType, errorMessage, errorDetails] = request as ErrorResponse; - if (!this.requests.has(messageId)) { - // Error - throw new OCPPError( - ErrorType.INTERNAL_ERROR, - `Error response for unknown message id ${messageId}`, - null, - { errorType, errorMessage, errorDetails } - ); - } - cachedRequest = this.requests.get(messageId); - if (Utils.isIterable(cachedRequest)) { - [, errorCallback, requestCommandName] = cachedRequest; - } else { - throw new OCPPError( - ErrorType.PROTOCOL_ERROR, - `Cached request for message id ${messageId} error response is not iterable`, - null, - cachedRequest as unknown as JsonType - ); - } - logger.debug( - `${this.logPrefix()} << Command '${ - requestCommandName ?? 'unknown' - }' received error payload: ${JSON.stringify(request)}` - ); - errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)); + this.handleErrorMessage(request as ErrorResponse); break; - // Error + // Unknown Message default: // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - errMsg = `${this.logPrefix()} Wrong message type ${messageType}`; - logger.error(errMsg); - throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); + errorMsg = `Wrong message type ${messageType}`; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new OCPPError(ErrorType.PROTOCOL_ERROR, errorMsg); } - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + this.emit(ChargingStationEvents.updated); } else { - throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, { - payload: request, - }); + throw new OCPPError( + ErrorType.PROTOCOL_ERROR, + 'Incoming message is not an array', + undefined, + { + request, + }, + ); } } catch (error) { - // Log - logger.error( - "%s Incoming OCPP '%s' message '%j' matching cached request '%j' processing error:", - this.logPrefix(), - commandName ?? requestCommandName ?? null, - data.toString(), - this.requests.get(messageId), - error - ); - if (!(error instanceof OCPPError)) { + let commandName: IncomingRequestCommand | undefined; + let requestCommandName: RequestCommand | IncomingRequestCommand | undefined; + let errorCallback: ErrorCallback; + const [, messageId] = request!; + switch (messageType) { + case MessageType.CALL_MESSAGE: + [, , commandName] = request as IncomingRequest; + // Send error + await this.ocppRequestService.sendError(this, messageId, error as OCPPError, commandName); + break; + case MessageType.CALL_RESULT_MESSAGE: + case MessageType.CALL_ERROR_MESSAGE: + if (this.requests.has(messageId) === true) { + [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId)!; + // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op) + errorCallback(error as OCPPError, false); + } else { + // Remove the request from the cache in case of error at response handling + this.requests.delete(messageId); + } + break; + } + if (error instanceof OCPPError === false) { logger.warn( - "%s Error thrown at incoming OCPP '%s' message '%j' handling is not an OCPPError:", - this.logPrefix(), - commandName ?? requestCommandName ?? null, - data.toString(), - error + `${this.logPrefix()} Error thrown at incoming OCPP command '${ + commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND + // eslint-disable-next-line @typescript-eslint/no-base-to-string + }' message '${data.toString()}' handling is not an OCPPError:`, + error, ); } - // Send error - messageType === MessageType.CALL_MESSAGE && - (await this.ocppRequestService.sendError( - this, - messageId, - error as OCPPError, - commandName ?? requestCommandName ?? null - )); + logger.error( + `${this.logPrefix()} Incoming OCPP command '${ + commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND + // eslint-disable-next-line @typescript-eslint/no-base-to-string + }' message '${data.toString()}'${ + messageType !== MessageType.CALL_MESSAGE + ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'` + : '' + } processing error:`, + error, + ); } } private onPing(): void { - logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); + logger.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`); } private onPong(): void { - logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); + logger.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`); } private onError(error: WSError): void { this.closeWSConnection(); - logger.error(this.logPrefix() + ' WebSocket error:', error); + logger.error(`${this.logPrefix()} WebSocket error:`, error); } - private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean | undefined { - const localStationInfo = stationInfo ?? this.stationInfo; - return !Utils.isUndefined(localStationInfo.useConnectorId0) - ? localStationInfo.useConnectorId0 - : true; + private getEnergyActiveImportRegister(connectorStatus: ConnectorStatus, rounded = false): number { + if (this.stationInfo?.meteringPerTransaction === true) { + return ( + (rounded === true + ? Math.round(connectorStatus.transactionEnergyActiveImportRegisterValue!) + : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0 + ); + } + return ( + (rounded === true + ? Math.round(connectorStatus.energyActiveImportRegisterValue!) + : connectorStatus?.energyActiveImportRegisterValue) ?? 0 + ); } - private getNumberOfRunningTransactions(): number { - let trxCount = 0; - for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { - trxCount++; + private getUseConnectorId0(stationTemplate?: ChargingStationTemplate): boolean { + return stationTemplate?.useConnectorId0 ?? true; + } + + private async stopRunningTransactions(reason?: StopTransactionReason): Promise { + if (this.hasEvses) { + for (const [evseId, evseStatus] of this.evses) { + if (evseId === 0) { + continue; + } + for (const [connectorId, connectorStatus] of evseStatus.connectors) { + if (connectorStatus.transactionStarted === true) { + await this.stopTransactionOnConnector(connectorId, reason); + } + } + } + } else { + for (const connectorId of this.connectors.keys()) { + if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) { + await this.stopTransactionOnConnector(connectorId, reason); + } } } - return trxCount; } // 0 for disabling - private getConnectionTimeout(): number | undefined { - if ( - ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.ConnectionTimeOut - ) - ) { + private getConnectionTimeout(): number { + if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)) { return ( - parseInt( - ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.ConnectionTimeOut - ).value - ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT + parseInt(getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut)!.value!) ?? + Constants.DEFAULT_CONNECTION_TIMEOUT ); } return Constants.DEFAULT_CONNECTION_TIMEOUT; } - // -1 for unlimited, 0 for disabling - private getAutoReconnectMaxRetries(): number | undefined { - if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { - return this.stationInfo.autoReconnectMaxRetries; - } - if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { - return Configuration.getAutoReconnectMaxRetries(); - } - return -1; - } - - // 0 for disabling - private getRegistrationMaxRetries(): number | undefined { - if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { - return this.stationInfo.registrationMaxRetries; - } - return -1; - } - private getPowerDivider(): number { - let powerDivider = this.getNumberOfConnectors(); - if (this.stationInfo?.powerSharedByConnectors) { + let powerDivider = this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors(); + if (this.stationInfo?.powerSharedByConnectors === true) { powerDivider = this.getNumberOfRunningTransactions(); } return powerDivider; } - private getMaximumPower(stationInfo?: ChargingStationInfo): number { - const localStationInfo = stationInfo ?? this.stationInfo; - return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower; - } - private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined { const maximumPower = this.getMaximumPower(stationInfo); switch (this.getCurrentOutType(stationInfo)) { case CurrentType.AC: return ACElectricUtils.amperagePerPhaseFromPower( this.getNumberOfPhases(stationInfo), - maximumPower / this.getNumberOfConnectors(), - this.getVoltageOut(stationInfo) + maximumPower / (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()), + this.getVoltageOut(stationInfo), ); case CurrentType.DC: return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo)); } } + private getMaximumPower(stationInfo?: ChargingStationInfo): number { + return (stationInfo ?? this.stationInfo).maximumPower!; + } + + private getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType { + return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC; + } + + private getVoltageOut(stationInfo?: ChargingStationInfo): number { + const defaultVoltageOut = getDefaultVoltageOut( + this.getCurrentOutType(stationInfo), + this.logPrefix(), + this.templateFile, + ); + return (stationInfo ?? this.stationInfo).voltageOut ?? defaultVoltageOut; + } + private getAmperageLimitation(): number | undefined { if ( - this.stationInfo.amperageLimitationOcppKey && - ChargingStationConfigurationUtils.getConfigurationKey( - this, - this.stationInfo.amperageLimitationOcppKey - ) + isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && + getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) ) { return ( - Utils.convertToInt( - ChargingStationConfigurationUtils.getConfigurationKey( - this, - this.stationInfo.amperageLimitationOcppKey - ).value - ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo) + convertToInt( + getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)?.value, + ) / getAmperageLimitationUnitDivider(this.stationInfo) ); } } private async startMessageSequence(): Promise { - if (this.stationInfo?.autoRegister) { + if (this.stationInfo?.autoRegister === true) { await this.ocppRequestService.requestHandler< BootNotificationRequest, BootNotificationResponse - >( - this, - 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 } - ); + >(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, { + skipBufferingOnError: true, + }); } // Start WebSocket ping this.startWebSocketPing(); // Start heartbeat this.startHeartbeat(); // Initialize connectors status - for (const connectorId of this.connectors.keys()) { - if (connectorId === 0) { - continue; - } else if ( - !this.stopped && - !this.getConnectorStatus(connectorId)?.status && - this.getConnectorStatus(connectorId)?.bootStatus - ) { - // Send status in template at startup - await this.ocppRequestService.requestHandler< - StatusNotificationRequest, - StatusNotificationResponse - >(this, 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 && - this.getConnectorStatus(connectorId)?.bootStatus - ) { - // Send status in template after reset - await this.ocppRequestService.requestHandler< - StatusNotificationRequest, - StatusNotificationResponse - >(this, 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.requestHandler< - StatusNotificationRequest, - StatusNotificationResponse - >(this, RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: this.getConnectorStatus(connectorId).status, - errorCode: ChargePointErrorCode.NO_ERROR, - }); - } else { - // Send default status - await this.ocppRequestService.requestHandler< - StatusNotificationRequest, - StatusNotificationResponse - >(this, RequestCommand.STATUS_NOTIFICATION, { - connectorId, - status: ChargePointStatus.AVAILABLE, - errorCode: ChargePointErrorCode.NO_ERROR, - }); - this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE; - } - } - // Start the ATG - this.startAutomaticTransactionGenerator(); - } - - private startAutomaticTransactionGenerator() { - if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable) { - if (!this.automaticTransactionGenerator) { - this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance( - this.getAutomaticTransactionGeneratorConfigurationFromTemplate(), - this - ); + if (this.hasEvses) { + for (const [evseId, evseStatus] of this.evses) { + if (evseId > 0) { + for (const [connectorId, connectorStatus] of evseStatus.connectors) { + const connectorBootStatus = getBootConnectorStatus(this, connectorId, connectorStatus); + await OCPPServiceUtils.sendAndSetConnectorStatus( + this, + connectorId, + connectorBootStatus, + evseId, + ); + } + } } - if (!this.automaticTransactionGenerator.started) { - this.automaticTransactionGenerator.start(); + } else { + for (const connectorId of this.connectors.keys()) { + if (connectorId > 0) { + const connectorBootStatus = getBootConnectorStatus( + this, + connectorId, + this.getConnectorStatus(connectorId)!, + ); + await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorBootStatus); + } } } - } + if (this.stationInfo?.firmwareStatus === FirmwareStatus.Installing) { + await this.ocppRequestService.requestHandler< + FirmwareStatusNotificationRequest, + FirmwareStatusNotificationResponse + >(this, RequestCommand.FIRMWARE_STATUS_NOTIFICATION, { + status: FirmwareStatus.Installed, + }); + this.stationInfo.firmwareStatus = FirmwareStatus.Installed; + } - private stopAutomaticTransactionGenerator(): void { - if (this.automaticTransactionGenerator?.started) { - this.automaticTransactionGenerator.stop(); - this.automaticTransactionGenerator = null; + // Start the ATG + if (this.getAutomaticTransactionGeneratorConfiguration().enable === true) { + this.startAutomaticTransactionGenerator(); } + this.wsConnectionRestarted === true && this.flushMessageBuffer(); } private async stopMessageSequence( - reason: StopTransactionReason = StopTransactionReason.NONE + reason?: StopTransactionReason, + stopTransactions = this.stationInfo?.stopTransactionsOnStopped, ): Promise { // Stop WebSocket ping this.stopWebSocketPing(); // Stop heartbeat this.stopHeartbeat(); - // Stop ongoing transactions - if (this.automaticTransactionGenerator?.configuration?.enable) { + // Stop the ATG + if (this.automaticTransactionGenerator?.started === true) { this.stopAutomaticTransactionGenerator(); - } else { - for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { - const transactionId = this.getConnectorStatus(connectorId).transactionId; - if ( - this.getBeginEndMeterValues() && - this.getOcppStrictCompliance() && - !this.getOutOfOrderEndMeterValues() - ) { - // FIXME: Implement OCPP version agnostic helpers - const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( - this, - connectorId, - this.getEnergyActiveImportRegisterByTransactionId(transactionId) - ); - await this.ocppRequestService.requestHandler( + } + // Stop ongoing transactions + stopTransactions && (await this.stopRunningTransactions(reason)); + if (this.hasEvses) { + for (const [evseId, evseStatus] of this.evses) { + if (evseId > 0) { + for (const [connectorId, connectorStatus] of evseStatus.connectors) { + await this.ocppRequestService.requestHandler< + StatusNotificationRequest, + StatusNotificationResponse + >( this, - RequestCommand.METER_VALUES, - { + RequestCommand.STATUS_NOTIFICATION, + OCPPServiceUtils.buildStatusNotificationRequest( + this, connectorId, - transactionId, - meterValue: [transactionEndMeterValue], - } + ConnectorStatusEnum.Unavailable, + evseId, + ), ); + delete connectorStatus?.status; } + } + } + } else { + for (const connectorId of this.connectors.keys()) { + if (connectorId > 0) { await this.ocppRequestService.requestHandler< - StopTransactionRequest, - StopTransactionResponse - >(this, RequestCommand.STOP_TRANSACTION, { - transactionId, - meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId), - idTag: this.getTransactionIdTag(transactionId), - reason, - }); + StatusNotificationRequest, + StatusNotificationResponse + >( + this, + RequestCommand.STATUS_NOTIFICATION, + OCPPServiceUtils.buildStatusNotificationRequest( + this, + connectorId, + ConnectorStatusEnum.Unavailable, + ), + ); + delete this.getConnectorStatus(connectorId)?.status; } } } } private startWebSocketPing(): void { - const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey( + const webSocketPingInterval: number = getConfigurationKey( this, - StandardParametersKey.WebSocketPingInterval + StandardParametersKey.WebSocketPingInterval, ) - ? Utils.convertToInt( - ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.WebSocketPingInterval - ).value - ) + ? convertToInt(getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value) : 0; if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { this.webSocketPingSetInterval = setInterval(() => { - if (this.isWebSocketConnectionOpened()) { - this.wsConnection.ping((): void => { - /* This is intentional */ - }); + if (this.isWebSocketConnectionOpened() === true) { + this.wsConnection?.ping(); } - }, webSocketPingInterval * 1000); + }, secondsToMilliseconds(webSocketPingInterval)); logger.info( - this.logPrefix() + - ' WebSocket ping started every ' + - Utils.formatDurationSeconds(webSocketPingInterval) + `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds( + webSocketPingInterval, + )}`, ); } else if (this.webSocketPingSetInterval) { logger.info( - this.logPrefix() + - ' WebSocket ping every ' + - Utils.formatDurationSeconds(webSocketPingInterval) + - ' already started' + `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds( + webSocketPingInterval, + )}`, ); } 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`, ); } } @@ -1806,255 +2239,108 @@ export default class ChargingStation { private stopWebSocketPing(): void { if (this.webSocketPingSetInterval) { clearInterval(this.webSocketPingSetInterval); + delete this.webSocketPingSetInterval; } } private getConfiguredSupervisionUrl(): URL { - const supervisionUrls = Utils.cloneObject( - this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls() - ); - if (!Utils.isEmptyArray(supervisionUrls)) { - let urlIndex = 0; + let configuredSupervisionUrl: string; + const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls(); + if (isNotEmptyArray(supervisionUrls)) { + let configuredSupervisionUrlIndex: number; switch (Configuration.getSupervisionUrlDistribution()) { - case SupervisionUrlDistribution.ROUND_ROBIN: - urlIndex = (this.index - 1) % supervisionUrls.length; - break; case SupervisionUrlDistribution.RANDOM: - // Get a random url - urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length); - break; - case SupervisionUrlDistribution.SEQUENTIAL: - if (this.index <= supervisionUrls.length) { - urlIndex = this.index - 1; - } else { - logger.warn( - `${this.logPrefix()} No more configured supervision urls available, using the first one` - ); - } + configuredSupervisionUrlIndex = Math.floor( + secureRandom() * (supervisionUrls as string[]).length, + ); break; + case SupervisionUrlDistribution.ROUND_ROBIN: + case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY: default: - logger.error( - `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ - SupervisionUrlDistribution.ROUND_ROBIN - }` - ); - urlIndex = (this.index - 1) % supervisionUrls.length; + Object.values(SupervisionUrlDistribution).includes( + Configuration.getSupervisionUrlDistribution()!, + ) === false && + logger.error( + // eslint-disable-next-line @typescript-eslint/no-base-to-string + `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ + SupervisionUrlDistribution.CHARGING_STATION_AFFINITY + }`, + ); + configuredSupervisionUrlIndex = (this.index - 1) % (supervisionUrls as string[]).length; break; } - return new URL(supervisionUrls[urlIndex]); - } - return new URL(supervisionUrls as string); - } - - private getHeartbeatInterval(): number | undefined { - const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.HeartbeatInterval - ); - if (HeartbeatInterval) { - return Utils.convertToInt(HeartbeatInterval.value) * 1000; + configuredSupervisionUrl = (supervisionUrls as string[])[configuredSupervisionUrlIndex]; + } else { + configuredSupervisionUrl = supervisionUrls as string; } - const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( - this, - StandardParametersKey.HeartBeatInterval - ); - if (HeartBeatInterval) { - return Utils.convertToInt(HeartBeatInterval.value) * 1000; + if (isNotEmptyString(configuredSupervisionUrl)) { + return new URL(configuredSupervisionUrl); } - !this.stationInfo?.autoRegister && - logger.warn( - `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ - Constants.DEFAULT_HEARTBEAT_INTERVAL - }` - ); - return Constants.DEFAULT_HEARTBEAT_INTERVAL; + const errorMsg = 'No supervision url(s) configured'; + logger.error(`${this.logPrefix()} ${errorMsg}`); + throw new BaseError(`${errorMsg}`); } private stopHeartbeat(): void { if (this.heartbeatSetInterval) { clearInterval(this.heartbeatSetInterval); - } - } - - private openWSConnection( - options: WsOptions = this.stationInfo?.wsOptions ?? {}, - params: { closeOpened?: boolean; terminateOpened?: boolean } = { - closeOpened: false, - terminateOpened: false, - } - ): void { - options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; - params.closeOpened = params?.closeOpened ?? false; - params.terminateOpened = params?.terminateOpened ?? false; - if ( - !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && - !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword) - ) { - options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; - } - if (params?.closeOpened) { - this.closeWSConnection(); - } - if (params?.terminateOpened) { - this.terminateWSConnection(); - } - let protocol: string; - switch (this.getOcppVersion()) { - case OCPPVersion.VERSION_16: - protocol = 'ocpp' + OCPPVersion.VERSION_16; - break; - default: - this.handleUnsupportedVersion(this.getOcppVersion()); - break; - } - - logger.info( - this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString() - ); - - this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); - - // Handle WebSocket message - this.wsConnection.on( - 'message', - this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void - ); - // Handle WebSocket error - this.wsConnection.on( - 'error', - this.onError.bind(this) as (this: WebSocket, error: Error) => void - ); - // Handle WebSocket close - this.wsConnection.on( - 'close', - this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void - ); - // Handle WebSocket open - this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void); - // Handle WebSocket ping - this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void); - // Handle WebSocket pong - this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void); - } - - private closeWSConnection(): void { - if (this.isWebSocketConnectionOpened()) { - this.wsConnection.close(); - this.wsConnection = null; + delete this.heartbeatSetInterval; } } private terminateWSConnection(): void { - if (this.isWebSocketConnectionOpened()) { - this.wsConnection.terminate(); + if (this.isWebSocketConnectionOpened() === true) { + this.wsConnection?.terminate(); this.wsConnection = null; } } - private stopMeterValues(connectorId: number) { - if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { - clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval); - } - } - - private getReconnectExponentialDelay(): boolean | undefined { - return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) - ? this.stationInfo.reconnectExponentialDelay - : false; - } - - private async reconnect(code: number): Promise { + private async reconnect(): Promise { // Stop WebSocket ping this.stopWebSocketPing(); // Stop heartbeat this.stopHeartbeat(); // Stop the ATG if needed - if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure) { + if (this.getAutomaticTransactionGeneratorConfiguration().stopOnConnectionFailure === true) { this.stopAutomaticTransactionGenerator(); } if ( - this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || - this.getAutoReconnectMaxRetries() === -1 + this.autoReconnectRetryCount < this.stationInfo.autoReconnectMaxRetries! || + this.stationInfo?.autoReconnectMaxRetries === -1 ) { - this.autoReconnectRetryCount++; - const reconnectDelay = this.getReconnectExponentialDelay() - ? Utils.exponentialDelay(this.autoReconnectRetryCount) - : this.getConnectionTimeout() * 1000; + ++this.autoReconnectRetryCount; + const reconnectDelay = + this.stationInfo?.reconnectExponentialDelay === true + ? exponentialDelay(this.autoReconnectRetryCount) + : secondsToMilliseconds(this.getConnectionTimeout()); const reconnectDelayWithdraw = 1000; const reconnectTimeout = reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0 ? reconnectDelay - reconnectDelayWithdraw : 0; logger.error( - `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo( + `${this.logPrefix()} WebSocket connection retry in ${roundTo( reconnectDelay, - 2 - )}ms, timeout ${reconnectTimeout}ms` + 2, + )}ms, timeout ${reconnectTimeout}ms`, ); - await Utils.sleep(reconnectDelay); + await sleep(reconnectDelay); logger.error( - this.logPrefix() + - ' WebSocket: reconnecting try #' + - this.autoReconnectRetryCount.toString() + `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`, ); this.openWSConnection( - { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout }, - { closeOpened: true } + { + handshakeTimeout: reconnectTimeout, + }, + { closeOpened: true }, ); this.wsConnectionRestarted = true; - } else if (this.getAutoReconnectMaxRetries() !== -1) { + } else if (this.stationInfo?.autoReconnectMaxRetries !== -1) { logger.error( - `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${ + `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${ this.autoReconnectRetryCount - }) or retry disabled (${this.getAutoReconnectMaxRetries()})` + }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`, ); } } - - private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null { - return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null; - } - - 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; - } - - private async handleWorkerBroadcastChannelMessage(message: MessageEvent): Promise { - const [command, payload] = message.data as unknown as [ - ProcedureName, - WorkerBroadcastChannelData - ]; - - if (payload.hashId !== this.hashId) { - return; - } - - switch (command) { - case ProcedureName.START_TRANSACTION: - await this.ocppRequestService.requestHandler< - StartTransactionRequest, - StartTransactionResponse - >(this, RequestCommand.START_TRANSACTION, { - connectorId: payload.connectorId, - idTag: payload.idTag, - }); - break; - case ProcedureName.STOP_TRANSACTION: - await this.ocppRequestService.requestHandler< - StopTransactionRequest, - StopTransactionResponse - >(this, RequestCommand.STOP_TRANSACTION, { - transactionId: payload.transactionId, - meterStop: this.getEnergyActiveImportRegisterByTransactionId(payload.transactionId), - idTag: this.getTransactionIdTag(payload.transactionId), - reason: StopTransactionReason.NONE, - }); - break; - } - } }