1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { AvailabilityType
, BootNotificationRequest
, CachedRequest
, IncomingRequest
, IncomingRequestCommand
, RequestCommand
} from
'../types/ocpp/Requests';
4 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
5 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
6 import ChargingStationTemplate
, { CurrentType
, PowerUnits
, Voltage
} from
'../types/ChargingStationTemplate';
7 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
, VendorDefaultParametersKey
} from
'../types/ocpp/Configuration';
8 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
9 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
10 import WebSocket
, { ClientOptions
, Data
, OPEN
} from
'ws';
12 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
13 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
14 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
15 import ChargingStationInfo from
'../types/ChargingStationInfo';
16 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
17 import { ClientRequestArgs
} from
'http';
18 import Configuration from
'../utils/Configuration';
19 import { ConnectorStatus
} from
'../types/ConnectorStatus';
20 import Constants from
'../utils/Constants';
21 import { ErrorType
} from
'../types/ocpp/ErrorType';
22 import FileUtils from
'../utils/FileUtils';
23 import { MessageType
} from
'../types/ocpp/MessageType';
24 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
25 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
26 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
27 import OCPPError from
'../exception/OCPPError';
28 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
29 import OCPPRequestService from
'./ocpp/OCPPRequestService';
30 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
31 import PerformanceStatistics from
'../performance/PerformanceStatistics';
32 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
33 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
34 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
35 import { URL
} from
'url';
36 import Utils from
'../utils/Utils';
37 import crypto from
'crypto';
39 import logger from
'../utils/Logger';
40 import { parentPort
} from
'worker_threads';
41 import path from
'path';
43 export default class ChargingStation
{
44 public readonly stationTemplateFile
: string;
45 public authorizedTags
: string[];
46 public stationInfo
!: ChargingStationInfo
;
47 public readonly connectors
: Map
<number, ConnectorStatus
>;
48 public configuration
!: ChargingStationConfiguration
;
49 public wsConnection
!: WebSocket
;
50 public readonly requests
: Map
<string, CachedRequest
>;
51 public performanceStatistics
!: PerformanceStatistics
;
52 public heartbeatSetInterval
!: NodeJS
.Timeout
;
53 public ocppRequestService
!: OCPPRequestService
;
54 private readonly index
: number;
55 private bootNotificationRequest
!: BootNotificationRequest
;
56 private bootNotificationResponse
!: BootNotificationResponse
| null;
57 private connectorsConfigurationHash
!: string;
58 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
59 private readonly messageBuffer
: Set
<string>;
60 private wsConfiguredConnectionUrl
!: URL
;
61 private wsConnectionRestarted
: boolean;
62 private stopped
: boolean;
63 private autoReconnectRetryCount
: number;
64 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
65 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
67 constructor(index
: number, stationTemplateFile
: string) {
69 this.stationTemplateFile
= stationTemplateFile
;
70 this.connectors
= new Map
<number, ConnectorStatus
>();
74 this.wsConnectionRestarted
= false;
75 this.autoReconnectRetryCount
= 0;
77 this.requests
= new Map
<string, CachedRequest
>();
78 this.messageBuffer
= new Set
<string>();
80 this.authorizedTags
= this.getAuthorizedTags();
83 get
wsConnectionUrl(): URL
{
84 return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
).value
+ '/' + this.stationInfo
.chargingStationId
) : this.wsConfiguredConnectionUrl
;
87 public logPrefix(): string {
88 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
91 public getBootNotificationRequest(): BootNotificationRequest
{
92 return this.bootNotificationRequest
;
95 public getRandomIdTag(): string {
96 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
97 return this.authorizedTags
[index
];
100 public hasAuthorizedTags(): boolean {
101 return !Utils
.isEmptyArray(this.authorizedTags
);
104 public getEnableStatistics(): boolean | undefined {
105 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
108 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
109 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
112 public getNumberOfPhases(): number | undefined {
113 switch (this.getCurrentOutType()) {
115 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
121 public isWebSocketConnectionOpened(): boolean {
122 return this?.wsConnection
?.readyState
=== OPEN
;
125 public isInPendingState(): boolean {
126 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
129 public isInAcceptedState(): boolean {
130 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
133 public isInRejectedState(): boolean {
134 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
137 public isRegistered(): boolean {
138 return this.isInAcceptedState() || this.isInPendingState();
141 public isChargingStationAvailable(): boolean {
142 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
145 public isConnectorAvailable(id
: number): boolean {
146 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
149 public getNumberOfConnectors(): number {
150 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
153 public getConnectorStatus(id
: number): ConnectorStatus
{
154 return this.connectors
.get(id
);
157 public getCurrentOutType(): CurrentType
| undefined {
158 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
161 public getVoltageOut(): number | undefined {
162 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
163 let defaultVoltageOut
: number;
164 switch (this.getCurrentOutType()) {
166 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
169 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
172 logger
.error(errMsg
);
173 throw new Error(errMsg
);
175 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
178 public getTransactionIdTag(transactionId
: number): string | undefined {
179 for (const connectorId
of this.connectors
.keys()) {
180 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
181 return this.getConnectorStatus(connectorId
).transactionIdTag
;
186 public getOutOfOrderEndMeterValues(): boolean {
187 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
190 public getBeginEndMeterValues(): boolean {
191 return this.stationInfo
.beginEndMeterValues
?? false;
194 public getMeteringPerTransaction(): boolean {
195 return this.stationInfo
.meteringPerTransaction
?? true;
198 public getTransactionDataMeterValues(): boolean {
199 return this.stationInfo
.transactionDataMeterValues
?? false;
202 public getMainVoltageMeterValues(): boolean {
203 return this.stationInfo
.mainVoltageMeterValues
?? true;
206 public getPhaseLineToLineVoltageMeterValues(): boolean {
207 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
210 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
211 if (this.getMeteringPerTransaction()) {
212 for (const connectorId
of this.connectors
.keys()) {
213 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
214 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
218 for (const connectorId
of this.connectors
.keys()) {
219 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
220 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
225 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
226 if (this.getMeteringPerTransaction()) {
227 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
229 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
232 public getAuthorizeRemoteTxRequests(): boolean {
233 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
234 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
237 public getLocalAuthListEnabled(): boolean {
238 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
239 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
242 public restartWebSocketPing(): void {
243 // Stop WebSocket ping
244 this.stopWebSocketPing();
245 // Start WebSocket ping
246 this.startWebSocketPing();
249 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
250 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
251 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
252 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
255 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
256 logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`);
259 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
260 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
261 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
262 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
263 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
264 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
265 return sampledValueTemplates[index];
266 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
267 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
268 return sampledValueTemplates[index];
269 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
270 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
271 return sampledValueTemplates[index];
274 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
275 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
276 logger.error(errorMsg);
277 throw new Error(errorMsg);
279 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
282 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
283 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
286 public startHeartbeat(): void {
287 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
288 // eslint-disable-next-line @typescript-eslint/no-misused-promises
289 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
290 await this.ocppRequestService
.sendHeartbeat();
291 }, this.getHeartbeatInterval());
292 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
293 } else if (this.heartbeatSetInterval
) {
294 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
296 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
300 public restartHeartbeat(): void {
302 this.stopHeartbeat();
304 this.startHeartbeat();
307 public startMeterValues(connectorId
: number, interval
: number): void {
308 if (connectorId
=== 0) {
309 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
312 if (!this.getConnectorStatus(connectorId
)) {
313 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
316 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
317 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
319 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
320 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
324 // eslint-disable-next-line @typescript-eslint/no-misused-promises
325 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
326 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
329 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
333 public start(): void {
334 if (this.getEnableStatistics()) {
335 this.performanceStatistics
.start();
337 this.openWSConnection();
338 // Monitor authorization file
339 this.startAuthorizationFileMonitoring();
340 // Monitor station template file
341 this.startStationTemplateFileMonitoring();
342 // Handle WebSocket message
343 this.wsConnection
.on('message', this.onMessage
.bind(this));
344 // Handle WebSocket error
345 this.wsConnection
.on('error', this.onError
.bind(this));
346 // Handle WebSocket close
347 this.wsConnection
.on('close', this.onClose
.bind(this));
348 // Handle WebSocket open
349 this.wsConnection
.on('open', this.onOpen
.bind(this));
350 // Handle WebSocket ping
351 this.wsConnection
.on('ping', this.onPing
.bind(this));
352 // Handle WebSocket pong
353 this.wsConnection
.on('pong', this.onPong
.bind(this));
354 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
357 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
358 // Stop message sequence
359 await this.stopMessageSequence(reason
);
360 for (const connectorId
of this.connectors
.keys()) {
361 if (connectorId
> 0) {
362 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
363 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
366 if (this.isWebSocketConnectionOpened()) {
367 this.wsConnection
.close();
369 if (this.getEnableStatistics()) {
370 this.performanceStatistics
.stop();
372 this.bootNotificationResponse
= null;
373 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
377 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
378 return this.configuration
.configurationKey
.find((configElement
) => {
379 if (caseInsensitive
) {
380 return configElement
.key
.toLowerCase() === key
.toLowerCase();
382 return configElement
.key
=== key
;
386 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
387 const keyFound
= this.getConfigurationKey(key
);
388 const readonly = options
.readonly;
389 const visible
= options
.visible
;
390 const reboot
= options
.reboot
;
392 this.configuration
.configurationKey
.push({
400 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
404 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
405 const keyFound
= this.getConfigurationKey(key
);
407 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
408 this.configuration
.configurationKey
[keyIndex
].value
= value
;
410 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
414 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
415 let cpReplaced
= false;
416 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
417 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
418 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
419 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
420 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
425 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
428 public resetConnectorStatus(connectorId
: number): void {
429 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
430 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
431 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
432 this.getConnectorStatus(connectorId
).transactionStarted
= false;
433 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
434 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
435 delete this.getConnectorStatus(connectorId
).transactionId
;
436 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
437 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
438 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
439 this.stopMeterValues(connectorId
);
442 public bufferMessage(message
: string): void {
443 this.messageBuffer
.add(message
);
446 private flushMessageBuffer() {
447 if (this.messageBuffer
.size
> 0) {
448 this.messageBuffer
.forEach((message
) => {
449 // TODO: evaluate the need to track performance
450 this.wsConnection
.send(message
);
451 this.messageBuffer
.delete(message
);
456 private getSupervisionUrlOcppConfiguration(): boolean {
457 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
460 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
461 // In case of multiple instances: add instance index to charging station id
462 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
463 const idSuffix
= stationTemplate
.nameSuffix
?? '';
464 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
467 private buildStationInfo(): ChargingStationInfo
{
468 let stationTemplateFromFile
: ChargingStationTemplate
;
470 // Load template file
471 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
472 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
473 fs
.closeSync(fileDescriptor
);
475 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
477 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
478 // Deprecation template keys section
479 this.warnDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', chargingStationId
, 'Use \'supervisionUrls\' instead');
480 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
481 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
482 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
483 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
484 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
485 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
486 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
487 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
488 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
490 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
491 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
492 ? stationTemplateFromFile
.power
* 1000
493 : stationTemplateFromFile
.power
;
495 delete stationInfo
.power
;
496 delete stationInfo
.powerUnit
;
497 stationInfo
.chargingStationId
= chargingStationId
;
498 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
502 private getOcppVersion(): OCPPVersion
{
503 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
506 private handleUnsupportedVersion(version
: OCPPVersion
) {
507 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
508 logger
.error(errMsg
);
509 throw new Error(errMsg
);
512 private initialize(): void {
513 this.stationInfo
= this.buildStationInfo();
514 this.configuration
= this.getTemplateChargingStationConfiguration();
515 delete this.stationInfo
.Configuration
;
516 this.bootNotificationRequest
= {
517 chargePointModel
: this.stationInfo
.chargePointModel
,
518 chargePointVendor
: this.stationInfo
.chargePointVendor
,
519 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
520 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
522 // Build connectors if needed
523 const maxConnectors
= this.getMaxNumberOfConnectors();
524 if (maxConnectors
<= 0) {
525 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
527 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
528 if (templateMaxConnectors
<= 0) {
529 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
531 if (!this.stationInfo
.Connectors
[0]) {
532 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
535 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
536 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
537 this.stationInfo
.randomConnectors
= true;
539 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
540 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
541 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
542 connectorsConfigChanged
&& (this.connectors
.clear());
543 this.connectorsConfigurationHash
= connectorsConfigHash
;
544 // Add connector Id 0
545 let lastConnector
= '0';
546 for (lastConnector
in this.stationInfo
.Connectors
) {
547 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
548 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
549 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
550 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
551 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
552 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
556 // Generate all connectors
557 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
558 for (let index
= 1; index
<= maxConnectors
; index
++) {
559 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
560 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
561 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
562 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
563 this.getConnectorStatus(index
).chargingProfiles
= [];
568 // Avoid duplication of connectors related information
569 delete this.stationInfo
.Connectors
;
570 // Initialize transaction attributes on connectors
571 for (const connectorId
of this.connectors
.keys()) {
572 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
573 this.initializeConnectorStatus(connectorId
);
576 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
);
577 switch (this.getOcppVersion()) {
578 case OCPPVersion
.VERSION_16
:
579 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
580 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
583 this.handleUnsupportedVersion(this.getOcppVersion());
587 this.initOcppParameters();
588 if (this.stationInfo
.autoRegister
) {
589 this.bootNotificationResponse
= {
590 currentTime
: new Date().toISOString(),
591 interval
: this.getHeartbeatInterval() / 1000,
592 status: RegistrationStatus
.ACCEPTED
595 this.stationInfo
.powerDivider
= this.getPowerDivider();
596 if (this.getEnableStatistics()) {
597 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
601 private initOcppParameters(): void {
602 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
603 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionUrl().href
, { reboot
: true });
605 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
606 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
608 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
609 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
610 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
612 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
613 const connectorPhaseRotation
= [];
614 for (const connectorId
of this.connectors
.keys()) {
616 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
617 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
618 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
619 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
621 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
622 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
623 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
624 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
627 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
629 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
630 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
632 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
633 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
634 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
636 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
637 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
641 private async onOpen(): Promise
<void> {
642 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
643 if (!this.isRegistered()) {
644 // Send BootNotification
645 let registrationRetryCount
= 0;
647 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
648 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
649 if (!this.isRegistered()) {
650 registrationRetryCount
++;
651 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
653 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
655 if (this.isRegistered() && this.stationInfo
.autoRegister
) {
656 await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
657 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
659 if (this.isInAcceptedState()) {
660 await this.startMessageSequence();
661 this.stopped
&& (this.stopped
= false);
662 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
663 this.flushMessageBuffer();
665 } else if (this.isInPendingState()) {
666 // The central server shall issue a TriggerMessage to the charging station for the boot notification at the end of its configuration process
667 while (!this.isInAcceptedState()) {
668 await Utils
.sleep(Constants
.CHARGING_STATION_DEFAULT_START_SEQUENCE_DELAY
);
670 await this.startMessageSequence();
671 this.stopped
&& (this.stopped
= false);
672 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
673 this.flushMessageBuffer();
676 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
678 this.autoReconnectRetryCount
= 0;
679 this.wsConnectionRestarted
= false;
682 private async onClose(code
: number, reason
: string): Promise
<void> {
685 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
686 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
687 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
688 this.autoReconnectRetryCount
= 0;
692 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
693 await this.reconnect(code
);
698 private async onMessage(data
: Data
): Promise
<void> {
699 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
700 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
701 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
702 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
703 let requestPayload
: Record
<string, unknown
>;
704 let cachedRequest
: CachedRequest
;
707 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
708 if (Utils
.isIterable(request
)) {
710 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
712 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
714 // Check the Type of message
715 switch (messageType
) {
717 case MessageType
.CALL_MESSAGE
:
718 if (this.getEnableStatistics()) {
719 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
722 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
725 case MessageType
.CALL_RESULT_MESSAGE
:
727 cachedRequest
= this.requests
.get(messageId
);
728 if (Utils
.isIterable(cachedRequest
)) {
729 [responseCallback
, , , requestPayload
] = cachedRequest
;
731 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
733 if (!responseCallback
) {
735 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
737 responseCallback(commandName
, requestPayload
);
740 case MessageType
.CALL_ERROR_MESSAGE
:
741 cachedRequest
= this.requests
.get(messageId
);
742 if (Utils
.isIterable(cachedRequest
)) {
743 [, rejectCallback
, requestCommandName
] = cachedRequest
;
745 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
747 if (!rejectCallback
) {
749 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
751 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
755 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
756 logger
.error(errMsg
);
757 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
761 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
763 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
767 private onPing(): void {
768 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
771 private onPong(): void {
772 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
775 private async onError(error
: WSError
): Promise
<void> {
776 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
777 // switch (error.code) {
778 // case 'ECONNREFUSED':
779 // await this.reconnect(error);
784 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
785 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
788 private getAuthorizationFile(): string | undefined {
789 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
792 private getAuthorizedTags(): string[] {
793 let authorizedTags
: string[] = [];
794 const authorizationFile
= this.getAuthorizationFile();
795 if (authorizationFile
) {
797 // Load authorization file
798 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
799 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
800 fs
.closeSync(fileDescriptor
);
802 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
805 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
807 return authorizedTags
;
810 private getUseConnectorId0(): boolean | undefined {
811 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
814 private getNumberOfRunningTransactions(): number {
816 for (const connectorId
of this.connectors
.keys()) {
817 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
825 private getConnectionTimeout(): number | undefined {
826 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
827 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
829 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
832 // -1 for unlimited, 0 for disabling
833 private getAutoReconnectMaxRetries(): number | undefined {
834 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
835 return this.stationInfo
.autoReconnectMaxRetries
;
837 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
838 return Configuration
.getAutoReconnectMaxRetries();
844 private getRegistrationMaxRetries(): number | undefined {
845 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
846 return this.stationInfo
.registrationMaxRetries
;
851 private getPowerDivider(): number {
852 let powerDivider
= this.getNumberOfConnectors();
853 if (this.stationInfo
.powerSharedByConnectors
) {
854 powerDivider
= this.getNumberOfRunningTransactions();
859 private getTemplateMaxNumberOfConnectors(): number {
860 return Object.keys(this.stationInfo
.Connectors
).length
;
863 private getMaxNumberOfConnectors(): number {
864 let maxConnectors
: number;
865 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
866 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
867 // Distribute evenly the number of connectors
868 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
869 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
870 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
872 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
874 return maxConnectors
;
877 private async startMessageSequence(): Promise
<void> {
878 // Start WebSocket ping
879 this.startWebSocketPing();
881 this.startHeartbeat();
882 // Initialize connectors status
883 for (const connectorId
of this.connectors
.keys()) {
884 if (connectorId
=== 0) {
886 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
887 // Send status in template at startup
888 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
889 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
890 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
891 // Send status in template after reset
892 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
893 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
894 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
895 // Send previous status at template reload
896 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
898 // Send default status
899 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
900 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
904 this.startAutomaticTransactionGenerator();
907 private startAutomaticTransactionGenerator() {
908 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
909 if (!this.automaticTransactionGenerator
) {
910 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
912 if (!this.automaticTransactionGenerator
.started
) {
913 this.automaticTransactionGenerator
.start();
918 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
919 // Stop WebSocket ping
920 this.stopWebSocketPing();
922 this.stopHeartbeat();
924 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
925 this.automaticTransactionGenerator
&&
926 this.automaticTransactionGenerator
.started
) {
927 this.automaticTransactionGenerator
.stop();
929 for (const connectorId
of this.connectors
.keys()) {
930 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
931 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
932 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
933 this.getTransactionIdTag(transactionId
), reason
);
939 private startWebSocketPing(): void {
940 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
941 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
943 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
944 this.webSocketPingSetInterval
= setInterval(() => {
945 if (this.isWebSocketConnectionOpened()) {
946 this.wsConnection
.ping((): void => { /* This is intentional */ });
948 }, webSocketPingInterval
* 1000);
949 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
950 } else if (this.webSocketPingSetInterval
) {
951 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
953 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
957 private stopWebSocketPing(): void {
958 if (this.webSocketPingSetInterval
) {
959 clearInterval(this.webSocketPingSetInterval
);
963 private warnDeprecatedTemplateKey(template
: ChargingStationTemplate
, key
: string, chargingStationId
: string, logMsgToAppend
= ''): void {
964 if (!Utils
.isUndefined(template
[key
])) {
965 logger
.warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key
'${key}' usage
in file
'${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}
`);
969 private convertDeprecatedTemplateKey(template: ChargingStationTemplate, deprecatedKey: string, key: string): void {
970 if (!Utils.isUndefined(template[deprecatedKey])) {
971 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
972 template[key] = template[deprecatedKey];
973 delete template[deprecatedKey];
977 private getConfiguredSupervisionUrl(): URL {
978 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls());
979 if (!Utils.isEmptyArray(supervisionUrls)) {
981 switch (Configuration.getSupervisionUrlDistribution()) {
982 case SupervisionUrlDistribution.ROUND_ROBIN:
983 urlIndex = (this.index - 1) % supervisionUrls.length;
985 case SupervisionUrlDistribution.RANDOM:
987 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
989 case SupervisionUrlDistribution.SEQUENTIAL:
990 if (this.index <= supervisionUrls.length) {
991 urlIndex = this.index - 1;
993 logger.warn(`${this.logPrefix()} No more configured supervision urls available
, using the first one
`);
997 logger.error(`${this.logPrefix()} Unknown supervision url distribution
'${Configuration.getSupervisionUrlDistribution()}' from values
'${SupervisionUrlDistribution.toString()}', defaulting to ${SupervisionUrlDistribution.ROUND_ROBIN}
`);
998 urlIndex = (this.index - 1) % supervisionUrls.length;
1001 return new URL(supervisionUrls[urlIndex]);
1003 return new URL(supervisionUrls as string);
1006 private getHeartbeatInterval(): number | undefined {
1007 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1008 if (HeartbeatInterval) {
1009 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1011 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1012 if (HeartBeatInterval) {
1013 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1015 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set
, using
default value
: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}
`);
1016 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1019 private stopHeartbeat(): void {
1020 if (this.heartbeatSetInterval) {
1021 clearInterval(this.heartbeatSetInterval);
1025 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
1026 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1027 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
1028 options.auth = `${this.stationInfo.supervisionUser}
:${this.stationInfo.supervisionPassword}
`;
1030 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1031 this.wsConnection.close();
1033 let protocol: string;
1034 switch (this.getOcppVersion()) {
1035 case OCPPVersion.VERSION_16:
1036 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1039 this.handleUnsupportedVersion(this.getOcppVersion());
1042 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1043 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
1046 private stopMeterValues(connectorId: number) {
1047 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1048 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1052 private startAuthorizationFileMonitoring(): void {
1053 const authorizationFile = this.getAuthorizationFile();
1054 if (authorizationFile) {
1056 fs.watch(authorizationFile, (event, filename) => {
1057 if (filename && event === 'change') {
1059 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1060 // Initialize authorizedTags
1061 this.authorizedTags = this.getAuthorizedTags();
1063 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1068 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1071 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1075 private startStationTemplateFileMonitoring(): void {
1077 fs.watch(this.stationTemplateFile, (event, filename): void => {
1078 if (filename && event === 'change') {
1080 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1084 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1085 this.automaticTransactionGenerator) {
1086 this.automaticTransactionGenerator.stop();
1088 this.startAutomaticTransactionGenerator();
1089 if (this.getEnableStatistics()) {
1090 this.performanceStatistics.restart();
1092 this.performanceStatistics.stop();
1094 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1096 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1101 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1105 private getReconnectExponentialDelay(): boolean | undefined {
1106 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1109 private async reconnect(code: number): Promise<void> {
1110 // Stop WebSocket ping
1111 this.stopWebSocketPing();
1113 this.stopHeartbeat();
1114 // Stop the ATG if needed
1115 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1116 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1117 this.automaticTransactionGenerator &&
1118 this.automaticTransactionGenerator.started) {
1119 this.automaticTransactionGenerator.stop();
1121 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1122 this.autoReconnectRetryCount++;
1123 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1124 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
1125 logger.error(`${this.logPrefix()} WebSocket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectTimeout}ms
`);
1126 await Utils.sleep(reconnectDelay);
1127 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1128 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
1129 this.wsConnectionRestarted = true;
1130 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1131 logger.error(`${this.logPrefix()} WebSocket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1135 private initializeConnectorStatus(connectorId: number): void {
1136 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1137 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1138 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1139 this.getConnectorStatus(connectorId).transactionStarted = false;
1140 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1141 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;