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 stationTemplateFile
: string;
46 public authorizedTags
: string[];
47 public stationInfo
!: ChargingStationInfo
;
48 public readonly connectors
: Map
<number, ConnectorStatus
>;
49 public configuration
!: ChargingStationConfiguration
;
50 public wsConnection
!: WebSocket
;
51 public readonly requests
: Map
<string, CachedRequest
>;
52 public performanceStatistics
!: PerformanceStatistics
;
53 public heartbeatSetInterval
!: NodeJS
.Timeout
;
54 public ocppRequestService
!: OCPPRequestService
;
55 private readonly index
: number;
56 private bootNotificationRequest
!: BootNotificationRequest
;
57 private bootNotificationResponse
!: BootNotificationResponse
| null;
58 private connectorsConfigurationHash
!: string;
59 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
60 private readonly messageBuffer
: Set
<string>;
61 private wsConfiguredConnectionUrl
!: URL
;
62 private wsConnectionRestarted
: boolean;
63 private stopped
: boolean;
64 private autoReconnectRetryCount
: number;
65 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
66 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
68 constructor(index
: number, stationTemplateFile
: string) {
70 this.stationTemplateFile
= stationTemplateFile
;
71 this.connectors
= new Map
<number, ConnectorStatus
>();
75 this.wsConnectionRestarted
= false;
76 this.autoReconnectRetryCount
= 0;
78 this.requests
= new Map
<string, CachedRequest
>();
79 this.messageBuffer
= new Set
<string>();
81 this.authorizedTags
= this.getAuthorizedTags();
84 get
wsConnectionUrl(): URL
{
85 return this.getSupervisionUrlOcppConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
).value
+ '/' + this.stationInfo
.chargingStationId
) : this.wsConfiguredConnectionUrl
;
88 public logPrefix(): string {
89 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
92 public getBootNotificationRequest(): BootNotificationRequest
{
93 return this.bootNotificationRequest
;
96 public getRandomIdTag(): string {
97 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
98 return this.authorizedTags
[index
];
101 public hasAuthorizedTags(): boolean {
102 return !Utils
.isEmptyArray(this.authorizedTags
);
105 public getEnableStatistics(): boolean | undefined {
106 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
109 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
110 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
113 public getNumberOfPhases(): number | undefined {
114 switch (this.getCurrentOutType()) {
116 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
122 public isWebSocketConnectionOpened(): boolean {
123 return this?.wsConnection
?.readyState
=== OPEN
;
126 public getRegistrationStatus(): RegistrationStatus
{
127 return this?.bootNotificationResponse
?.status;
130 public isInUnknownState(): boolean {
131 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
134 public isInPendingState(): boolean {
135 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
138 public isInAcceptedState(): boolean {
139 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
142 public isInRejectedState(): boolean {
143 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
146 public isRegistered(): boolean {
147 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
150 public isChargingStationAvailable(): boolean {
151 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
154 public isConnectorAvailable(id
: number): boolean {
155 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
158 public getNumberOfConnectors(): number {
159 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
162 public getConnectorStatus(id
: number): ConnectorStatus
{
163 return this.connectors
.get(id
);
166 public getCurrentOutType(): CurrentType
| undefined {
167 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
170 public getOcppStrictCompliance(): boolean {
171 return this.stationInfo
.ocppStrictCompliance
?? false;
174 public getVoltageOut(): number | undefined {
175 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
176 let defaultVoltageOut
: number;
177 switch (this.getCurrentOutType()) {
179 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
182 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
185 logger
.error(errMsg
);
186 throw new Error(errMsg
);
188 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
191 public getTransactionIdTag(transactionId
: number): string | undefined {
192 for (const connectorId
of this.connectors
.keys()) {
193 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
194 return this.getConnectorStatus(connectorId
).transactionIdTag
;
199 public getOutOfOrderEndMeterValues(): boolean {
200 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
203 public getBeginEndMeterValues(): boolean {
204 return this.stationInfo
.beginEndMeterValues
?? false;
207 public getMeteringPerTransaction(): boolean {
208 return this.stationInfo
.meteringPerTransaction
?? true;
211 public getTransactionDataMeterValues(): boolean {
212 return this.stationInfo
.transactionDataMeterValues
?? false;
215 public getMainVoltageMeterValues(): boolean {
216 return this.stationInfo
.mainVoltageMeterValues
?? true;
219 public getPhaseLineToLineVoltageMeterValues(): boolean {
220 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
223 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
224 if (this.getMeteringPerTransaction()) {
225 for (const connectorId
of this.connectors
.keys()) {
226 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
227 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
231 for (const connectorId
of this.connectors
.keys()) {
232 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
233 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
238 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
239 if (this.getMeteringPerTransaction()) {
240 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
242 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
245 public getAuthorizeRemoteTxRequests(): boolean {
246 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
247 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
250 public getLocalAuthListEnabled(): boolean {
251 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
252 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
255 public restartWebSocketPing(): void {
256 // Stop WebSocket ping
257 this.stopWebSocketPing();
258 // Start WebSocket ping
259 this.startWebSocketPing();
262 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
263 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
264 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
265 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
268 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
269 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`);
272 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
273 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
274 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
275 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
276 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
277 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
278 return sampledValueTemplates[index];
279 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
280 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
281 return sampledValueTemplates[index];
282 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
283 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
284 return sampledValueTemplates[index];
287 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
288 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
289 logger.error(errorMsg);
290 throw new Error(errorMsg);
292 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
295 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
296 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
299 public startHeartbeat(): void {
300 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
301 // eslint-disable-next-line @typescript-eslint/no-misused-promises
302 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
303 await this.ocppRequestService
.sendHeartbeat();
304 }, this.getHeartbeatInterval());
305 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
306 } else if (this.heartbeatSetInterval
) {
307 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
309 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
313 public restartHeartbeat(): void {
315 this.stopHeartbeat();
317 this.startHeartbeat();
320 public startMeterValues(connectorId
: number, interval
: number): void {
321 if (connectorId
=== 0) {
322 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
325 if (!this.getConnectorStatus(connectorId
)) {
326 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
329 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
330 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
332 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
333 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
337 // eslint-disable-next-line @typescript-eslint/no-misused-promises
338 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
339 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
342 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
346 public start(): void {
347 if (this.getEnableStatistics()) {
348 this.performanceStatistics
.start();
350 this.openWSConnection();
351 // Monitor authorization file
352 this.startAuthorizationFileMonitoring();
353 // Monitor station template file
354 this.startStationTemplateFileMonitoring();
355 // Handle WebSocket message
356 this.wsConnection
.on('message', this.onMessage
.bind(this));
357 // Handle WebSocket error
358 this.wsConnection
.on('error', this.onError
.bind(this));
359 // Handle WebSocket close
360 this.wsConnection
.on('close', this.onClose
.bind(this));
361 // Handle WebSocket open
362 this.wsConnection
.on('open', this.onOpen
.bind(this));
363 // Handle WebSocket ping
364 this.wsConnection
.on('ping', this.onPing
.bind(this));
365 // Handle WebSocket pong
366 this.wsConnection
.on('pong', this.onPong
.bind(this));
367 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
370 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
371 // Stop message sequence
372 await this.stopMessageSequence(reason
);
373 for (const connectorId
of this.connectors
.keys()) {
374 if (connectorId
> 0) {
375 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
376 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
379 if (this.isWebSocketConnectionOpened()) {
380 this.wsConnection
.close();
382 if (this.getEnableStatistics()) {
383 this.performanceStatistics
.stop();
385 this.bootNotificationResponse
= null;
386 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
390 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
391 return this.configuration
.configurationKey
.find((configElement
) => {
392 if (caseInsensitive
) {
393 return configElement
.key
.toLowerCase() === key
.toLowerCase();
395 return configElement
.key
=== key
;
399 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
400 const keyFound
= this.getConfigurationKey(key
);
401 const readonly = options
.readonly;
402 const visible
= options
.visible
;
403 const reboot
= options
.reboot
;
405 this.configuration
.configurationKey
.push({
413 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
417 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
418 const keyFound
= this.getConfigurationKey(key
);
420 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
421 this.configuration
.configurationKey
[keyIndex
].value
= value
;
423 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
427 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
428 let cpReplaced
= false;
429 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
430 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
431 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
432 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
433 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
438 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
441 public resetConnectorStatus(connectorId
: number): void {
442 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
443 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
444 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
445 this.getConnectorStatus(connectorId
).transactionStarted
= false;
446 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
447 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
448 delete this.getConnectorStatus(connectorId
).transactionId
;
449 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
450 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
451 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
452 this.stopMeterValues(connectorId
);
455 public bufferMessage(message
: string): void {
456 this.messageBuffer
.add(message
);
459 private flushMessageBuffer() {
460 if (this.messageBuffer
.size
> 0) {
461 this.messageBuffer
.forEach((message
) => {
462 // TODO: evaluate the need to track performance
463 this.wsConnection
.send(message
);
464 this.messageBuffer
.delete(message
);
469 private getSupervisionUrlOcppConfiguration(): boolean {
470 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
473 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
474 // In case of multiple instances: add instance index to charging station id
475 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
476 const idSuffix
= stationTemplate
.nameSuffix
?? '';
477 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
480 private buildStationInfo(): ChargingStationInfo
{
481 let stationTemplateFromFile
: ChargingStationTemplate
;
483 // Load template file
484 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
485 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
486 fs
.closeSync(fileDescriptor
);
488 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
490 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
491 // Deprecation template keys section
492 this.warnDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', chargingStationId
, 'Use \'supervisionUrls\' instead');
493 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
494 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
495 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
496 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
497 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
498 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
499 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
500 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
501 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
503 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
504 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
505 ? stationTemplateFromFile
.power
* 1000
506 : stationTemplateFromFile
.power
;
508 delete stationInfo
.power
;
509 delete stationInfo
.powerUnit
;
510 stationInfo
.chargingStationId
= chargingStationId
;
511 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
515 private getOcppVersion(): OCPPVersion
{
516 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
519 private handleUnsupportedVersion(version
: OCPPVersion
) {
520 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
521 logger
.error(errMsg
);
522 throw new Error(errMsg
);
525 private initialize(): void {
526 this.stationInfo
= this.buildStationInfo();
527 this.configuration
= this.getTemplateChargingStationConfiguration();
528 delete this.stationInfo
.Configuration
;
529 this.bootNotificationRequest
= {
530 chargePointModel
: this.stationInfo
.chargePointModel
,
531 chargePointVendor
: this.stationInfo
.chargePointVendor
,
532 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
533 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
535 // Build connectors if needed
536 const maxConnectors
= this.getMaxNumberOfConnectors();
537 if (maxConnectors
<= 0) {
538 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
540 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
541 if (templateMaxConnectors
<= 0) {
542 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
544 if (!this.stationInfo
.Connectors
[0]) {
545 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
548 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
549 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
550 this.stationInfo
.randomConnectors
= true;
552 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
553 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
554 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
555 connectorsConfigChanged
&& (this.connectors
.clear());
556 this.connectorsConfigurationHash
= connectorsConfigHash
;
557 // Add connector Id 0
558 let lastConnector
= '0';
559 for (lastConnector
in this.stationInfo
.Connectors
) {
560 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
561 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
562 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
563 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
564 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
565 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
569 // Generate all connectors
570 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
571 for (let index
= 1; index
<= maxConnectors
; index
++) {
572 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
573 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
574 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
575 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
576 this.getConnectorStatus(index
).chargingProfiles
= [];
581 // Avoid duplication of connectors related information
582 delete this.stationInfo
.Connectors
;
583 // Initialize transaction attributes on connectors
584 for (const connectorId
of this.connectors
.keys()) {
585 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
586 this.initializeConnectorStatus(connectorId
);
589 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
);
590 switch (this.getOcppVersion()) {
591 case OCPPVersion
.VERSION_16
:
592 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
593 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
596 this.handleUnsupportedVersion(this.getOcppVersion());
600 this.initOcppParameters();
601 if (this.stationInfo
.autoRegister
) {
602 this.bootNotificationResponse
= {
603 currentTime
: new Date().toISOString(),
604 interval
: this.getHeartbeatInterval() / 1000,
605 status: RegistrationStatus
.ACCEPTED
608 this.stationInfo
.powerDivider
= this.getPowerDivider();
609 if (this.getEnableStatistics()) {
610 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
614 private initOcppParameters(): void {
615 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
616 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionUrl().href
, { reboot
: true });
618 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
619 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
621 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
622 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
623 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
625 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
626 const connectorPhaseRotation
= [];
627 for (const connectorId
of this.connectors
.keys()) {
629 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
630 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
631 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
632 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
634 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
635 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
636 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
637 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
640 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
642 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
643 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
645 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
646 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
647 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
649 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
650 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
654 private async onOpen(): Promise
<void> {
655 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
656 if (!this.isInAcceptedState()) {
657 // Send BootNotification
658 let registrationRetryCount
= 0;
660 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
661 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
662 if (!this.isInAcceptedState()) {
663 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
664 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
666 } while (!this.isInAcceptedState() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
668 if (this.isInAcceptedState()) {
669 await this.startMessageSequence();
670 this.stopped
&& (this.stopped
= false);
671 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
672 this.flushMessageBuffer();
675 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
677 this.autoReconnectRetryCount
= 0;
678 this.wsConnectionRestarted
= false;
681 private async onClose(code
: number, reason
: string): Promise
<void> {
684 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
685 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
686 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
687 this.autoReconnectRetryCount
= 0;
691 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
692 await this.reconnect(code
);
697 private async onMessage(data
: Data
): Promise
<void> {
698 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
699 let responseCallback
: (payload
: JsonType
| string, requestPayload
: JsonType
| OCPPError
) => void;
700 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
701 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
702 let requestPayload
: JsonType
| OCPPError
;
703 let cachedRequest
: CachedRequest
;
706 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
707 if (Utils
.isIterable(request
)) {
709 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
711 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
713 // Check the Type of message
714 switch (messageType
) {
716 case MessageType
.CALL_MESSAGE
:
717 if (this.getEnableStatistics()) {
718 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
721 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
724 case MessageType
.CALL_RESULT_MESSAGE
:
726 cachedRequest
= this.requests
.get(messageId
);
727 if (Utils
.isIterable(cachedRequest
)) {
728 [responseCallback
, , , requestPayload
] = cachedRequest
;
730 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
732 if (!responseCallback
) {
734 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
736 responseCallback(commandName
, requestPayload
);
739 case MessageType
.CALL_ERROR_MESSAGE
:
740 cachedRequest
= this.requests
.get(messageId
);
741 if (Utils
.isIterable(cachedRequest
)) {
742 [, rejectCallback
, requestCommandName
] = cachedRequest
;
744 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
746 if (!rejectCallback
) {
748 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
750 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
754 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
755 logger
.error(errMsg
);
756 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
760 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
762 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
766 private onPing(): void {
767 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
770 private onPong(): void {
771 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
774 private async onError(error
: WSError
): Promise
<void> {
775 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
776 // switch (error.code) {
777 // case 'ECONNREFUSED':
778 // await this.reconnect(error);
783 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
784 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
787 private getAuthorizationFile(): string | undefined {
788 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
791 private getAuthorizedTags(): string[] {
792 let authorizedTags
: string[] = [];
793 const authorizationFile
= this.getAuthorizationFile();
794 if (authorizationFile
) {
796 // Load authorization file
797 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
798 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
799 fs
.closeSync(fileDescriptor
);
801 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
804 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
806 return authorizedTags
;
809 private getUseConnectorId0(): boolean | undefined {
810 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
813 private getNumberOfRunningTransactions(): number {
815 for (const connectorId
of this.connectors
.keys()) {
816 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
824 private getConnectionTimeout(): number | undefined {
825 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
826 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
828 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
831 // -1 for unlimited, 0 for disabling
832 private getAutoReconnectMaxRetries(): number | undefined {
833 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
834 return this.stationInfo
.autoReconnectMaxRetries
;
836 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
837 return Configuration
.getAutoReconnectMaxRetries();
843 private getRegistrationMaxRetries(): number | undefined {
844 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
845 return this.stationInfo
.registrationMaxRetries
;
850 private getPowerDivider(): number {
851 let powerDivider
= this.getNumberOfConnectors();
852 if (this.stationInfo
.powerSharedByConnectors
) {
853 powerDivider
= this.getNumberOfRunningTransactions();
858 private getTemplateMaxNumberOfConnectors(): number {
859 return Object.keys(this.stationInfo
.Connectors
).length
;
862 private getMaxNumberOfConnectors(): number {
863 let maxConnectors
: number;
864 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
865 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
866 // Distribute evenly the number of connectors
867 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
868 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
869 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
871 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
873 return maxConnectors
;
876 private async startMessageSequence(): Promise
<void> {
877 if (this.stationInfo
.autoRegister
) {
878 await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
879 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
881 // Start WebSocket ping
882 this.startWebSocketPing();
884 this.startHeartbeat();
885 // Initialize connectors status
886 for (const connectorId
of this.connectors
.keys()) {
887 if (connectorId
=== 0) {
889 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
890 // Send status in template at startup
891 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
892 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
893 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
894 // Send status in template after reset
895 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
896 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
897 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
898 // Send previous status at template reload
899 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
901 // Send default status
902 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
903 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
907 this.startAutomaticTransactionGenerator();
910 private startAutomaticTransactionGenerator() {
911 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
912 if (!this.automaticTransactionGenerator
) {
913 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
915 if (!this.automaticTransactionGenerator
.started
) {
916 this.automaticTransactionGenerator
.start();
921 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
922 // Stop WebSocket ping
923 this.stopWebSocketPing();
925 this.stopHeartbeat();
927 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
928 this.automaticTransactionGenerator
&&
929 this.automaticTransactionGenerator
.started
) {
930 this.automaticTransactionGenerator
.stop();
932 for (const connectorId
of this.connectors
.keys()) {
933 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
934 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
935 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
936 this.getTransactionIdTag(transactionId
), reason
);
942 private startWebSocketPing(): void {
943 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
944 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
946 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
947 this.webSocketPingSetInterval
= setInterval(() => {
948 if (this.isWebSocketConnectionOpened()) {
949 this.wsConnection
.ping((): void => { /* This is intentional */ });
951 }, webSocketPingInterval
* 1000);
952 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
953 } else if (this.webSocketPingSetInterval
) {
954 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
956 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
960 private stopWebSocketPing(): void {
961 if (this.webSocketPingSetInterval
) {
962 clearInterval(this.webSocketPingSetInterval
);
966 private warnDeprecatedTemplateKey(template
: ChargingStationTemplate
, key
: string, chargingStationId
: string, logMsgToAppend
= ''): void {
967 if (!Utils
.isUndefined(template
[key
])) {
968 logger
.warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key
'${key}' usage
in file
'${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}
`);
972 private convertDeprecatedTemplateKey(template: ChargingStationTemplate, deprecatedKey: string, key: string): void {
973 if (!Utils.isUndefined(template[deprecatedKey])) {
974 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
975 template[key] = template[deprecatedKey];
976 delete template[deprecatedKey];
980 private getConfiguredSupervisionUrl(): URL {
981 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls());
982 if (!Utils.isEmptyArray(supervisionUrls)) {
984 switch (Configuration.getSupervisionUrlDistribution()) {
985 case SupervisionUrlDistribution.ROUND_ROBIN:
986 urlIndex = (this.index - 1) % supervisionUrls.length;
988 case SupervisionUrlDistribution.RANDOM:
990 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
992 case SupervisionUrlDistribution.SEQUENTIAL:
993 if (this.index <= supervisionUrls.length) {
994 urlIndex = this.index - 1;
996 logger.warn(`${this.logPrefix()} No more configured supervision urls available
, using the first one
`);
1000 logger.error(`${this.logPrefix()} Unknown supervision url distribution
'${Configuration.getSupervisionUrlDistribution()}' from values
'${SupervisionUrlDistribution.toString()}', defaulting to ${SupervisionUrlDistribution.ROUND_ROBIN}
`);
1001 urlIndex = (this.index - 1) % supervisionUrls.length;
1004 return new URL(supervisionUrls[urlIndex]);
1006 return new URL(supervisionUrls as string);
1009 private getHeartbeatInterval(): number | undefined {
1010 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1011 if (HeartbeatInterval) {
1012 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1014 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1015 if (HeartBeatInterval) {
1016 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1018 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set
, using
default value
: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}
`);
1019 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1022 private stopHeartbeat(): void {
1023 if (this.heartbeatSetInterval) {
1024 clearInterval(this.heartbeatSetInterval);
1028 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
1029 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1030 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
1031 options.auth = `${this.stationInfo.supervisionUser}
:${this.stationInfo.supervisionPassword}
`;
1033 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1034 this.wsConnection.close();
1036 let protocol: string;
1037 switch (this.getOcppVersion()) {
1038 case OCPPVersion.VERSION_16:
1039 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1042 this.handleUnsupportedVersion(this.getOcppVersion());
1045 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1046 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
1049 private stopMeterValues(connectorId: number) {
1050 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1051 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1055 private startAuthorizationFileMonitoring(): void {
1056 const authorizationFile = this.getAuthorizationFile();
1057 if (authorizationFile) {
1059 fs.watch(authorizationFile, (event, filename) => {
1060 if (filename && event === 'change') {
1062 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1063 // Initialize authorizedTags
1064 this.authorizedTags = this.getAuthorizedTags();
1066 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1071 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1074 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1078 private startStationTemplateFileMonitoring(): void {
1080 fs.watch(this.stationTemplateFile, (event, filename): void => {
1081 if (filename && event === 'change') {
1083 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1087 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1088 this.automaticTransactionGenerator) {
1089 this.automaticTransactionGenerator.stop();
1091 this.startAutomaticTransactionGenerator();
1092 if (this.getEnableStatistics()) {
1093 this.performanceStatistics.restart();
1095 this.performanceStatistics.stop();
1097 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1099 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1104 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1108 private getReconnectExponentialDelay(): boolean | undefined {
1109 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1112 private async reconnect(code: number): Promise<void> {
1113 // Stop WebSocket ping
1114 this.stopWebSocketPing();
1116 this.stopHeartbeat();
1117 // Stop the ATG if needed
1118 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1119 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1120 this.automaticTransactionGenerator &&
1121 this.automaticTransactionGenerator.started) {
1122 this.automaticTransactionGenerator.stop();
1124 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1125 this.autoReconnectRetryCount++;
1126 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1127 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
1128 logger.error(`${this.logPrefix()} WebSocket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectTimeout}ms
`);
1129 await Utils.sleep(reconnectDelay);
1130 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1131 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
1132 this.wsConnectionRestarted = true;
1133 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1134 logger.error(`${this.logPrefix()} WebSocket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1138 private initializeConnectorStatus(connectorId: number): void {
1139 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1140 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1141 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1142 this.getConnectorStatus(connectorId).transactionStarted = false;
1143 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1144 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;