X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fcharging-station%2FChargingStation.ts;h=c5b89152199f53373bc6680648545c7205edab83;hb=60c59a02878ddd2ddbac38ec3b3d38f706e538e9;hp=1da63faacc5449659dc647d9d0f909286574c245;hpb=b9863834948c360e10755a5df6504c6b1a613146;p=e-mobility-charging-stations-simulator.git diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 1da63faa..c5b89152 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -1,1432 +1,2018 @@ -import { AuthorizationStatus, StartTransactionRequest, StartTransactionResponse, StopTransactionReason, StopTransactionRequest, StopTransactionResponse } from '../types/ocpp/1.6/Transaction'; -import { BootNotificationResponse, ChangeConfigurationResponse, DefaultResponse, GetConfigurationResponse, HeartbeatResponse, RegistrationStatus, SetChargingProfileResponse, StatusNotificationResponse, UnlockConnectorResponse } from '../types/ocpp/1.6/RequestResponses'; -import { ChargingProfile, ChargingProfilePurposeType } from '../types/ocpp/1.6/ChargingProfile'; -import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration'; -import ChargingStationTemplate, { PowerOutType } from '../types/ChargingStationTemplate'; -import Connectors, { Connector } from '../types/Connectors'; -import { MeterValue, MeterValueLocation, MeterValueMeasurand, MeterValuePhase, MeterValueUnit, MeterValuesRequest, MeterValuesResponse, SampledValue } from '../types/ocpp/1.6/MeterValues'; -import { PerformanceObserver, performance } from 'perf_hooks'; -import Requests, { BootNotificationRequest, ChangeConfigurationRequest, GetConfigurationRequest, HeartbeatRequest, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests'; -import WebSocket, { MessageEvent } from 'ws'; +// Partial Copyright Jerome Benoit. 2021. All Rights Reserved. -import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; -import { ChargePointErrorCode } from '../types/ocpp/1.6/ChargePointErrorCode'; -import { ChargePointStatus } from '../types/ocpp/1.6/ChargePointStatus'; -import ChargingStationInfo from '../types/ChargingStationInfo'; -import Configuration from '../utils/Configuration'; -import Constants from '../utils/Constants'; -import ElectricUtils from '../utils/ElectricUtils'; -import MeasurandValues from '../types/MeasurandValues'; -import OCPPError from './OcppError'; -import Statistics from '../utils/Statistics'; -import Utils from '../utils/Utils'; import crypto from 'crypto'; import fs from 'fs'; +import path from 'path'; +import { URL } from 'url'; +import { parentPort } from 'worker_threads'; + +import WebSocket, { Data, RawData } from 'ws'; + +import BaseError from '../exception/BaseError'; +import OCPPError from '../exception/OCPPError'; +import PerformanceStatistics from '../performance/PerformanceStatistics'; +import type { AutomaticTransactionGeneratorConfiguration } from '../types/AutomaticTransactionGenerator'; +import type ChargingStationConfiguration from '../types/ChargingStationConfiguration'; +import type ChargingStationInfo from '../types/ChargingStationInfo'; +import type ChargingStationOcppConfiguration from '../types/ChargingStationOcppConfiguration'; +import ChargingStationTemplate, { + CurrentType, + PowerUnits, + WsOptions, +} from '../types/ChargingStationTemplate'; +import { SupervisionUrlDistribution } from '../types/ConfigurationData'; +import type { ConnectorStatus } from '../types/ConnectorStatus'; +import { FileType } from '../types/FileType'; +import type { JsonType } from '../types/JsonType'; +import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode'; +import { ChargePointStatus } from '../types/ocpp/ChargePointStatus'; +import { ChargingProfile, ChargingRateUnitType } from '../types/ocpp/ChargingProfile'; +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'; +import { + AvailabilityType, + BootNotificationRequest, + CachedRequest, + HeartbeatRequest, + IncomingRequest, + IncomingRequestCommand, + MeterValuesRequest, + RequestCommand, + StatusNotificationRequest, +} from '../types/ocpp/Requests'; +import { + BootNotificationResponse, + ErrorResponse, + HeartbeatResponse, + MeterValuesResponse, + RegistrationStatus, + Response, + StatusNotificationResponse, +} from '../types/ocpp/Responses'; +import { + StopTransactionReason, + StopTransactionRequest, + StopTransactionResponse, +} from '../types/ocpp/Transaction'; +import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket'; +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 ChargingStationWorkerBroadcastChannel from './ChargingStationWorkerBroadcastChannel'; +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 type OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService'; +import type OCPPRequestService from './ocpp/OCPPRequestService'; +import SharedLRUCache from './SharedLRUCache'; export default class ChargingStation { - private _index: number; - private _stationTemplateFile: string; - private _stationInfo: ChargingStationInfo; - private _bootNotificationRequest: BootNotificationRequest; - private _bootNotificationResponse: BootNotificationResponse; - private _connectors: Connectors; - private _configuration: ChargingStationConfiguration; - private _connectorsConfigurationHash: string; - private _supervisionUrl: string; - private _wsConnectionUrl: string; - private _wsConnection: WebSocket; - private _hasStopped: boolean; - private _hasSocketRestarted: boolean; - private _connectionTimeout: number; - private _autoReconnectRetryCount: number; - private _autoReconnectMaxRetries: number; - private _requests: Requests; - private _messageQueue: string[]; - private _automaticTransactionGeneration: AutomaticTransactionGenerator; - private _authorizedTags: string[]; - private _heartbeatInterval: number; - private _heartbeatSetInterval: NodeJS.Timeout; - private _webSocketPingSetInterval: NodeJS.Timeout; - private _statistics: Statistics; - private _performanceObserver: PerformanceObserver; - - constructor(index: number, stationTemplateFile: string) { - this._index = index; - this._stationTemplateFile = stationTemplateFile; - this._connectors = {} as Connectors; - this._initialize(); - - this._hasStopped = false; - this._hasSocketRestarted = false; - this._autoReconnectRetryCount = 0; - - this._requests = {} as Requests; - this._messageQueue = [] as string[]; - - this._authorizedTags = this._loadAndGetAuthorizedTags(); - } - - _getStationName(stationTemplate: ChargingStationTemplate): string { - return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index.toString()).substr(('000000000' + this._index.toString()).length - 4); - } - - _buildStationInfo(): ChargingStationInfo { - let stationTemplateFromFile: ChargingStationTemplate; - try { - // Load template file - const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r'); - stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate; - fs.closeSync(fileDescriptor); - } catch (error) { - logger.error('Template file ' + this._stationTemplateFile + ' loading error: %j', error); - throw error; - } - const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo; - if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { - stationTemplateFromFile.power = stationTemplateFromFile.power as number[]; - stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)]; - } else { - stationInfo.maxPower = stationTemplateFromFile.power as number; - } - stationInfo.name = this._getStationName(stationTemplateFromFile); - stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; - return stationInfo; - } - - get stationInfo(): ChargingStationInfo { - return this._stationInfo; - } - - _initialize(): void { - this._stationInfo = this._buildStationInfo(); - this._bootNotificationRequest = { - chargePointModel: this._stationInfo.chargePointModel, - chargePointVendor: this._stationInfo.chargePointVendor, - ...!Utils.isUndefined(this._stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this._stationInfo.chargeBoxSerialNumberPrefix }, - ...!Utils.isUndefined(this._stationInfo.firmwareVersion) && { firmwareVersion: this._stationInfo.firmwareVersion }, - }; - this._configuration = this._getTemplateChargingStationConfiguration(); - this._supervisionUrl = this._getSupervisionURL(); - this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name; - this._connectionTimeout = this._getConnectionTimeout() * 1000; // Ms, zero for disabling - this._autoReconnectMaxRetries = this._getAutoReconnectMaxRetries(); // -1 for unlimited - // Build connectors if needed - const maxConnectors = this._getMaxNumberOfConnectors(); - if (maxConnectors <= 0) { - logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`); - } - const templateMaxConnectors = this._getTemplateMaxNumberOfConnectors(); - if (templateMaxConnectors <= 0) { - logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configuration`); - } - if (!this._stationInfo.Connectors[0]) { - logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector Id 0 configuration`); - } - // Sanity check - if (maxConnectors > (this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this._stationInfo.randomConnectors) { - logger.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`); - this._stationInfo.randomConnectors = true; - } - const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this._stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); - // FIXME: Handle shrinking the number of connectors - if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) { - this._connectorsConfigurationHash = connectorsConfigHash; - // Add connector Id 0 - let lastConnector = '0'; - for (lastConnector in this._stationInfo.Connectors) { - if (Utils.convertToInt(lastConnector) === 0 && this._getUseConnectorId0() && this._stationInfo.Connectors[lastConnector]) { - this._connectors[lastConnector] = Utils.cloneObject(this._stationInfo.Connectors[lastConnector]) as Connector; - } - } - // Generate all connectors - if ((this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { - for (let index = 1; index <= maxConnectors; index++) { - const randConnectorID = this._stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index; - this._connectors[index] = Utils.cloneObject(this._stationInfo.Connectors[randConnectorID]) as Connector; - } - } - } - // Avoid duplication of connectors related information - delete this._stationInfo.Connectors; - // Initialize transaction attributes on connectors - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) { - this._initTransactionOnConnector(Utils.convertToInt(connector)); - } - } - // OCPP parameters - this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors().toString(), true); - if (!this._getConfigurationKey('MeterValuesSampledData')) { - this._addConfigurationKey('MeterValuesSampledData', MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER); - } - this._stationInfo.powerDivider = this._getPowerDivider(); - if (this.getEnableStatistics()) { - this._statistics = Statistics.getInstance(); - this._statistics.objName = this._stationInfo.name; - this._performanceObserver = new PerformanceObserver((list) => { - const entry = list.getEntries()[0]; - this._statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION); - this._performanceObserver.disconnect(); - }); + public hashId!: string; + public readonly templateFile: string; + public authorizedTagsCache: AuthorizedTagsCache; + public stationInfo!: ChargingStationInfo; + public stopped: boolean; + public readonly connectors: Map; + public ocppConfiguration!: ChargingStationOcppConfiguration; + public wsConnection!: WebSocket; + public readonly requests: Map; + public performanceStatistics!: PerformanceStatistics; + public heartbeatSetInterval!: NodeJS.Timeout; + public ocppRequestService!: OCPPRequestService; + public bootNotificationResponse!: BootNotificationResponse | null; + public powerDivider!: number; + private readonly index: number; + private configurationFile!: string; + private configurationFileHash!: string; + private bootNotificationRequest!: BootNotificationRequest; + private connectorsConfigurationHash!: string; + private ocppIncomingRequestService!: OCPPIncomingRequestService; + private readonly messageBuffer: Set; + private configuredSupervisionUrl!: URL; + private wsConnectionRestarted: boolean; + private autoReconnectRetryCount: number; + private templateFileWatcher!: fs.FSWatcher; + private readonly sharedLRUCache: SharedLRUCache; + private automaticTransactionGenerator!: AutomaticTransactionGenerator; + private webSocketPingSetInterval!: NodeJS.Timeout; + private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel; + + constructor(index: number, templateFile: string) { + this.index = index; + this.templateFile = templateFile; + this.stopped = false; + this.wsConnectionRestarted = false; + this.autoReconnectRetryCount = 0; + this.sharedLRUCache = SharedLRUCache.getInstance(); + this.authorizedTagsCache = AuthorizedTagsCache.getInstance(); + this.connectors = new Map(); + this.requests = new Map(); + this.messageBuffer = new Set(); + this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this); + + this.initialize(); + } + + private get wsConnectionUrl(): URL { + return new URL( + (this.getSupervisionUrlOcppConfiguration() + ? ChargingStationConfigurationUtils.getConfigurationKey( + this, + this.getSupervisionUrlOcppKey() + ).value + : this.configuredSupervisionUrl.href) + + '/' + + this.stationInfo.chargingStationId + ); + } + + public logPrefix(): string { + return Utils.logPrefix( + ` ${ + this?.stationInfo?.chargingStationId ?? + ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) + } |` + ); + } + + public getBootNotificationRequest(): BootNotificationRequest { + return this.bootNotificationRequest; + } + + 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 { + const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo; + switch (this.getCurrentOutType(stationInfo)) { + case CurrentType.AC: + return !Utils.isUndefined(localStationInfo.numberOfPhases) + ? localStationInfo.numberOfPhases + : 3; + case CurrentType.DC: + return 0; } } - get connectors(): Connectors { - return this._connectors; + public isWebSocketConnectionOpened(): boolean { + return this?.wsConnection?.readyState === WebSocket.OPEN; } - get statistics(): Statistics { - return this._statistics; + public getRegistrationStatus(): RegistrationStatus { + return this?.bootNotificationResponse?.status; } - _logPrefix(): string { - return Utils.logPrefix(` ${this._stationInfo.name}:`); + public isInUnknownState(): boolean { + return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status); } - _getTemplateChargingStationConfiguration(): ChargingStationConfiguration { - return this._stationInfo.Configuration ? this._stationInfo.Configuration : {} as ChargingStationConfiguration; + public isInPendingState(): boolean { + return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING; } - _getAuthorizationFile(): string { - return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile; + public isInAcceptedState(): boolean { + return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; } - _getUseConnectorId0(): boolean { - return !Utils.isUndefined(this._stationInfo.useConnectorId0) ? this._stationInfo.useConnectorId0 : true; + public isInRejectedState(): boolean { + return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED; } - _loadAndGetAuthorizedTags(): string[] { - let authorizedTags: string[] = []; - const authorizationFile = this._getAuthorizationFile(); - if (authorizationFile) { - try { - // Load authorization file - const fileDescriptor = fs.openSync(authorizationFile, 'r'); - authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[]; - fs.closeSync(fileDescriptor); - } catch (error) { - logger.error(this._logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error); - throw error; - } - } else { - logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile); - } - return authorizedTags; + public isRegistered(): boolean { + return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState()); } - getRandomTagId(): string { - const index = Math.floor(Math.random() * this._authorizedTags.length); - return this._authorizedTags[index]; + public isChargingStationAvailable(): boolean { + return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE; } - hasAuthorizedTags(): boolean { - return !Utils.isEmptyArray(this._authorizedTags); + public isConnectorAvailable(id: number): boolean { + return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE; } - getEnableStatistics(): boolean { - return !Utils.isUndefined(this._stationInfo.enableStatistics) ? this._stationInfo.enableStatistics : true; + public getNumberOfConnectors(): number { + return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size; } - _getNumberOfPhases(): number { - switch (this._getPowerOutType()) { - case PowerOutType.AC: - return !Utils.isUndefined(this._stationInfo.numberOfPhases) ? Utils.convertToInt(this._stationInfo.numberOfPhases) : 3; - case PowerOutType.DC: - return 0; - } + public getConnectorStatus(id: number): ConnectorStatus { + return this.connectors.get(id); } - _getNumberOfRunningTransactions(): number { - let trxCount = 0; - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { - trxCount++; - } - } - return trxCount; + public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType { + return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC; } - _getConnectionTimeout(): number { - if (!Utils.isUndefined(this._stationInfo.connectionTimeout)) { - return this._stationInfo.connectionTimeout; - } - if (!Utils.isUndefined(Configuration.getConnectionTimeout())) { - return Configuration.getConnectionTimeout(); - } - return 30; + public getOcppStrictCompliance(): boolean { + return this.stationInfo?.ocppStrictCompliance ?? false; } - _getAutoReconnectMaxRetries(): number { - if (!Utils.isUndefined(this._stationInfo.autoReconnectMaxRetries)) { - return this._stationInfo.autoReconnectMaxRetries; - } - if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { - return Configuration.getAutoReconnectMaxRetries(); - } - return -1; + 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; } - _getPowerDivider(): number { - let powerDivider = this._getNumberOfConnectors(); - if (this._stationInfo.powerSharedByConnectors) { - powerDivider = this._getNumberOfRunningTransactions(); + public getConnectorMaximumAvailablePower(connectorId: number): number { + let connectorAmperageLimitationPowerLimit: number; + if ( + !Utils.isNullOrUndefined(this.getAmperageLimitation()) && + this.getAmperageLimitation() < this.stationInfo.maximumAmperage + ) { + connectorAmperageLimitationPowerLimit = + (this.getCurrentOutType() === CurrentType.AC + ? ACElectricUtils.powerTotal( + this.getNumberOfPhases(), + this.getVoltageOut(), + this.getAmperageLimitation() * this.getNumberOfConnectors() + ) + : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) / + this.powerDivider; } - return powerDivider; - } - - getConnector(id: number): Connector { - return this._connectors[id]; + const connectorMaximumPower = this.getMaximumPower() / this.powerDivider; + const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId); + return Math.min( + isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower, + isNaN(connectorAmperageLimitationPowerLimit) + ? Infinity + : connectorAmperageLimitationPowerLimit, + isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit + ); } - _getTemplateMaxNumberOfConnectors(): number { - return Object.keys(this._stationInfo.Connectors).length; - } - - _getMaxNumberOfConnectors(): number { - let maxConnectors = 0; - if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) { - const numberOfConnectors = this._stationInfo.numberOfConnectors as number[]; - // Distribute evenly the number of connectors - maxConnectors = numberOfConnectors[(this._index - 1) % numberOfConnectors.length]; - } else if (!Utils.isUndefined(this._stationInfo.numberOfConnectors)) { - maxConnectors = this._stationInfo.numberOfConnectors as number; - } else { - maxConnectors = this._stationInfo.Connectors[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors(); - } - return maxConnectors; - } - - _getNumberOfConnectors(): number { - return this._connectors[0] ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length; - } - - _getVoltageOut(): number { - const errMsg = `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`; - let defaultVoltageOut: number; - switch (this._getPowerOutType()) { - case PowerOutType.AC: - defaultVoltageOut = 230; - break; - case PowerOutType.DC: - defaultVoltageOut = 400; - break; - default: - logger.error(errMsg); - throw Error(errMsg); - } - return !Utils.isUndefined(this._stationInfo.voltageOut) ? Utils.convertToInt(this._stationInfo.voltageOut) : defaultVoltageOut; - } - - _getTransactionIdTag(transactionId: number): string { - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { - return this.getConnector(Utils.convertToInt(connector)).idTag; + 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; } } } - _getTransactionMeterStop(transactionId: number): number { - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { - return this.getConnector(Utils.convertToInt(connector)).lastEnergyActiveImportRegisterValue; - } - } + public getOutOfOrderEndMeterValues(): boolean { + return this.stationInfo?.outOfOrderEndMeterValues ?? false; } - _getPowerOutType(): PowerOutType { - return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : PowerOutType.AC; + public getBeginEndMeterValues(): boolean { + return this.stationInfo?.beginEndMeterValues ?? false; } - _getSupervisionURL(): string { - const supervisionUrls = Utils.cloneObject(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()) as string | string[]; - let indexUrl = 0; - if (!Utils.isEmptyArray(supervisionUrls)) { - if (Configuration.getDistributeStationsToTenantsEqually()) { - indexUrl = this._index % supervisionUrls.length; - } else { - // Get a random url - indexUrl = Math.floor(Math.random() * supervisionUrls.length); - } - return supervisionUrls[indexUrl]; - } - return supervisionUrls as string; + public getMeteringPerTransaction(): boolean { + return this.stationInfo?.meteringPerTransaction ?? true; } - _getReconnectExponentialDelay(): boolean { - return !Utils.isUndefined(this._stationInfo.reconnectExponentialDelay) ? this._stationInfo.reconnectExponentialDelay : false; + public getTransactionDataMeterValues(): boolean { + return this.stationInfo?.transactionDataMeterValues ?? false; } - _getAuthorizeRemoteTxRequests(): boolean { - const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests'); - return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; + public getMainVoltageMeterValues(): boolean { + return this.stationInfo?.mainVoltageMeterValues ?? true; } - _getLocalAuthListEnabled(): boolean { - const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled'); - return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; + public getPhaseLineToLineVoltageMeterValues(): boolean { + return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false; } - async _startMessageSequence(): Promise { - // Start WebSocket ping - this._startWebSocketPing(); - // Start heartbeat - this._startHeartbeat(); - // Initialize connectors status - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) === 0) { - continue; - } else if (!this._hasStopped && !this.getConnector(Utils.convertToInt(connector)).status && this.getConnector(Utils.convertToInt(connector)).bootStatus) { - // Send status in template at startup - await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); - } else if (this._hasStopped && this.getConnector(Utils.convertToInt(connector)).bootStatus) { - // Send status in template after reset - await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); - } else if (!this._hasStopped && this.getConnector(Utils.convertToInt(connector)).status) { - // Send previous status at template reload - await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status); - } else { - // Send default status - await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE); - } - } - // Start the ATG - if (this._stationInfo.AutomaticTransactionGenerator.enable) { - if (!this._automaticTransactionGeneration) { - this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this); - } - if (this._automaticTransactionGeneration.timeToStop) { - this._automaticTransactionGeneration.start(); - } - } - if (this.getEnableStatistics()) { - this._statistics.start(); - } + public getCustomValueLimitationMeterValues(): boolean { + return this.stationInfo?.customValueLimitationMeterValues ?? true; } - async _stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise { - // Stop WebSocket ping - this._stopWebSocketPing(); - // Stop heartbeat - this._stopHeartbeat(); - // Stop the ATG - if (this._stationInfo.AutomaticTransactionGenerator.enable && - this._automaticTransactionGeneration && - !this._automaticTransactionGeneration.timeToStop) { - await this._automaticTransactionGeneration.stop(reason); - } else { - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { - await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason); - } + public getConnectorIdByTransactionId(transactionId: number): number | undefined { + for (const connectorId of this.connectors.keys()) { + if ( + connectorId > 0 && + this.getConnectorStatus(connectorId)?.transactionId === transactionId + ) { + return connectorId; } } } - _startWebSocketPing(): void { - const webSocketPingInterval: number = this._getConfigurationKey('WebSocketPingInterval') ? Utils.convertToInt(this._getConfigurationKey('WebSocketPingInterval').value) : 0; - if (webSocketPingInterval > 0 && !this._webSocketPingSetInterval) { - this._webSocketPingSetInterval = setInterval(() => { - if (this._wsConnection?.readyState === WebSocket.OPEN) { - this._wsConnection.ping((): void => { }); - } - }, webSocketPingInterval * 1000); - logger.info(this._logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval)); - } else if (this._webSocketPingSetInterval) { - logger.info(this._logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started'); - } else { - logger.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`); + public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number { + const transactionConnectorStatus = this.getConnectorStatus( + this.getConnectorIdByTransactionId(transactionId) + ); + if (this.getMeteringPerTransaction()) { + return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue ?? 0; } + return transactionConnectorStatus?.energyActiveImportRegisterValue ?? 0; } - _stopWebSocketPing(): void { - if (this._webSocketPingSetInterval) { - clearInterval(this._webSocketPingSetInterval); - this._webSocketPingSetInterval = null; + public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number { + const connectorStatus = this.getConnectorStatus(connectorId); + if (this.getMeteringPerTransaction()) { + return connectorStatus?.transactionEnergyActiveImportRegisterValue ?? 0; } + return connectorStatus?.energyActiveImportRegisterValue ?? 0; } - _restartWebSocketPing(): void { - // Stop WebSocket ping - this._stopWebSocketPing(); - // Start WebSocket ping - this._startWebSocketPing(); + public getAuthorizeRemoteTxRequests(): boolean { + const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.AuthorizeRemoteTxRequests + ); + return authorizeRemoteTxRequests + ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) + : false; } - _startHeartbeat(): void { - if (this._heartbeatInterval && this._heartbeatInterval > 0 && !this._heartbeatSetInterval) { - this._heartbeatSetInterval = setInterval(async () => { - await this.sendHeartbeat(); - }, this._heartbeatInterval); - logger.info(this._logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this._heartbeatInterval)); - } else if (this._heartbeatSetInterval) { - logger.info(this._logPrefix() + ' Heartbeat every ' + Utils.milliSecondsToHHMMSS(this._heartbeatInterval) + ' already started'); - } else { - logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval ? Utils.milliSecondsToHHMMSS(this._heartbeatInterval) : this._heartbeatInterval}, not starting the heartbeat`); - } + public getLocalAuthListEnabled(): boolean { + const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.LocalAuthListEnabled + ); + return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; } - _stopHeartbeat(): void { - if (this._heartbeatSetInterval) { - clearInterval(this._heartbeatSetInterval); - this._heartbeatSetInterval = null; + public startHeartbeat(): void { + if ( + this.getHeartbeatInterval() && + this.getHeartbeatInterval() > 0 && + !this.heartbeatSetInterval + ) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + this.heartbeatSetInterval = setInterval(async (): Promise => { + await this.ocppRequestService.requestHandler( + this, + RequestCommand.HEARTBEAT + ); + }, this.getHeartbeatInterval()); + logger.info( + this.logPrefix() + + ' Heartbeat started every ' + + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) + ); + } else if (this.heartbeatSetInterval) { + logger.info( + this.logPrefix() + + ' Heartbeat already started every ' + + Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) + ); + } else { + logger.error( + `${this.logPrefix()} Heartbeat interval set to ${ + this.getHeartbeatInterval() + ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) + : this.getHeartbeatInterval() + }, not starting the heartbeat` + ); } } - _restartHeartbeat(): void { + public restartHeartbeat(): void { // Stop heartbeat - this._stopHeartbeat(); + this.stopHeartbeat(); // Start heartbeat - this._startHeartbeat(); - } - - _startAuthorizationFileMonitoring(): void { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - fs.watchFile(this._getAuthorizationFile(), (current, previous) => { - try { - logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload'); - // Initialize _authorizedTags - this._authorizedTags = this._loadAndGetAuthorizedTags(); - } catch (error) { - logger.error(this._logPrefix() + ' Authorization file monitoring error: %j', error); - } - }); + this.startHeartbeat(); } - _startStationTemplateFileMonitoring(): void { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - fs.watchFile(this._stationTemplateFile, (current, previous) => { - try { - logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload'); - // Initialize - this._initialize(); - if (!this._stationInfo.AutomaticTransactionGenerator.enable && - this._automaticTransactionGeneration) { - this._automaticTransactionGeneration.stop().catch(() => { }); - } - // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed - } catch (error) { - logger.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error); - } - }); + public restartWebSocketPing(): void { + // Stop WebSocket ping + this.stopWebSocketPing(); + // Start WebSocket ping + this.startWebSocketPing(); } - _startMeterValues(connectorId: number, interval: number): void { - if (!this.getConnector(connectorId).transactionStarted) { - logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`); + public startMeterValues(connectorId: number, interval: number): void { + if (connectorId === 0) { + logger.error( + `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}` + ); + return; + } + if (!this.getConnectorStatus(connectorId)) { + logger.error( + `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}` + ); return; - } else if (this.getConnector(connectorId).transactionStarted && !this.getConnector(connectorId).transactionId) { - logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`); + } + if (!this.getConnectorStatus(connectorId)?.transactionStarted) { + logger.error( + `${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 + ) { + logger.error( + `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id` + ); return; } if (interval > 0) { - this.getConnector(connectorId).transactionSetInterval = setInterval(async () => { - if (this.getEnableStatistics()) { - const sendMeterValues = performance.timerify(this.sendMeterValues); - this._performanceObserver.observe({ - entryTypes: ['function'], - }); - await sendMeterValues(connectorId, interval, this); - } else { - await this.sendMeterValues(connectorId, interval, this); - } - }, interval); + // 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, + RequestCommand.METER_VALUES, + { + connectorId, + transactionId: this.getConnectorStatus(connectorId).transactionId, + meterValue: [meterValue], + } + ); + }, + interval + ); } else { - logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`); - } - } - - _openWSConnection(options?: WebSocket.ClientOptions): void { - if (Utils.isUndefined(options)) { - options = {} as WebSocket.ClientOptions; + logger.error( + `${this.logPrefix()} Charging station ${ + StandardParametersKey.MeterValueSampleInterval + } configuration set to ${ + interval ? Utils.formatDurationMilliSeconds(interval) : interval + }, not sending MeterValues` + ); } - if (Utils.isUndefined(options.handshakeTimeout)) { - options.handshakeTimeout = this._connectionTimeout; - } - this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16, options); - logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl); } - start(): void { - this._openWSConnection(); - // Monitor authorization file - this._startAuthorizationFileMonitoring(); - // Monitor station template file - this._startStationTemplateFileMonitoring(); - // Handle Socket incoming messages - this._wsConnection.on('message', this.onMessage.bind(this)); - // Handle Socket error - this._wsConnection.on('error', this.onError.bind(this)); - // Handle Socket close - this._wsConnection.on('close', this.onClose.bind(this)); - // Handle Socket opening connection - this._wsConnection.on('open', this.onOpen.bind(this)); - // Handle Socket ping - this._wsConnection.on('ping', this.onPing.bind(this)); - // Handle Socket pong - this._wsConnection.on('pong', this.onPong.bind(this)); + public start(): void { + if (this.getEnableStatistics()) { + this.performanceStatistics.start(); + } + 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 + ); + } + } + } + ); + parentPort.postMessage(MessageChannelUtils.buildStartedMessage(this)); } - async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise { + public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise { // Stop message sequence - await this._stopMessageSequence(reason); - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0) { - await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE); + 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; } } - if (this._wsConnection?.readyState === WebSocket.OPEN) { - this._wsConnection.close(); - } - this._bootNotificationResponse = null; - this._hasStopped = true; - } - - async _reconnect(error): Promise { - logger.error(this._logPrefix() + ' Socket: abnormally closed: %j', error); - // Stop heartbeat - this._stopHeartbeat(); - // Stop the ATG if needed - if (this._stationInfo.AutomaticTransactionGenerator.enable && - this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && - this._automaticTransactionGeneration && - !this._automaticTransactionGeneration.timeToStop) { - this._automaticTransactionGeneration.stop().catch(() => { }); - } - if (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1) { - this._autoReconnectRetryCount++; - const reconnectDelay = (this._getReconnectExponentialDelay() ? Utils.exponentialDelay(this._autoReconnectRetryCount) : this._connectionTimeout); - logger.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`); - await Utils.sleep(reconnectDelay); - logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount.toString()); - this._openWSConnection({ handshakeTimeout: reconnectDelay - 100 }); - } else if (this._autoReconnectMaxRetries !== -1) { - logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectMaxRetries})`); - } - } + this.closeWSConnection(); + if (this.getEnableStatistics()) { + this.performanceStatistics.stop(); + } + this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); + this.templateFileWatcher.close(); + this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash); + this.bootNotificationResponse = null; + this.stopped = true; + parentPort.postMessage(MessageChannelUtils.buildStoppedMessage(this)); + } + + public async reset(reason?: StopTransactionReason): Promise { + await this.stop(reason); + await Utils.sleep(this.stationInfo.resetTime); + this.initialize(); + this.start(); + } + + public saveOcppConfiguration(): void { + if (this.getOcppPersistentConfiguration()) { + 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) + ); + } + if (!Utils.isEmptyArray(chargingProfiles)) { + const result = ChargingStationUtils.getLimitFromChargingProfiles( + chargingProfiles, + Utils.logPrefix() + ); + 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); + } - async onOpen(): Promise { - logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`); - if (!this._hasSocketRestarted || this._hasStopped) { - // Send BootNotification - this._bootNotificationResponse = await this.sendBootNotification(); - } - if (this._bootNotificationResponse.status === RegistrationStatus.ACCEPTED) { - await this._startMessageSequence(); - } else { - do { - await Utils.sleep(this._bootNotificationResponse.interval * 1000); - // Resend BootNotification - this._bootNotificationResponse = await this.sendBootNotification(); - } while (this._bootNotificationResponse.status !== RegistrationStatus.ACCEPTED); - } - if (this._hasSocketRestarted && this._bootNotificationResponse.status === RegistrationStatus.ACCEPTED) { - if (!Utils.isEmptyArray(this._messageQueue)) { - this._messageQueue.forEach((message, index) => { - if (this._wsConnection?.readyState === WebSocket.OPEN) { - this._messageQueue.splice(index, 1); - this._wsConnection.send(message); - } - }); + 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; + } } } - this._autoReconnectRetryCount = 0; - this._hasSocketRestarted = false; - } - - async onError(errorEvent): Promise { - switch (errorEvent.code) { - case 'ECONNREFUSED': - this._hasSocketRestarted = true; - await this._reconnect(errorEvent); + return limit; + } + + 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` + ); + this.getConnectorStatus(connectorId).chargingProfiles = []; + } + if (Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles) === false) { + 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` + ); + 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; + } + } + ); + } + !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 hasFeatureProfile(featureProfile: SupportedFeatureProfiles) { + return ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.SupportedFeatureProfiles + )?.value.includes(featureProfile); + } + + public bufferMessage(message: string): void { + this.messageBuffer.add(message); + } + + public 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: - logger.error(this._logPrefix() + ' Socket error: %j', errorEvent); + this.handleUnsupportedVersion(this.getOcppVersion()); break; } - } - async onClose(closeEvent): Promise { - switch (closeEvent) { - case 1000: // Normal close - case 1005: - logger.info(this._logPrefix() + ' Socket normally closed: %j', closeEvent); - this._autoReconnectRetryCount = 0; - break; - default: // Abnormal close - this._hasSocketRestarted = true; - await this._reconnect(closeEvent); - 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); + } + + public closeWSConnection(): void { + if (this.isWebSocketConnectionOpened()) { + this.wsConnection.close(); + this.wsConnection = null; + } + } + + 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); + }); } } - onPing(): void { - logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server'); + private getSupervisionUrlOcppConfiguration(): boolean { + return this.stationInfo.supervisionUrlOcppConfiguration ?? false; } - onPong(): void { - logger.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server'); + private getSupervisionUrlOcppKey(): string { + return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; } - async onMessage(messageEvent: MessageEvent): Promise { - let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', '']; + private getTemplateFromFile(): ChargingStationTemplate | null { + let template: ChargingStationTemplate = null; try { - // Parse the message - [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()); - - // Check the Type of message - switch (messageType) { - // Incoming Message - case Constants.OCPP_JSON_CALL_MESSAGE: - if (this.getEnableStatistics()) { - this._statistics.addMessage(commandName, messageType); - } - // Process the call - await this.handleRequest(messageId, commandName, commandPayload); - break; - // Outcome Message - case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: - // Respond - // eslint-disable-next-line no-case-declarations - let responseCallback; let requestPayload; - if (Utils.isIterable(this._requests[messageId])) { - [responseCallback, , requestPayload] = this._requests[messageId]; - } else { - throw new Error(`Response request for message id ${messageId} is not iterable`); - } - if (!responseCallback) { - // Error - throw new Error(`Response request for unknown message id ${messageId}`); - } - delete this._requests[messageId]; - responseCallback(commandName, requestPayload); - break; - // Error Message - case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: - if (!this._requests[messageId]) { - // Error - throw new Error(`Error request for unknown message id ${messageId}`); - } - // eslint-disable-next-line no-case-declarations - let rejectCallback; - if (Utils.isIterable(this._requests[messageId])) { - [, rejectCallback] = this._requests[messageId]; - } else { - throw new Error(`Error request for message id ${messageId} is not iterable`); - } - delete this._requests[messageId]; - rejectCallback(new OCPPError(commandName, commandPayload, errorDetails)); - break; - // Error - default: - // eslint-disable-next-line no-case-declarations - const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`; - logger.error(errMsg); - throw new Error(errMsg); + if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) { + template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash); + } else { + const measureId = `${FileType.ChargingStationTemplate} read`; + const beginId = PerformanceStatistics.beginMeasure(measureId); + template = JSON.parse( + fs.readFileSync(this.templateFile, 'utf8') + ) as ChargingStationTemplate; + PerformanceStatistics.endMeasure(measureId, beginId); + template.templateHash = crypto + .createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update(JSON.stringify(template)) + .digest('hex'); + this.sharedLRUCache.setChargingStationTemplate(template); } } catch (error) { - // Log - logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent, error, this._requests[messageId]); - // Send error - messageType !== Constants.OCPP_JSON_CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName); - } + FileUtils.handleFileException( + this.logPrefix(), + FileType.ChargingStationTemplate, + this.templateFile, + error as NodeJS.ErrnoException + ); + } + 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)) { + stationTemplate.power = stationTemplate.power as number[]; + const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length); + stationInfo.maximumPower = + stationTemplate.powerUnit === PowerUnits.KILO_WATT + ? stationTemplate.power[powerArrayRandomIndex] * 1000 + : stationTemplate.power[powerArrayRandomIndex]; + } else { + stationTemplate.power = stationTemplate.power as number; + stationInfo.maximumPower = + 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() + ); + if ( + configuredMaxConnectors > + (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && + !stationTemplate?.randomConnectors + ) { + logger.warn( + `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ + this.templateFile + }, forcing random connector configurations affectation` + ); + stationInfo.randomConnectors = true; + } + // Build connectors if needed (FIXME: should be factored out) + this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors); + stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo); + ChargingStationUtils.createStationInfoHash(stationInfo); + return stationInfo; } - async sendHeartbeat(): Promise { - try { - const payload: HeartbeatRequest = {}; - await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat'); - } catch (error) { - logger.error(this._logPrefix() + ' Send Heartbeat error: %j', error); - throw error; - } + private getStationInfoFromFile(): ChargingStationInfo | null { + let stationInfo: ChargingStationInfo = null; + this.getStationInfoPersistentConfiguration() && + (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null); + stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo); + return stationInfo; } - async sendBootNotification(): Promise { - try { - return await this.sendMessage(Utils.generateUUID(), this._bootNotificationRequest, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification') as BootNotificationResponse; - } catch (error) { - logger.error(this._logPrefix() + ' Send BootNotification error: %j', error); - throw error; + 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 + if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { + if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) { + return this.stationInfo; + } + return stationInfoFromFile; } + stationInfoFromFile && + ChargingStationUtils.propagateSerialNumber( + this.getTemplateFromFile(), + stationInfoFromFile, + stationInfoFromTemplate + ); + return stationInfoFromTemplate; } - async sendStatusNotification(connectorId: number, status: ChargePointStatus, errorCode: ChargePointErrorCode = ChargePointErrorCode.NO_ERROR): Promise { - this.getConnector(connectorId).status = status; - try { - const payload: StatusNotificationRequest = { - connectorId, - errorCode, - status, - }; - await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification'); - } catch (error) { - logger.error(this._logPrefix() + ' Send StatusNotification error: %j', error); - throw error; + private saveStationInfo(): void { + if (this.getStationInfoPersistentConfiguration()) { + this.saveConfiguration(); } } - async sendStartTransaction(connectorId: number, idTag?: string): Promise { - try { - const payload: StartTransactionRequest = { - connectorId, - ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.TRANSACTION_DEFAULT_IDTAG }, - meterStart: 0, - timestamp: new Date().toISOString(), - }; - return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction') as StartTransactionResponse; - } catch (error) { - logger.error(this._logPrefix() + ' Send StartTransaction error: %j', error); - throw error; - } + private getOcppVersion(): OCPPVersion { + return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; } - async sendStopTransaction(transactionId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise { - const idTag = this._getTransactionIdTag(transactionId); - try { - const payload: StopTransactionRequest = { - transactionId, - ...!Utils.isUndefined(idTag) && { idTag: idTag }, - meterStop: this._getTransactionMeterStop(transactionId), - timestamp: new Date().toISOString(), - ...reason && { reason }, + 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 BaseError(errMsg); + } + + 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' + ); + this.stationInfo = this.getStationInfo(); + this.saveStationInfo(); + // Avoid duplication of connectors related information in RAM + this.stationInfo?.Connectors && delete this.stationInfo.Connectors; + this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl(); + if (this.getEnableStatistics()) { + this.performanceStatistics = PerformanceStatistics.getInstance( + this.hashId, + this.stationInfo.chargingStationId, + this.configuredSupervisionUrl + ); + } + this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest( + this.stationInfo + ); + this.powerDivider = this.getPowerDivider(); + // OCPP configuration + this.ocppConfiguration = this.getOcppConfiguration(); + this.initializeOcppConfiguration(); + switch (this.getOcppVersion()) { + case OCPPVersion.VERSION_16: + this.ocppIncomingRequestService = + OCPP16IncomingRequestService.getInstance(); + this.ocppRequestService = OCPP16RequestService.getInstance( + OCPP16ResponseService.getInstance() + ); + break; + default: + this.handleUnsupportedVersion(this.getOcppVersion()); + break; + } + if (this.stationInfo?.autoRegister) { + this.bootNotificationResponse = { + currentTime: new Date().toISOString(), + interval: this.getHeartbeatInterval() / 1000, + status: RegistrationStatus.ACCEPTED, }; - return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction') as StartTransactionResponse; - } catch (error) { - logger.error(this._logPrefix() + ' Send StopTransaction error: %j', error); - throw error; } } - // eslint-disable-next-line consistent-this - async sendMeterValues(connectorId: number, interval: number, self: ChargingStation, debug = false): Promise { - try { - const meterValue: MeterValue = { - timestamp: new Date().toISOString(), - sampledValue: [], - }; - const meterValuesTemplate: SampledValue[] = self.getConnector(connectorId).MeterValues; - for (let index = 0; index < meterValuesTemplate.length; index++) { - const connector = self.getConnector(connectorId); - // SoC measurand - if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.STATE_OF_CHARGE && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.STATE_OF_CHARGE)) { - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.PERCENT }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - measurand: meterValuesTemplate[index].measurand, - ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: MeterValueLocation.EV }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100).toString() }, - }); - const sampledValuesIndex = meterValue.sampledValue.length - 1; - if (Utils.convertToInt(meterValue.sampledValue[sampledValuesIndex].value) > 100 || debug) { - logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/100`); - } - // Voltage measurand - } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.VOLTAGE && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.VOLTAGE)) { - const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1); - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - measurand: meterValuesTemplate[index].measurand, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() }, - }); - for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { - let phaseValue: string; - if (self._getVoltageOut() >= 0 && self._getVoltageOut() <= 250) { - phaseValue = `L${phase}-N`; - } else if (self._getVoltageOut() > 250) { - phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`; + private initializeOcppConfiguration(): void { + if ( + !ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.HeartbeatInterval + ) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.HeartbeatInterval, + '0' + ); + } + if ( + !ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.HeartBeatInterval + ) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.HeartBeatInterval, + '0', + { visible: false } + ); + } + if ( + this.getSupervisionUrlOcppConfiguration() && + !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + this.getSupervisionUrlOcppKey(), + this.configuredSupervisionUrl.href, + { reboot: true } + ); + } else if ( + !this.getSupervisionUrlOcppConfiguration() && + ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey()) + ) { + ChargingStationConfigurationUtils.deleteConfigurationKey( + this, + this.getSupervisionUrlOcppKey(), + { save: false } + ); + } + if ( + this.stationInfo.amperageLimitationOcppKey && + !ChargingStationConfigurationUtils.getConfigurationKey( + this, + this.stationInfo.amperageLimitationOcppKey + ) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + this.stationInfo.amperageLimitationOcppKey, + ( + this.stationInfo.maximumAmperage * + ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo) + ).toString() + ); + } + if ( + !ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.SupportedFeatureProfiles + ) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.SupportedFeatureProfiles, + `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}` + ); + } + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.NumberOfConnectors, + this.getNumberOfConnectors().toString(), + { readonly: true }, + { overwrite: true } + ); + if ( + !ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.MeterValuesSampledData + ) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.MeterValuesSampledData, + 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}`); + } + } + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.ConnectorPhaseRotation, + connectorPhaseRotation.toString() + ); + } + if ( + !ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.AuthorizeRemoteTxRequests + ) + ) { + ChargingStationConfigurationUtils.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 + ) + ) { + ChargingStationConfigurationUtils.addConfigurationKey( + this, + StandardParametersKey.ConnectionTimeOut, + 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]) { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no connector Id 0 configuration` + ); + } + if (stationInfo?.Connectors) { + const connectorsConfigHash = crypto + .createHash(Constants.DEFAULT_HASH_ALGORITHM) + .update(JSON.stringify(stationInfo?.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 = []; } - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - measurand: meterValuesTemplate[index].measurand, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() }, - phase: phaseValue as MeterValuePhase, - }); - } - // Power.Active.Import measurand - } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.POWER_ACTIVE_IMPORT && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.POWER_ACTIVE_IMPORT)) { - // FIXME: factor out powerDivider checks - if (Utils.isUndefined(self._stationInfo.powerDivider)) { - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`; - logger.error(errMsg); - throw Error(errMsg); - } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; - logger.error(errMsg); - throw Error(errMsg); - } - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`; - const powerMeasurandValues = {} as MeasurandValues; - const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider); - const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases()); - switch (self._getPowerOutType()) { - case PowerOutType.AC: - if (Utils.isUndefined(meterValuesTemplate[index].value)) { - powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase); - powerMeasurandValues.L2 = 0; - powerMeasurandValues.L3 = 0; - if (self._getNumberOfPhases() === 3) { - powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase); - powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase); - } - powerMeasurandValues.allPhases = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2); - } - break; - case PowerOutType.DC: - if (Utils.isUndefined(meterValuesTemplate[index].value)) { - powerMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxPower); - } - break; - default: - logger.error(errMsg); - throw Error(errMsg); - } - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - measurand: meterValuesTemplate[index].measurand, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.allPhases.toString() }, - }); - const sampledValuesIndex = meterValue.sampledValue.length - 1; - if (Utils.convertToFloat(meterValue.sampledValue[sampledValuesIndex].value) > maxPower || debug) { - logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxPower}`); - } - for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { - const phaseValue = `L${phase}-N`; - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] as string }, - phase: phaseValue as MeterValuePhase, - }); - } - // Current.Import measurand - } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.CURRENT_IMPORT && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.CURRENT_IMPORT)) { - // FIXME: factor out powerDivider checks - if (Utils.isUndefined(self._stationInfo.powerDivider)) { - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`; - logger.error(errMsg); - throw Error(errMsg); - } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; - logger.error(errMsg); - throw Error(errMsg); - } - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`; - const currentMeasurandValues: MeasurandValues = {} as MeasurandValues; - let maxAmperage: number; - switch (self._getPowerOutType()) { - case PowerOutType.AC: - maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut()); - if (Utils.isUndefined(meterValuesTemplate[index].value)) { - currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage); - currentMeasurandValues.L2 = 0; - currentMeasurandValues.L3 = 0; - if (self._getNumberOfPhases() === 3) { - currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage); - currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage); - } - currentMeasurandValues.allPhases = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2); - } - break; - case PowerOutType.DC: - maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut()); - if (Utils.isUndefined(meterValuesTemplate[index].value)) { - currentMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxAmperage); - } - break; - default: - logger.error(errMsg); - throw Error(errMsg); - } - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - measurand: meterValuesTemplate[index].measurand, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.allPhases.toString() }, - }); - const sampledValuesIndex = meterValue.sampledValue.length - 1; - if (Utils.convertToFloat(meterValue.sampledValue[sampledValuesIndex].value) > maxAmperage || debug) { - logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxAmperage}`); - } - for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { - const phaseValue = `L${phase}`; - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] as string }, - phase: phaseValue as MeterValuePhase, - }); } - // Energy.Active.Import.Register measurand (default) - } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { - // FIXME: factor out powerDivider checks - if (Utils.isUndefined(self._stationInfo.powerDivider)) { - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`; - logger.error(errMsg); - throw Error(errMsg); - } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { - const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; - logger.error(errMsg); - throw Error(errMsg); - } - if (Utils.isUndefined(meterValuesTemplate[index].value)) { - const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval); - // Persist previous value in connector - if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) { - connector.lastEnergyActiveImportRegisterValue += measurandValue; - } else { - connector.lastEnergyActiveImportRegisterValue = 0; + } + // 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]) + ); + this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; + if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { + this.getConnectorStatus(index).chargingProfiles = []; } } - meterValue.sampledValue.push({ - ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT_HOUR }, - ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, - ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, - ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, - ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : - { value: connector.lastEnergyActiveImportRegisterValue.toString() }, - }); - const sampledValuesIndex = meterValue.sampledValue.length - 1; - const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval)); - if (Utils.convertToFloat(meterValue.sampledValue[sampledValuesIndex].value) > maxConsumption || debug) { - logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxConsumption}`); - } - // Unsupported measurand - } else { - logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`); } } - const payload: MeterValuesRequest = { - connectorId, - transactionId: self.getConnector(connectorId).transactionId, - meterValue: meterValue, - }; - await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues'); - } catch (error) { - logger.error(self._logPrefix() + ' Send MeterValues error: %j', error); - throw error; - } - } - - async sendError(messageId: string, err: Error | OCPPError, commandName: string): Promise { - // Check exception type: only OCPP error are accepted - const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack); - // Send error - return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName); - } - - async sendMessage(messageId: string, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string): Promise { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const self = this; - // Send a message through wsConnection - return new Promise((resolve: (value?: any | PromiseLike) => void, reject: (reason?: any) => void) => { - let messageToSend; - // Type of message - switch (messageType) { - // Request - case Constants.OCPP_JSON_CALL_MESSAGE: - // Build request - this._requests[messageId] = [responseCallback, rejectCallback, commandParams]; - messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]); - break; - // Response - case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: - // Build response - messageToSend = JSON.stringify([messageType, messageId, commandParams]); - break; - // Error Message - case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: - // Build Error Message - messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]); - break; + } else { + logger.warn( + `${this.logPrefix()} Charging station information from template ${ + this.templateFile + } with no connectors configuration defined, using already defined connectors` + ); + } + // Initialize transaction attributes on connectors + for (const connectorId of this.connectors.keys()) { + if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) { + this.initializeConnectorStatus(connectorId); } - // Check if wsConnection is ready - if (this._wsConnection?.readyState === WebSocket.OPEN) { - if (this.getEnableStatistics()) { - this._statistics.addMessage(commandName, messageType); + } + } + + private getConfigurationFromFile(): ChargingStationConfiguration | null { + let configuration: ChargingStationConfiguration = null; + if (this.configurationFile && fs.existsSync(this.configurationFile)) { + try { + if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { + configuration = this.sharedLRUCache.getChargingStationConfiguration( + this.configurationFileHash + ); + } else { + const measureId = `${FileType.ChargingStationConfiguration} read`; + const beginId = PerformanceStatistics.beginMeasure(measureId); + configuration = JSON.parse( + fs.readFileSync(this.configurationFile, 'utf8') + ) as ChargingStationConfiguration; + PerformanceStatistics.endMeasure(measureId, beginId); + this.configurationFileHash = configuration.configurationHash; + this.sharedLRUCache.setChargingStationConfiguration(configuration); } - // Yes: Send Message - this._wsConnection.send(messageToSend); - } else { - let dups = false; - // Handle dups in buffer - for (const message of this._messageQueue) { - // Same message - if (JSON.stringify(messageToSend) === JSON.stringify(message)) { - dups = true; - break; - } + } catch (error) { + FileUtils.handleFileException( + this.logPrefix(), + FileType.ChargingStationConfiguration, + this.configurationFile, + error as NodeJS.ErrnoException + ); + } + } + return configuration; + } + + private saveConfiguration(): void { + if (this.configurationFile) { + try { + if (!fs.existsSync(path.dirname(this.configurationFile))) { + fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); } - if (!dups) { - // Buffer message - this._messageQueue.push(messageToSend); + 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)) + .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); + } else { + logger.debug( + `${this.logPrefix()} Not saving unchanged charging station configuration file ${ + this.configurationFile + }` + ); } - // Reject it - return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {})); + } catch (error) { + FileUtils.handleFileException( + this.logPrefix(), + FileType.ChargingStationConfiguration, + this.configurationFile, + error as NodeJS.ErrnoException + ); } - // Response? - if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) { - // Yes: send Ok - resolve(); - } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) { - // Send timeout - setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_SOCKET_TIMEOUT); + } else { + logger.error( + `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file` + ); + } + } + + private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null { + return this.getTemplateFromFile()?.Configuration ?? null; + } + + private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null { + let configuration: ChargingStationConfiguration = null; + if (this.getOcppPersistentConfiguration()) { + const configurationFromFile = this.getConfigurationFromFile(); + configuration = configurationFromFile?.configurationKey && configurationFromFile; + } + configuration && delete configuration.stationInfo; + return configuration; + } + + private getOcppConfiguration(): ChargingStationOcppConfiguration | null { + let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile(); + if (!ocppConfiguration) { + ocppConfiguration = this.getOcppConfigurationFromTemplate(); + } + return ocppConfiguration; + } + + private async onOpen(): Promise { + if (this.isWebSocketConnectionOpened()) { + logger.info( + `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded` + ); + if (!this.isRegistered()) { + // 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 + ); + } + } while ( + !this.isRegistered() && + (registrationRetryCount <= this.getRegistrationMaxRetries() || + this.getRegistrationMaxRetries() === -1) + ); } - - // Function that will receive the request's response - async function responseCallback(payload, requestPayload): Promise { - if (self.getEnableStatistics()) { - self._statistics.addMessage(commandName, messageType); + if (this.isRegistered()) { + if (this.isInAcceptedState()) { + await this.startMessageSequence(); + this.wsConnectionRestarted && this.flushMessageBuffer(); } - // Send the response - await self.handleResponse(commandName, payload, requestPayload); - resolve(payload); + } else { + logger.error( + `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})` + ); } + this.stopped && (this.stopped = false); + this.autoReconnectRetryCount = 0; + this.wsConnectionRestarted = false; + } else { + logger.warn( + `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` + ); + } + } + + private async onClose(code: number, reason: string): 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.autoReconnectRetryCount = 0; + break; + // Abnormal close + default: + logger.error( + `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString( + code + )}' and reason '${reason}'` + ); + await this.reconnect(code); + break; + } + } - // Function that will receive the request's rejection - function rejectCallback(error: OCPPError): void { - if (self.getEnableStatistics()) { - self._statistics.addMessage(commandName, messageType); + 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; + try { + const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; + if (Array.isArray(request) === true) { + [messageType, messageId] = 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 + ); + break; + // Outcome 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 (Array.isArray(cachedRequest) === true) { + [responseCallback, , requestCommandName, requestPayload] = cachedRequest; + } else { + throw new OCPPError( + ErrorType.PROTOCOL_ERROR, + `Cached request for message id ${messageId} response is not an array`, + null, + cachedRequest as unknown as JsonType + ); + } + logger.debug( + `${this.logPrefix()} << Command '${ + requestCommandName ?? 'unknown' + }' received response payload: ${JSON.stringify(request)}` + ); + responseCallback(commandPayload, requestPayload); + 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 (Array.isArray(cachedRequest) === true) { + [, errorCallback, requestCommandName] = cachedRequest; + } else { + throw new OCPPError( + ErrorType.PROTOCOL_ERROR, + `Cached request for message id ${messageId} error response is not an array`, + 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)); + break; + // Error + 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); } - logger.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error, commandName, commandParams); - // Build Exception - // eslint-disable-next-line no-empty-function - self._requests[messageId] = [() => { }, () => { }, {}]; // Properly format the request - // Send error - reject(error); + parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + } else { + throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, { + payload: 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)) { + logger.warn( + "%s Error thrown at incoming OCPP '%s' message '%j' handling is not an OCPPError:", + this.logPrefix(), + commandName ?? requestCommandName ?? null, + data.toString(), + error + ); } - }); + // Send error + messageType === MessageType.CALL_MESSAGE && + (await this.ocppRequestService.sendError( + this, + messageId, + error as OCPPError, + commandName ?? requestCommandName ?? null + )); + } } - async handleResponse(commandName: string, payload, requestPayload): Promise { - const responseCallbackFn = 'handleResponse' + commandName; - if (typeof this[responseCallbackFn] === 'function') { - await this[responseCallbackFn](payload, requestPayload); - } else { - logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn); - } + private onPing(): void { + logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); } - handleResponseBootNotification(payload: BootNotificationResponse, requestPayload: BootNotificationRequest): void { - if (payload.status === RegistrationStatus.ACCEPTED) { - this._heartbeatInterval = payload.interval * 1000; - this._heartbeatSetInterval ? this._restartHeartbeat() : this._startHeartbeat(); - this._addConfigurationKey('HeartBeatInterval', payload.interval.toString()); - this._addConfigurationKey('HeartbeatInterval', payload.interval.toString(), false, false); - this._hasStopped && (this._hasStopped = false); - } else if (payload.status === RegistrationStatus.PENDING) { - logger.info(this._logPrefix() + ' Charging station in pending state on the central server'); - } else { - logger.info(this._logPrefix() + ' Charging station rejected by the central server'); - } + private onPong(): void { + 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); } - _initTransactionOnConnector(connectorId: number): void { - this.getConnector(connectorId).transactionStarted = false; - this.getConnector(connectorId).transactionId = null; - this.getConnector(connectorId).idTag = null; - this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1; + private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean | undefined { + const localStationInfo = stationInfo ?? this.stationInfo; + return !Utils.isUndefined(localStationInfo.useConnectorId0) + ? localStationInfo.useConnectorId0 + : true; } - _resetTransactionOnConnector(connectorId: number): void { - this._initTransactionOnConnector(connectorId); - if (this.getConnector(connectorId).transactionSetInterval) { - clearInterval(this.getConnector(connectorId).transactionSetInterval); + private getNumberOfRunningTransactions(): number { + let trxCount = 0; + for (const connectorId of this.connectors.keys()) { + if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { + trxCount++; + } } + return trxCount; } - async handleResponseStartTransaction(payload: StartTransactionResponse, requestPayload: StartTransactionRequest): Promise { - const connectorId = Utils.convertToInt(requestPayload.connectorId); - if (this.getConnector(connectorId).transactionStarted) { - logger.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId.toString() + ': %j', this.getConnector(connectorId)); - return; + // 0 for disabling + private getConnectionTimeout(): number | undefined { + if ( + ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.ConnectionTimeOut + ) + ) { + return ( + parseInt( + ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.ConnectionTimeOut + ).value + ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT + ); } + return Constants.DEFAULT_CONNECTION_TIMEOUT; + } - let transactionConnectorId: number; - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && Utils.convertToInt(connector) === connectorId) { - transactionConnectorId = Utils.convertToInt(connector); - break; - } + // -1 for unlimited, 0 for disabling + private getAutoReconnectMaxRetries(): number | undefined { + if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { + return this.stationInfo.autoReconnectMaxRetries; } - if (!transactionConnectorId) { - logger.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId.toString()); - return; + if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { + return Configuration.getAutoReconnectMaxRetries(); } - if (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { - this.getConnector(connectorId).transactionStarted = true; - this.getConnector(connectorId).transactionId = payload.transactionId; - this.getConnector(connectorId).idTag = requestPayload.idTag; - this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = 0; - await this.sendStatusNotification(connectorId, ChargePointStatus.CHARGING); - logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId.toString() + ' STARTED on ' + this._stationInfo.name + '#' + connectorId.toString() + ' for idTag ' + requestPayload.idTag); - if (this._stationInfo.powerSharedByConnectors) { - this._stationInfo.powerDivider++; - } - const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval'); - this._startMeterValues(connectorId, - configuredMeterValueSampleInterval ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000 : 60000); - } else { - logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId.toString() + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag); - this._resetTransactionOnConnector(connectorId); - await this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE); + return -1; + } + + // 0 for disabling + private getRegistrationMaxRetries(): number | undefined { + if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { + return this.stationInfo.registrationMaxRetries; } + return -1; } - async handleResponseStopTransaction(payload: StopTransactionResponse, requestPayload: StopTransactionRequest): Promise { - let transactionConnectorId: number; - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === Utils.convertToInt(requestPayload.transactionId)) { - transactionConnectorId = Utils.convertToInt(connector); - break; - } + private getPowerDivider(): number { + let powerDivider = this.getNumberOfConnectors(); + if (this.stationInfo?.powerSharedByConnectors) { + powerDivider = this.getNumberOfRunningTransactions(); } - if (!transactionConnectorId) { - logger.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload.transactionId.toString()); - return; + 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) + ); + case CurrentType.DC: + return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo)); + } + } + + private getAmperageLimitation(): number | undefined { + if ( + this.stationInfo.amperageLimitationOcppKey && + ChargingStationConfigurationUtils.getConfigurationKey( + this, + this.stationInfo.amperageLimitationOcppKey + ) + ) { + return ( + Utils.convertToInt( + ChargingStationConfigurationUtils.getConfigurationKey( + this, + this.stationInfo.amperageLimitationOcppKey + ).value + ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo) + ); + } + } + + private async startMessageSequence(): Promise { + if (this.stationInfo?.autoRegister) { + 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 (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { - await this.sendStatusNotification(transactionConnectorId, ChargePointStatus.AVAILABLE); - if (this._stationInfo.powerSharedByConnectors) { - this._stationInfo.powerDivider--; + // 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; } - logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId.toString() + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId.toString()); - this._resetTransactionOnConnector(transactionConnectorId); - } else { - logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId.toString() + ' REJECTED with status ' + payload.idTagInfo?.status); } + // Start the ATG + this.startAutomaticTransactionGenerator(); } - handleResponseStatusNotification(payload: StatusNotificationRequest, requestPayload: StatusNotificationResponse): void { - logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload); - } - - handleResponseMeterValues(payload: MeterValuesRequest, requestPayload: MeterValuesResponse): void { - logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload); + private startAutomaticTransactionGenerator() { + if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable) { + if (!this.automaticTransactionGenerator) { + this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance( + this.getAutomaticTransactionGeneratorConfigurationFromTemplate(), + this + ); + } + if (!this.automaticTransactionGenerator.started) { + this.automaticTransactionGenerator.start(); + } + } } - handleResponseHeartbeat(payload: HeartbeatResponse, requestPayload: HeartbeatRequest): void { - logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload); + private stopAutomaticTransactionGenerator(): void { + if (this.automaticTransactionGenerator?.started) { + this.automaticTransactionGenerator.stop(); + this.automaticTransactionGenerator = null; + } } - async handleRequest(messageId: string, commandName: string, commandPayload): Promise { - let response; - // Call - if (typeof this['handleRequest' + commandName] === 'function') { - try { - // Call the method to build the response - response = await this['handleRequest' + commandName](commandPayload); - } catch (error) { - // Log - logger.error(this._logPrefix() + ' Handle request error: %j', error); - // Send back response to inform backend - await this.sendError(messageId, error, commandName); - throw error; - } + private async stopMessageSequence( + reason: StopTransactionReason = StopTransactionReason.NONE + ): Promise { + // Stop WebSocket ping + this.stopWebSocketPing(); + // Stop heartbeat + this.stopHeartbeat(); + // Stop ongoing transactions + if (this.automaticTransactionGenerator?.configuration?.enable) { + this.stopAutomaticTransactionGenerator(); } else { - // Throw exception - await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName); - throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`); + 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( + this, + RequestCommand.METER_VALUES, + { + connectorId, + transactionId, + meterValue: [transactionEndMeterValue], + } + ); + } + await this.ocppRequestService.requestHandler< + StopTransactionRequest, + StopTransactionResponse + >(this, RequestCommand.STOP_TRANSACTION, { + transactionId, + meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId), + idTag: this.getTransactionIdTag(transactionId), + reason, + }); + } + } } - // Send response - await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName); } - // Simulate charging station restart - handleRequestReset(commandPayload: ResetRequest): DefaultResponse { - setImmediate(async () => { - await this.stop(commandPayload.type + 'Reset' as StopTransactionReason); - await Utils.sleep(this._stationInfo.resetTime); - await this.start(); - }); - logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`); - return Constants.OCPP_RESPONSE_ACCEPTED; + private startWebSocketPing(): void { + const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.WebSocketPingInterval + ) + ? Utils.convertToInt( + ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.WebSocketPingInterval + ).value + ) + : 0; + if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { + this.webSocketPingSetInterval = setInterval(() => { + if (this.isWebSocketConnectionOpened()) { + this.wsConnection.ping((): void => { + /* This is intentional */ + }); + } + }, webSocketPingInterval * 1000); + logger.info( + this.logPrefix() + + ' WebSocket ping started every ' + + Utils.formatDurationSeconds(webSocketPingInterval) + ); + } else if (this.webSocketPingSetInterval) { + logger.info( + this.logPrefix() + + ' WebSocket ping every ' + + Utils.formatDurationSeconds(webSocketPingInterval) + + ' already started' + ); + } else { + logger.error( + `${this.logPrefix()} WebSocket ping interval set to ${ + webSocketPingInterval + ? Utils.formatDurationSeconds(webSocketPingInterval) + : webSocketPingInterval + }, not starting the WebSocket ping` + ); + } } - handleRequestClearCache(): DefaultResponse { - return Constants.OCPP_RESPONSE_ACCEPTED; + private stopWebSocketPing(): void { + if (this.webSocketPingSetInterval) { + clearInterval(this.webSocketPingSetInterval); + } } - async handleRequestUnlockConnector(commandPayload: UnlockConnectorRequest): Promise { - const connectorId = Utils.convertToInt(commandPayload.connectorId); - if (connectorId === 0) { - logger.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId.toString()); - return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED; - } - if (this.getConnector(connectorId).transactionStarted) { - const stopResponse = await this.sendStopTransaction(this.getConnector(connectorId).transactionId, StopTransactionReason.UNLOCK_COMMAND); - if (stopResponse.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { - return Constants.OCPP_RESPONSE_UNLOCKED; + private getConfiguredSupervisionUrl(): URL { + const supervisionUrls = Utils.cloneObject( + this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls() + ); + if (!Utils.isEmptyArray(supervisionUrls)) { + let urlIndex = 0; + 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` + ); + } + break; + 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; + break; } - return Constants.OCPP_RESPONSE_UNLOCK_FAILED; + return new URL(supervisionUrls[urlIndex]); } - await this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE); - return Constants.OCPP_RESPONSE_UNLOCKED; + return new URL(supervisionUrls as string); } - _getConfigurationKey(key: string): ConfigurationKey { - return this._configuration.configurationKey.find((configElement) => configElement.key === key); + private getHeartbeatInterval(): number | undefined { + const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.HeartbeatInterval + ); + if (HeartbeatInterval) { + return Utils.convertToInt(HeartbeatInterval.value) * 1000; + } + const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( + this, + StandardParametersKey.HeartBeatInterval + ); + if (HeartBeatInterval) { + return Utils.convertToInt(HeartBeatInterval.value) * 1000; + } + !this.stationInfo?.autoRegister && + logger.warn( + `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ + Constants.DEFAULT_HEARTBEAT_INTERVAL + }` + ); + return Constants.DEFAULT_HEARTBEAT_INTERVAL; } - _addConfigurationKey(key: string, value: string, readonly = false, visible = true, reboot = false): void { - const keyFound = this._getConfigurationKey(key); - if (!keyFound) { - this._configuration.configurationKey.push({ - key, - readonly, - value, - visible, - reboot, - }); + private stopHeartbeat(): void { + if (this.heartbeatSetInterval) { + clearInterval(this.heartbeatSetInterval); } } - _setConfigurationKeyValue(key: string, value: string): void { - const keyFound = this._getConfigurationKey(key); - if (keyFound) { - const keyIndex = this._configuration.configurationKey.indexOf(keyFound); - this._configuration.configurationKey[keyIndex].value = value; + private terminateWSConnection(): void { + if (this.isWebSocketConnectionOpened()) { + this.wsConnection.terminate(); + this.wsConnection = null; } } - handleRequestGetConfiguration(commandPayload: GetConfigurationRequest): GetConfigurationResponse { - const configurationKey: ConfigurationKey[] = []; - const unknownKey: string[] = []; - if (Utils.isEmptyArray(commandPayload.key)) { - for (const configuration of this._configuration.configurationKey) { - if (Utils.isUndefined(configuration.visible)) { - configuration.visible = true; - } - if (!configuration.visible) { - continue; - } - configurationKey.push({ - key: configuration.key, - readonly: configuration.readonly, - value: configuration.value, - }); - } - } else { - for (const key of commandPayload.key) { - const keyFound = this._getConfigurationKey(key); - if (keyFound) { - if (Utils.isUndefined(keyFound.visible)) { - keyFound.visible = true; - } - if (!keyFound.visible) { - continue; - } - configurationKey.push({ - key: keyFound.key, - readonly: keyFound.readonly, - value: keyFound.value, - }); - } else { - unknownKey.push(key); - } - } - } - return { - configurationKey, - unknownKey, - }; - } - - handleRequestChangeConfiguration(commandPayload: ChangeConfigurationRequest): ChangeConfigurationResponse { - const keyToChange = this._getConfigurationKey(commandPayload.key); - if (!keyToChange) { - return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED; - } else if (keyToChange && keyToChange.readonly) { - return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED; - } else if (keyToChange && !keyToChange.readonly) { - const keyIndex = this._configuration.configurationKey.indexOf(keyToChange); - let valueChanged = false; - if (this._configuration.configurationKey[keyIndex].value !== commandPayload.value) { - this._configuration.configurationKey[keyIndex].value = commandPayload.value; - valueChanged = true; - } - let triggerHeartbeatRestart = false; - if (keyToChange.key === 'HeartBeatInterval' && valueChanged) { - this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value); - triggerHeartbeatRestart = true; - } - if (keyToChange.key === 'HeartbeatInterval' && valueChanged) { - this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value); - triggerHeartbeatRestart = true; - } - if (triggerHeartbeatRestart) { - this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000; - this._restartHeartbeat(); - } - if (keyToChange.key === 'WebSocketPingInterval' && valueChanged) { - this._restartWebSocketPing(); - } - if (keyToChange.reboot) { - return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED; - } - return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED; + private stopMeterValues(connectorId: number) { + if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { + clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval); } } - handleRequestSetChargingProfile(commandPayload: SetChargingProfileRequest): SetChargingProfileResponse { - if (!this.getConnector(commandPayload.connectorId)) { - logger.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`); - return Constants.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED; - } - if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE && !this.getConnector(commandPayload.connectorId)?.transactionStarted) { - return Constants.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED; - } - this.getConnector(commandPayload.connectorId).chargingProfiles.forEach((chargingProfile: ChargingProfile, index: number) => { - if (chargingProfile.chargingProfileId === commandPayload.csChargingProfiles.chargingProfileId - || (chargingProfile.stackLevel === commandPayload.csChargingProfiles.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.csChargingProfiles.chargingProfilePurpose)) { - this.getConnector(commandPayload.connectorId).chargingProfiles[index] = chargingProfile; - return Constants.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED; - } - }); - this.getConnector(commandPayload.connectorId).chargingProfiles.push(commandPayload.csChargingProfiles); - return Constants.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED; - } - - async handleRequestRemoteStartTransaction(commandPayload: RemoteStartTransactionRequest): Promise { - const transactionConnectorID: number = commandPayload.connectorId ? Utils.convertToInt(commandPayload.connectorId) : 1; - if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) { - // Check if authorized - if (this._authorizedTags.find((value) => value === commandPayload.idTag)) { - // Authorization successful start transaction - await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag); - logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag); - return Constants.OCPP_RESPONSE_ACCEPTED; - } - logger.error(this._logPrefix() + ' Remote starting transaction REJECTED, idTag ' + commandPayload.idTag); - return Constants.OCPP_RESPONSE_REJECTED; - } - // No local authorization check required => start transaction - await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag); - logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag); - return Constants.OCPP_RESPONSE_ACCEPTED; + private getReconnectExponentialDelay(): boolean | undefined { + return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) + ? this.stationInfo.reconnectExponentialDelay + : false; } - async handleRequestRemoteStopTransaction(commandPayload: RemoteStopTransactionRequest): Promise { - const transactionId = Utils.convertToInt(commandPayload.transactionId); - for (const connector in this._connectors) { - if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { - await this.sendStopTransaction(transactionId); - return Constants.OCPP_RESPONSE_ACCEPTED; - } - } - logger.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString()); - return Constants.OCPP_RESPONSE_REJECTED; + private async reconnect(code: number): Promise { + // Stop WebSocket ping + this.stopWebSocketPing(); + // Stop heartbeat + this.stopHeartbeat(); + // Stop the ATG if needed + if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure) { + this.stopAutomaticTransactionGenerator(); + } + if ( + this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || + this.getAutoReconnectMaxRetries() === -1 + ) { + this.autoReconnectRetryCount++; + const reconnectDelay = this.getReconnectExponentialDelay() + ? Utils.exponentialDelay(this.autoReconnectRetryCount) + : this.getConnectionTimeout() * 1000; + const reconnectDelayWithdraw = 1000; + const reconnectTimeout = + reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0 + ? reconnectDelay - reconnectDelayWithdraw + : 0; + logger.error( + `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo( + reconnectDelay, + 2 + )}ms, timeout ${reconnectTimeout}ms` + ); + await Utils.sleep(reconnectDelay); + logger.error( + this.logPrefix() + + ' WebSocket: reconnecting try #' + + this.autoReconnectRetryCount.toString() + ); + this.openWSConnection( + { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout }, + { closeOpened: true } + ); + this.wsConnectionRestarted = true; + } else if (this.getAutoReconnectMaxRetries() !== -1) { + logger.error( + `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${ + this.autoReconnectRetryCount + }) or retry disabled (${this.getAutoReconnectMaxRetries()})` + ); + } + } + + 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; } } -