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 { JsonType
} from
'../types/JsonType';
24 import { MessageType
} from
'../types/ocpp/MessageType';
25 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
26 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
27 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
28 import OCPPError from
'../exception/OCPPError';
29 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
30 import OCPPRequestService from
'./ocpp/OCPPRequestService';
31 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
32 import PerformanceStatistics from
'../performance/PerformanceStatistics';
33 import { SampledValueTemplate
} from
'../types/MeasurandPerPhaseSampledValueTemplates';
34 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
35 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
36 import { URL
} from
'url';
37 import Utils from
'../utils/Utils';
38 import crypto from
'crypto';
40 import logger from
'../utils/Logger';
41 import { parentPort
} from
'worker_threads';
42 import path from
'path';
44 export default class ChargingStation
{
45 public readonly id
: string;
46 public readonly stationTemplateFile
: string;
47 public authorizedTags
: string[];
48 public stationInfo
!: ChargingStationInfo
;
49 public readonly connectors
: Map
<number, ConnectorStatus
>;
50 public configuration
!: ChargingStationConfiguration
;
51 public wsConnection
!: WebSocket
;
52 public readonly requests
: Map
<string, CachedRequest
>;
53 public performanceStatistics
!: PerformanceStatistics
;
54 public heartbeatSetInterval
!: NodeJS
.Timeout
;
55 public ocppRequestService
!: OCPPRequestService
;
56 private readonly index
: number;
57 private bootNotificationRequest
!: BootNotificationRequest
;
58 private bootNotificationResponse
!: BootNotificationResponse
| null;
59 private connectorsConfigurationHash
!: string;
60 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
61 private readonly messageBuffer
: Set
<string>;
62 private wsConfiguredConnectionUrl
!: URL
;
63 private wsConnectionRestarted
: boolean;
64 private stopped
: boolean;
65 private autoReconnectRetryCount
: number;
66 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
67 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
69 constructor(index
: number, stationTemplateFile
: string) {
70 this.id
= Utils
.generateUUID();
72 this.stationTemplateFile
= stationTemplateFile
;
74 this.wsConnectionRestarted
= false;
75 this.autoReconnectRetryCount
= 0;
76 this.connectors
= new Map
<number, ConnectorStatus
>();
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 getRegistrationStatus(): RegistrationStatus
{
126 return this?.bootNotificationResponse
?.status;
129 public isInUnknownState(): boolean {
130 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
133 public isInPendingState(): boolean {
134 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
137 public isInAcceptedState(): boolean {
138 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
141 public isInRejectedState(): boolean {
142 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
145 public isRegistered(): boolean {
146 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
149 public isChargingStationAvailable(): boolean {
150 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
153 public isConnectorAvailable(id
: number): boolean {
154 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
157 public getNumberOfConnectors(): number {
158 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
161 public getConnectorStatus(id
: number): ConnectorStatus
{
162 return this.connectors
.get(id
);
165 public getCurrentOutType(): CurrentType
| undefined {
166 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
169 public getOcppStrictCompliance(): boolean {
170 return this.stationInfo
.ocppStrictCompliance
?? false;
173 public getVoltageOut(): number | undefined {
174 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
175 let defaultVoltageOut
: number;
176 switch (this.getCurrentOutType()) {
178 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
181 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
184 logger
.error(errMsg
);
185 throw new Error(errMsg
);
187 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
190 public getTransactionIdTag(transactionId
: number): string | undefined {
191 for (const connectorId
of this.connectors
.keys()) {
192 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
193 return this.getConnectorStatus(connectorId
).transactionIdTag
;
198 public getOutOfOrderEndMeterValues(): boolean {
199 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
202 public getBeginEndMeterValues(): boolean {
203 return this.stationInfo
.beginEndMeterValues
?? false;
206 public getMeteringPerTransaction(): boolean {
207 return this.stationInfo
.meteringPerTransaction
?? true;
210 public getTransactionDataMeterValues(): boolean {
211 return this.stationInfo
.transactionDataMeterValues
?? false;
214 public getMainVoltageMeterValues(): boolean {
215 return this.stationInfo
.mainVoltageMeterValues
?? true;
218 public getPhaseLineToLineVoltageMeterValues(): boolean {
219 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
222 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
223 if (this.getMeteringPerTransaction()) {
224 for (const connectorId
of this.connectors
.keys()) {
225 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
226 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
230 for (const connectorId
of this.connectors
.keys()) {
231 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
232 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
237 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
238 if (this.getMeteringPerTransaction()) {
239 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
241 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
244 public getAuthorizeRemoteTxRequests(): boolean {
245 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
246 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
249 public getLocalAuthListEnabled(): boolean {
250 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
251 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
254 public restartWebSocketPing(): void {
255 // Stop WebSocket ping
256 this.stopWebSocketPing();
257 // Start WebSocket ping
258 this.startWebSocketPing();
261 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
262 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
263 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
264 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
267 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
268 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`);
271 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
272 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
273 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
274 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
275 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
276 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
277 return sampledValueTemplates[index];
278 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
279 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
280 return sampledValueTemplates[index];
281 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
282 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
283 return sampledValueTemplates[index];
286 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
287 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
288 logger.error(errorMsg);
289 throw new Error(errorMsg);
291 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
294 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
295 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
298 public startHeartbeat(): void {
299 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
300 // eslint-disable-next-line @typescript-eslint/no-misused-promises
301 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
302 await this.ocppRequestService
.sendHeartbeat();
303 }, this.getHeartbeatInterval());
304 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
305 } else if (this.heartbeatSetInterval
) {
306 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
308 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
312 public restartHeartbeat(): void {
314 this.stopHeartbeat();
316 this.startHeartbeat();
319 public startMeterValues(connectorId
: number, interval
: number): void {
320 if (connectorId
=== 0) {
321 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
324 if (!this.getConnectorStatus(connectorId
)) {
325 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
328 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
329 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
331 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
332 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
336 // eslint-disable-next-line @typescript-eslint/no-misused-promises
337 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
338 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
341 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
345 public start(): void {
346 if (this.getEnableStatistics()) {
347 this.performanceStatistics
.start();
349 this.openWSConnection();
350 // Monitor authorization file
351 this.startAuthorizationFileMonitoring();
352 // Monitor station template file
353 this.startStationTemplateFileMonitoring();
354 // Handle WebSocket message
355 this.wsConnection
.on('message', this.onMessage
.bind(this));
356 // Handle WebSocket error
357 this.wsConnection
.on('error', this.onError
.bind(this));
358 // Handle WebSocket close
359 this.wsConnection
.on('close', this.onClose
.bind(this));
360 // Handle WebSocket open
361 this.wsConnection
.on('open', this.onOpen
.bind(this));
362 // Handle WebSocket ping
363 this.wsConnection
.on('ping', this.onPing
.bind(this));
364 // Handle WebSocket pong
365 this.wsConnection
.on('pong', this.onPong
.bind(this));
366 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
369 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
370 // Stop message sequence
371 await this.stopMessageSequence(reason
);
372 for (const connectorId
of this.connectors
.keys()) {
373 if (connectorId
> 0) {
374 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
375 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
378 if (this.isWebSocketConnectionOpened()) {
379 this.wsConnection
.close();
381 if (this.getEnableStatistics()) {
382 this.performanceStatistics
.stop();
384 this.bootNotificationResponse
= null;
385 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
389 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
390 return this.configuration
.configurationKey
.find((configElement
) => {
391 if (caseInsensitive
) {
392 return configElement
.key
.toLowerCase() === key
.toLowerCase();
394 return configElement
.key
=== key
;
398 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
399 const keyFound
= this.getConfigurationKey(key
);
400 const readonly = options
.readonly;
401 const visible
= options
.visible
;
402 const reboot
= options
.reboot
;
404 this.configuration
.configurationKey
.push({
412 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
416 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
417 const keyFound
= this.getConfigurationKey(key
);
419 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
420 this.configuration
.configurationKey
[keyIndex
].value
= value
;
422 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
426 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
427 let cpReplaced
= false;
428 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
429 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
430 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
431 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
432 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
437 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
440 public resetConnectorStatus(connectorId
: number): void {
441 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
442 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
443 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
444 this.getConnectorStatus(connectorId
).transactionStarted
= false;
445 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
446 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
447 delete this.getConnectorStatus(connectorId
).transactionId
;
448 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
449 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
450 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
451 this.stopMeterValues(connectorId
);
454 public bufferMessage(message
: string): void {
455 this.messageBuffer
.add(message
);
458 private flushMessageBuffer() {
459 if (this.messageBuffer
.size
> 0) {
460 this.messageBuffer
.forEach((message
) => {
461 // TODO: evaluate the need to track performance
462 this.wsConnection
.send(message
);
463 this.messageBuffer
.delete(message
);
468 private getSupervisionUrlOcppConfiguration(): boolean {
469 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
472 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
473 // In case of multiple instances: add instance index to charging station id
474 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
475 const idSuffix
= stationTemplate
.nameSuffix
?? '';
476 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
479 private buildStationInfo(): ChargingStationInfo
{
480 let stationTemplateFromFile
: ChargingStationTemplate
;
482 // Load template file
483 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
484 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
485 fs
.closeSync(fileDescriptor
);
487 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
489 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
490 // Deprecation template keys section
491 this.warnDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', chargingStationId
, 'Use \'supervisionUrls\' instead');
492 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
493 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
494 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
495 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
496 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
497 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
498 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
499 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
500 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
502 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
503 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
504 ? stationTemplateFromFile
.power
* 1000
505 : stationTemplateFromFile
.power
;
507 delete stationInfo
.power
;
508 delete stationInfo
.powerUnit
;
509 stationInfo
.chargingStationId
= chargingStationId
;
510 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
514 private getOcppVersion(): OCPPVersion
{
515 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
518 private handleUnsupportedVersion(version
: OCPPVersion
) {
519 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
520 logger
.error(errMsg
);
521 throw new Error(errMsg
);
524 private initialize(): void {
525 this.stationInfo
= this.buildStationInfo();
526 this.configuration
= this.getTemplateChargingStationConfiguration();
527 delete this.stationInfo
.Configuration
;
528 this.bootNotificationRequest
= {
529 chargePointModel
: this.stationInfo
.chargePointModel
,
530 chargePointVendor
: this.stationInfo
.chargePointVendor
,
531 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
532 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
534 // Build connectors if needed
535 const maxConnectors
= this.getMaxNumberOfConnectors();
536 if (maxConnectors
<= 0) {
537 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
539 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
540 if (templateMaxConnectors
<= 0) {
541 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
543 if (!this.stationInfo
.Connectors
[0]) {
544 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
547 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
548 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
549 this.stationInfo
.randomConnectors
= true;
551 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
552 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
553 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
554 connectorsConfigChanged
&& (this.connectors
.clear());
555 this.connectorsConfigurationHash
= connectorsConfigHash
;
556 // Add connector Id 0
557 let lastConnector
= '0';
558 for (lastConnector
in this.stationInfo
.Connectors
) {
559 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
560 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
561 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
562 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
563 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
564 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
568 // Generate all connectors
569 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
570 for (let index
= 1; index
<= maxConnectors
; index
++) {
571 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
572 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
573 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
574 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
575 this.getConnectorStatus(index
).chargingProfiles
= [];
580 // Avoid duplication of connectors related information
581 delete this.stationInfo
.Connectors
;
582 // Initialize transaction attributes on connectors
583 for (const connectorId
of this.connectors
.keys()) {
584 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
585 this.initializeConnectorStatus(connectorId
);
588 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
);
589 switch (this.getOcppVersion()) {
590 case OCPPVersion
.VERSION_16
:
591 this.ocppIncomingRequestService
= OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>(this);
592 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(this, OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>(this));
595 this.handleUnsupportedVersion(this.getOcppVersion());
599 this.initOcppParameters();
600 if (this.stationInfo
.autoRegister
) {
601 this.bootNotificationResponse
= {
602 currentTime
: new Date().toISOString(),
603 interval
: this.getHeartbeatInterval() / 1000,
604 status: RegistrationStatus
.ACCEPTED
607 this.stationInfo
.powerDivider
= this.getPowerDivider();
608 if (this.getEnableStatistics()) {
609 this.performanceStatistics
= PerformanceStatistics
.getInstance(this.id
, this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
613 private initOcppParameters(): void {
614 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
615 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionUrl().href
, { reboot
: true });
617 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
618 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
620 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
621 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
622 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
624 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
625 const connectorPhaseRotation
= [];
626 for (const connectorId
of this.connectors
.keys()) {
628 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
629 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
630 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
631 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
633 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
634 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
635 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
636 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
639 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
641 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
642 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
644 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
645 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
646 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
648 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
649 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
653 private async onOpen(): Promise
<void> {
654 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
655 if (!this.isInAcceptedState()) {
656 // Send BootNotification
657 let registrationRetryCount
= 0;
659 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
660 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
661 if (!this.isInAcceptedState()) {
662 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
663 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
665 } while (!this.isInAcceptedState() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
667 if (this.isInAcceptedState()) {
668 await this.startMessageSequence();
669 this.stopped
&& (this.stopped
= false);
670 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
671 this.flushMessageBuffer();
674 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
676 this.autoReconnectRetryCount
= 0;
677 this.wsConnectionRestarted
= false;
680 private async onClose(code
: number, reason
: string): Promise
<void> {
683 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
684 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
685 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
686 this.autoReconnectRetryCount
= 0;
690 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
691 await this.reconnect(code
);
696 private async onMessage(data
: Data
): Promise
<void> {
697 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
698 let responseCallback
: (payload
: JsonType
| string, requestPayload
: JsonType
| OCPPError
) => void;
699 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
700 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
701 let requestPayload
: JsonType
| OCPPError
;
702 let cachedRequest
: CachedRequest
;
705 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
706 if (Utils
.isIterable(request
)) {
708 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
710 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
712 // Check the Type of message
713 switch (messageType
) {
715 case MessageType
.CALL_MESSAGE
:
716 if (this.getEnableStatistics()) {
717 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
720 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
723 case MessageType
.CALL_RESULT_MESSAGE
:
725 cachedRequest
= this.requests
.get(messageId
);
726 if (Utils
.isIterable(cachedRequest
)) {
727 [responseCallback
, , , requestPayload
] = cachedRequest
;
729 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
731 if (!responseCallback
) {
733 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
735 responseCallback(commandName
, requestPayload
);
738 case MessageType
.CALL_ERROR_MESSAGE
:
739 cachedRequest
= this.requests
.get(messageId
);
740 if (Utils
.isIterable(cachedRequest
)) {
741 [, rejectCallback
, requestCommandName
] = cachedRequest
;
743 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
745 if (!rejectCallback
) {
747 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
749 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
753 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
754 logger
.error(errMsg
);
755 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
759 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
761 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
765 private onPing(): void {
766 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
769 private onPong(): void {
770 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
773 private async onError(error
: WSError
): Promise
<void> {
774 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
775 // switch (error.code) {
776 // case 'ECONNREFUSED':
777 // await this.reconnect(error);
782 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
783 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
786 private getAuthorizationFile(): string | undefined {
787 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
790 private getAuthorizedTags(): string[] {
791 let authorizedTags
: string[] = [];
792 const authorizationFile
= this.getAuthorizationFile();
793 if (authorizationFile
) {
795 // Load authorization file
796 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
797 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
798 fs
.closeSync(fileDescriptor
);
800 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
803 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
805 return authorizedTags
;
808 private getUseConnectorId0(): boolean | undefined {
809 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
812 private getNumberOfRunningTransactions(): number {
814 for (const connectorId
of this.connectors
.keys()) {
815 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
823 private getConnectionTimeout(): number | undefined {
824 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
825 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
827 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
830 // -1 for unlimited, 0 for disabling
831 private getAutoReconnectMaxRetries(): number | undefined {
832 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
833 return this.stationInfo
.autoReconnectMaxRetries
;
835 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
836 return Configuration
.getAutoReconnectMaxRetries();
842 private getRegistrationMaxRetries(): number | undefined {
843 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
844 return this.stationInfo
.registrationMaxRetries
;
849 private getPowerDivider(): number {
850 let powerDivider
= this.getNumberOfConnectors();
851 if (this.stationInfo
.powerSharedByConnectors
) {
852 powerDivider
= this.getNumberOfRunningTransactions();
857 private getTemplateMaxNumberOfConnectors(): number {
858 return Object.keys(this.stationInfo
.Connectors
).length
;
861 private getMaxNumberOfConnectors(): number {
862 let maxConnectors
: number;
863 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
864 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
865 // Distribute evenly the number of connectors
866 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
867 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
868 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
870 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
872 return maxConnectors
;
875 private async startMessageSequence(): Promise
<void> {
876 if (this.stationInfo
.autoRegister
) {
877 await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
878 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
880 // Start WebSocket ping
881 this.startWebSocketPing();
883 this.startHeartbeat();
884 // Initialize connectors status
885 for (const connectorId
of this.connectors
.keys()) {
886 if (connectorId
=== 0) {
888 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
889 // Send status in template at startup
890 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
891 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
892 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
893 // Send status in template after reset
894 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
895 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
896 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
897 // Send previous status at template reload
898 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
900 // Send default status
901 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
902 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
906 this.startAutomaticTransactionGenerator();
909 private startAutomaticTransactionGenerator() {
910 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
911 if (!this.automaticTransactionGenerator
) {
912 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(this);
914 if (!this.automaticTransactionGenerator
.started
) {
915 this.automaticTransactionGenerator
.start();
920 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
921 // Stop WebSocket ping
922 this.stopWebSocketPing();
924 this.stopHeartbeat();
926 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
927 this.automaticTransactionGenerator
?.started
) {
928 this.automaticTransactionGenerator
.stop();
930 for (const connectorId
of this.connectors
.keys()) {
931 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
932 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
933 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
934 this.getTransactionIdTag(transactionId
), reason
);
940 private startWebSocketPing(): void {
941 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
942 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
944 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
945 this.webSocketPingSetInterval
= setInterval(() => {
946 if (this.isWebSocketConnectionOpened()) {
947 this.wsConnection
.ping((): void => { /* This is intentional */ });
949 }, webSocketPingInterval
* 1000);
950 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
951 } else if (this.webSocketPingSetInterval
) {
952 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
954 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
958 private stopWebSocketPing(): void {
959 if (this.webSocketPingSetInterval
) {
960 clearInterval(this.webSocketPingSetInterval
);
964 private warnDeprecatedTemplateKey(template
: ChargingStationTemplate
, key
: string, chargingStationId
: string, logMsgToAppend
= ''): void {
965 if (!Utils
.isUndefined(template
[key
])) {
966 logger
.warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key
'${key}' usage
in file
'${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}
`);
970 private convertDeprecatedTemplateKey(template: ChargingStationTemplate, deprecatedKey: string, key: string): void {
971 if (!Utils.isUndefined(template[deprecatedKey])) {
972 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
973 template[key] = template[deprecatedKey];
974 delete template[deprecatedKey];
978 private getConfiguredSupervisionUrl(): URL {
979 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls());
980 if (!Utils.isEmptyArray(supervisionUrls)) {
982 switch (Configuration.getSupervisionUrlDistribution()) {
983 case SupervisionUrlDistribution.ROUND_ROBIN:
984 urlIndex = (this.index - 1) % supervisionUrls.length;
986 case SupervisionUrlDistribution.RANDOM:
988 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
990 case SupervisionUrlDistribution.SEQUENTIAL:
991 if (this.index <= supervisionUrls.length) {
992 urlIndex = this.index - 1;
994 logger.warn(`${this.logPrefix()} No more configured supervision urls available
, using the first one
`);
998 logger.error(`${this.logPrefix()} Unknown supervision url distribution
'${Configuration.getSupervisionUrlDistribution()}' from values
'${SupervisionUrlDistribution.toString()}', defaulting to ${SupervisionUrlDistribution.ROUND_ROBIN}
`);
999 urlIndex = (this.index - 1) % supervisionUrls.length;
1002 return new URL(supervisionUrls[urlIndex]);
1004 return new URL(supervisionUrls as string);
1007 private getHeartbeatInterval(): number | undefined {
1008 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1009 if (HeartbeatInterval) {
1010 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1012 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1013 if (HeartBeatInterval) {
1014 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1016 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set
, using
default value
: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}
`);
1017 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1020 private stopHeartbeat(): void {
1021 if (this.heartbeatSetInterval) {
1022 clearInterval(this.heartbeatSetInterval);
1026 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
1027 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1028 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
1029 options.auth = `${this.stationInfo.supervisionUser}
:${this.stationInfo.supervisionPassword}
`;
1031 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1032 this.wsConnection.close();
1034 let protocol: string;
1035 switch (this.getOcppVersion()) {
1036 case OCPPVersion.VERSION_16:
1037 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1040 this.handleUnsupportedVersion(this.getOcppVersion());
1043 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1044 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
1047 private stopMeterValues(connectorId: number) {
1048 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1049 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1053 private startAuthorizationFileMonitoring(): void {
1054 const authorizationFile = this.getAuthorizationFile();
1055 if (authorizationFile) {
1057 fs.watch(authorizationFile, (event, filename) => {
1058 if (filename && event === 'change') {
1060 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1061 // Initialize authorizedTags
1062 this.authorizedTags = this.getAuthorizedTags();
1064 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1069 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1072 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1076 private startStationTemplateFileMonitoring(): void {
1078 fs.watch(this.stationTemplateFile, (event, filename): void => {
1079 if (filename && event === 'change') {
1081 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1085 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1086 this.automaticTransactionGenerator) {
1087 this.automaticTransactionGenerator.stop();
1089 this.startAutomaticTransactionGenerator();
1090 if (this.getEnableStatistics()) {
1091 this.performanceStatistics.restart();
1093 this.performanceStatistics.stop();
1095 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1097 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1102 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1106 private getReconnectExponentialDelay(): boolean | undefined {
1107 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1110 private async reconnect(code: number): Promise<void> {
1111 // Stop WebSocket ping
1112 this.stopWebSocketPing();
1114 this.stopHeartbeat();
1115 // Stop the ATG if needed
1116 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1117 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
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;