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 isInUnknownState(): boolean {
127 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
130 public isInPendingState(): boolean {
131 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
134 public isInAcceptedState(): boolean {
135 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
138 public isInRejectedState(): boolean {
139 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
142 public isRegistered(): boolean {
143 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
146 public isChargingStationAvailable(): boolean {
147 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
150 public isConnectorAvailable(id
: number): boolean {
151 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
154 public getNumberOfConnectors(): number {
155 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
158 public getConnectorStatus(id
: number): ConnectorStatus
{
159 return this.connectors
.get(id
);
162 public getCurrentOutType(): CurrentType
| undefined {
163 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
166 public getVoltageOut(): number | undefined {
167 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
168 let defaultVoltageOut
: number;
169 switch (this.getCurrentOutType()) {
171 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
174 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
177 logger
.error(errMsg
);
178 throw new Error(errMsg
);
180 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
183 public getTransactionIdTag(transactionId
: number): string | undefined {
184 for (const connectorId
of this.connectors
.keys()) {
185 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
186 return this.getConnectorStatus(connectorId
).transactionIdTag
;
191 public getOutOfOrderEndMeterValues(): boolean {
192 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
195 public getBeginEndMeterValues(): boolean {
196 return this.stationInfo
.beginEndMeterValues
?? false;
199 public getMeteringPerTransaction(): boolean {
200 return this.stationInfo
.meteringPerTransaction
?? true;
203 public getTransactionDataMeterValues(): boolean {
204 return this.stationInfo
.transactionDataMeterValues
?? false;
207 public getMainVoltageMeterValues(): boolean {
208 return this.stationInfo
.mainVoltageMeterValues
?? true;
211 public getPhaseLineToLineVoltageMeterValues(): boolean {
212 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
215 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
216 if (this.getMeteringPerTransaction()) {
217 for (const connectorId
of this.connectors
.keys()) {
218 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
219 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
223 for (const connectorId
of this.connectors
.keys()) {
224 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
225 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
230 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
231 if (this.getMeteringPerTransaction()) {
232 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
234 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
237 public getAuthorizeRemoteTxRequests(): boolean {
238 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
239 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
242 public getLocalAuthListEnabled(): boolean {
243 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
244 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
247 public restartWebSocketPing(): void {
248 // Stop WebSocket ping
249 this.stopWebSocketPing();
250 // Start WebSocket ping
251 this.startWebSocketPing();
254 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
255 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
256 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
257 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
260 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
261 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`);
264 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
265 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
266 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
267 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
268 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
269 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
270 return sampledValueTemplates[index];
271 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
272 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
273 return sampledValueTemplates[index];
274 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
275 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
276 return sampledValueTemplates[index];
279 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
280 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
281 logger.error(errorMsg);
282 throw new Error(errorMsg);
284 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
287 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
288 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
291 public startHeartbeat(): void {
292 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
293 // eslint-disable-next-line @typescript-eslint/no-misused-promises
294 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
295 await this.ocppRequestService
.sendHeartbeat();
296 }, this.getHeartbeatInterval());
297 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
298 } else if (this.heartbeatSetInterval
) {
299 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
301 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
305 public restartHeartbeat(): void {
307 this.stopHeartbeat();
309 this.startHeartbeat();
312 public startMeterValues(connectorId
: number, interval
: number): void {
313 if (connectorId
=== 0) {
314 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
317 if (!this.getConnectorStatus(connectorId
)) {
318 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
321 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
322 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
324 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
325 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
329 // eslint-disable-next-line @typescript-eslint/no-misused-promises
330 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
331 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
334 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
338 public start(): void {
339 if (this.getEnableStatistics()) {
340 this.performanceStatistics
.start();
342 this.openWSConnection();
343 // Monitor authorization file
344 this.startAuthorizationFileMonitoring();
345 // Monitor station template file
346 this.startStationTemplateFileMonitoring();
347 // Handle WebSocket message
348 this.wsConnection
.on('message', this.onMessage
.bind(this));
349 // Handle WebSocket error
350 this.wsConnection
.on('error', this.onError
.bind(this));
351 // Handle WebSocket close
352 this.wsConnection
.on('close', this.onClose
.bind(this));
353 // Handle WebSocket open
354 this.wsConnection
.on('open', this.onOpen
.bind(this));
355 // Handle WebSocket ping
356 this.wsConnection
.on('ping', this.onPing
.bind(this));
357 // Handle WebSocket pong
358 this.wsConnection
.on('pong', this.onPong
.bind(this));
359 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
362 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
363 // Stop message sequence
364 await this.stopMessageSequence(reason
);
365 for (const connectorId
of this.connectors
.keys()) {
366 if (connectorId
> 0) {
367 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
368 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
371 if (this.isWebSocketConnectionOpened()) {
372 this.wsConnection
.close();
374 if (this.getEnableStatistics()) {
375 this.performanceStatistics
.stop();
377 this.bootNotificationResponse
= null;
378 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
382 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
383 return this.configuration
.configurationKey
.find((configElement
) => {
384 if (caseInsensitive
) {
385 return configElement
.key
.toLowerCase() === key
.toLowerCase();
387 return configElement
.key
=== key
;
391 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
392 const keyFound
= this.getConfigurationKey(key
);
393 const readonly = options
.readonly;
394 const visible
= options
.visible
;
395 const reboot
= options
.reboot
;
397 this.configuration
.configurationKey
.push({
405 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
409 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
410 const keyFound
= this.getConfigurationKey(key
);
412 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
413 this.configuration
.configurationKey
[keyIndex
].value
= value
;
415 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
419 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
420 let cpReplaced
= false;
421 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
422 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
423 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
424 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
425 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
430 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
433 public resetConnectorStatus(connectorId
: number): void {
434 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
435 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
436 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
437 this.getConnectorStatus(connectorId
).transactionStarted
= false;
438 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
439 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
440 delete this.getConnectorStatus(connectorId
).transactionId
;
441 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
442 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
443 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
444 this.stopMeterValues(connectorId
);
447 public bufferMessage(message
: string): void {
448 this.messageBuffer
.add(message
);
451 private flushMessageBuffer() {
452 if (this.messageBuffer
.size
> 0) {
453 this.messageBuffer
.forEach((message
) => {
454 // TODO: evaluate the need to track performance
455 this.wsConnection
.send(message
);
456 this.messageBuffer
.delete(message
);
461 private getSupervisionUrlOcppConfiguration(): boolean {
462 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
465 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
466 // In case of multiple instances: add instance index to charging station id
467 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
468 const idSuffix
= stationTemplate
.nameSuffix
?? '';
469 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
472 private buildStationInfo(): ChargingStationInfo
{
473 let stationTemplateFromFile
: ChargingStationTemplate
;
475 // Load template file
476 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
477 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
478 fs
.closeSync(fileDescriptor
);
480 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
482 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
483 // Deprecation template keys section
484 this.warnDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', chargingStationId
, 'Use \'supervisionUrls\' instead');
485 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
486 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
487 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
488 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
489 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
490 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
491 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
492 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
493 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
495 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
496 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
497 ? stationTemplateFromFile
.power
* 1000
498 : stationTemplateFromFile
.power
;
500 delete stationInfo
.power
;
501 delete stationInfo
.powerUnit
;
502 stationInfo
.chargingStationId
= chargingStationId
;
503 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
507 private getOcppVersion(): OCPPVersion
{
508 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
511 private handleUnsupportedVersion(version
: OCPPVersion
) {
512 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
513 logger
.error(errMsg
);
514 throw new Error(errMsg
);
517 private initialize(): void {
518 this.stationInfo
= this.buildStationInfo();
519 this.configuration
= this.getTemplateChargingStationConfiguration();
520 delete this.stationInfo
.Configuration
;
521 this.bootNotificationRequest
= {
522 chargePointModel
: this.stationInfo
.chargePointModel
,
523 chargePointVendor
: this.stationInfo
.chargePointVendor
,
524 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
525 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
527 // Build connectors if needed
528 const maxConnectors
= this.getMaxNumberOfConnectors();
529 if (maxConnectors
<= 0) {
530 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
532 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
533 if (templateMaxConnectors
<= 0) {
534 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
536 if (!this.stationInfo
.Connectors
[0]) {
537 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
540 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
541 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
542 this.stationInfo
.randomConnectors
= true;
544 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
545 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
546 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
547 connectorsConfigChanged
&& (this.connectors
.clear());
548 this.connectorsConfigurationHash
= connectorsConfigHash
;
549 // Add connector Id 0
550 let lastConnector
= '0';
551 for (lastConnector
in this.stationInfo
.Connectors
) {
552 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
553 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
554 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
555 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
556 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
557 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
561 // Generate all connectors
562 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
563 for (let index
= 1; index
<= maxConnectors
; index
++) {
564 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
565 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
566 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
567 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
568 this.getConnectorStatus(index
).chargingProfiles
= [];
573 // Avoid duplication of connectors related information
574 delete this.stationInfo
.Connectors
;
575 // Initialize transaction attributes on connectors
576 for (const connectorId
of this.connectors
.keys()) {
577 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
578 this.initializeConnectorStatus(connectorId
);
581 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
);
582 switch (this.getOcppVersion()) {
583 case OCPPVersion
.VERSION_16
:
584 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
585 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
588 this.handleUnsupportedVersion(this.getOcppVersion());
592 this.initOcppParameters();
593 if (this.stationInfo
.autoRegister
) {
594 this.bootNotificationResponse
= {
595 currentTime
: new Date().toISOString(),
596 interval
: this.getHeartbeatInterval() / 1000,
597 status: RegistrationStatus
.ACCEPTED
600 this.stationInfo
.powerDivider
= this.getPowerDivider();
601 if (this.getEnableStatistics()) {
602 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
606 private initOcppParameters(): void {
607 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
608 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionUrl().href
, { reboot
: true });
610 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
611 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
613 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
614 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
615 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
617 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
618 const connectorPhaseRotation
= [];
619 for (const connectorId
of this.connectors
.keys()) {
621 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
622 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
623 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
624 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
626 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
627 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
628 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
629 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
632 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
634 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
635 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
637 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
638 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
639 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
641 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
642 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
646 private async onOpen(): Promise
<void> {
647 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
648 if (!this.isRegistered()) {
649 // Send BootNotification
650 let registrationRetryCount
= 0;
652 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
653 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
654 if (!this.isRegistered()) {
655 registrationRetryCount
++;
656 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
658 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
660 if (this.isRegistered() && this.stationInfo
.autoRegister
) {
661 await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
662 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
664 if (this.isInAcceptedState()) {
665 await this.startMessageSequence();
666 this.stopped
&& (this.stopped
= false);
667 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
668 this.flushMessageBuffer();
670 } else if (this.isInPendingState()) {
671 // The central server shall issue a TriggerMessage to the charging station for the boot notification at the end of its configuration process
672 while (!this.isInAcceptedState()) {
673 await Utils
.sleep(Constants
.CHARGING_STATION_DEFAULT_START_SEQUENCE_DELAY
);
675 await this.startMessageSequence();
676 this.stopped
&& (this.stopped
= false);
677 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
678 this.flushMessageBuffer();
681 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
683 this.autoReconnectRetryCount
= 0;
684 this.wsConnectionRestarted
= false;
687 private async onClose(code
: number, reason
: string): Promise
<void> {
690 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
691 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
692 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
693 this.autoReconnectRetryCount
= 0;
697 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
698 await this.reconnect(code
);
703 private async onMessage(data
: Data
): Promise
<void> {
704 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
705 let responseCallback
: (payload
: JsonType
| string, requestPayload
: JsonType
| OCPPError
) => void;
706 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
707 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
708 let requestPayload
: JsonType
| OCPPError
;
709 let cachedRequest
: CachedRequest
;
712 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
713 if (Utils
.isIterable(request
)) {
715 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
717 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
719 // Check the Type of message
720 switch (messageType
) {
722 case MessageType
.CALL_MESSAGE
:
723 if (this.getEnableStatistics()) {
724 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
727 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
730 case MessageType
.CALL_RESULT_MESSAGE
:
732 cachedRequest
= this.requests
.get(messageId
);
733 if (Utils
.isIterable(cachedRequest
)) {
734 [responseCallback
, , , requestPayload
] = cachedRequest
;
736 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
738 if (!responseCallback
) {
740 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
742 responseCallback(commandName
, requestPayload
);
745 case MessageType
.CALL_ERROR_MESSAGE
:
746 cachedRequest
= this.requests
.get(messageId
);
747 if (Utils
.isIterable(cachedRequest
)) {
748 [, rejectCallback
, requestCommandName
] = cachedRequest
;
750 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
752 if (!rejectCallback
) {
754 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
756 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
760 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
761 logger
.error(errMsg
);
762 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
766 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
768 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
772 private onPing(): void {
773 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
776 private onPong(): void {
777 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
780 private async onError(error
: WSError
): Promise
<void> {
781 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
782 // switch (error.code) {
783 // case 'ECONNREFUSED':
784 // await this.reconnect(error);
789 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
790 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
793 private getAuthorizationFile(): string | undefined {
794 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
797 private getAuthorizedTags(): string[] {
798 let authorizedTags
: string[] = [];
799 const authorizationFile
= this.getAuthorizationFile();
800 if (authorizationFile
) {
802 // Load authorization file
803 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
804 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
805 fs
.closeSync(fileDescriptor
);
807 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
810 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
812 return authorizedTags
;
815 private getUseConnectorId0(): boolean | undefined {
816 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
819 private getNumberOfRunningTransactions(): number {
821 for (const connectorId
of this.connectors
.keys()) {
822 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
830 private getConnectionTimeout(): number | undefined {
831 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
832 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
834 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
837 // -1 for unlimited, 0 for disabling
838 private getAutoReconnectMaxRetries(): number | undefined {
839 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
840 return this.stationInfo
.autoReconnectMaxRetries
;
842 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
843 return Configuration
.getAutoReconnectMaxRetries();
849 private getRegistrationMaxRetries(): number | undefined {
850 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
851 return this.stationInfo
.registrationMaxRetries
;
856 private getPowerDivider(): number {
857 let powerDivider
= this.getNumberOfConnectors();
858 if (this.stationInfo
.powerSharedByConnectors
) {
859 powerDivider
= this.getNumberOfRunningTransactions();
864 private getTemplateMaxNumberOfConnectors(): number {
865 return Object.keys(this.stationInfo
.Connectors
).length
;
868 private getMaxNumberOfConnectors(): number {
869 let maxConnectors
: number;
870 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
871 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
872 // Distribute evenly the number of connectors
873 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
874 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
875 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
877 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
879 return maxConnectors
;
882 private async startMessageSequence(): Promise
<void> {
883 // Start WebSocket ping
884 this.startWebSocketPing();
886 this.startHeartbeat();
887 // Initialize connectors status
888 for (const connectorId
of this.connectors
.keys()) {
889 if (connectorId
=== 0) {
891 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
892 // Send status in template at startup
893 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
894 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
895 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
896 // Send status in template after reset
897 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
898 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
899 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
900 // Send previous status at template reload
901 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
903 // Send default status
904 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
905 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
909 this.startAutomaticTransactionGenerator();
912 private startAutomaticTransactionGenerator() {
913 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
914 if (!this.automaticTransactionGenerator
) {
915 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
917 if (!this.automaticTransactionGenerator
.started
) {
918 this.automaticTransactionGenerator
.start();
923 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
924 // Stop WebSocket ping
925 this.stopWebSocketPing();
927 this.stopHeartbeat();
929 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
930 this.automaticTransactionGenerator
&&
931 this.automaticTransactionGenerator
.started
) {
932 this.automaticTransactionGenerator
.stop();
934 for (const connectorId
of this.connectors
.keys()) {
935 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
936 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
937 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
938 this.getTransactionIdTag(transactionId
), reason
);
944 private startWebSocketPing(): void {
945 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
946 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
948 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
949 this.webSocketPingSetInterval
= setInterval(() => {
950 if (this.isWebSocketConnectionOpened()) {
951 this.wsConnection
.ping((): void => { /* This is intentional */ });
953 }, webSocketPingInterval
* 1000);
954 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
955 } else if (this.webSocketPingSetInterval
) {
956 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
958 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
962 private stopWebSocketPing(): void {
963 if (this.webSocketPingSetInterval
) {
964 clearInterval(this.webSocketPingSetInterval
);
968 private warnDeprecatedTemplateKey(template
: ChargingStationTemplate
, key
: string, chargingStationId
: string, logMsgToAppend
= ''): void {
969 if (!Utils
.isUndefined(template
[key
])) {
970 logger
.warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key
'${key}' usage
in file
'${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}
`);
974 private convertDeprecatedTemplateKey(template: ChargingStationTemplate, deprecatedKey: string, key: string): void {
975 if (!Utils.isUndefined(template[deprecatedKey])) {
976 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
977 template[key] = template[deprecatedKey];
978 delete template[deprecatedKey];
982 private getConfiguredSupervisionUrl(): URL {
983 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls());
984 if (!Utils.isEmptyArray(supervisionUrls)) {
986 switch (Configuration.getSupervisionUrlDistribution()) {
987 case SupervisionUrlDistribution.ROUND_ROBIN:
988 urlIndex = (this.index - 1) % supervisionUrls.length;
990 case SupervisionUrlDistribution.RANDOM:
992 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
994 case SupervisionUrlDistribution.SEQUENTIAL:
995 if (this.index <= supervisionUrls.length) {
996 urlIndex = this.index - 1;
998 logger.warn(`${this.logPrefix()} No more configured supervision urls available
, using the first one
`);
1002 logger.error(`${this.logPrefix()} Unknown supervision url distribution
'${Configuration.getSupervisionUrlDistribution()}' from values
'${SupervisionUrlDistribution.toString()}', defaulting to ${SupervisionUrlDistribution.ROUND_ROBIN}
`);
1003 urlIndex = (this.index - 1) % supervisionUrls.length;
1006 return new URL(supervisionUrls[urlIndex]);
1008 return new URL(supervisionUrls as string);
1011 private getHeartbeatInterval(): number | undefined {
1012 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1013 if (HeartbeatInterval) {
1014 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1016 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1017 if (HeartBeatInterval) {
1018 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1020 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set
, using
default value
: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}
`);
1021 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1024 private stopHeartbeat(): void {
1025 if (this.heartbeatSetInterval) {
1026 clearInterval(this.heartbeatSetInterval);
1030 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
1031 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1032 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
1033 options.auth = `${this.stationInfo.supervisionUser}
:${this.stationInfo.supervisionPassword}
`;
1035 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1036 this.wsConnection.close();
1038 let protocol: string;
1039 switch (this.getOcppVersion()) {
1040 case OCPPVersion.VERSION_16:
1041 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1044 this.handleUnsupportedVersion(this.getOcppVersion());
1047 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1048 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
1051 private stopMeterValues(connectorId: number) {
1052 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1053 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1057 private startAuthorizationFileMonitoring(): void {
1058 const authorizationFile = this.getAuthorizationFile();
1059 if (authorizationFile) {
1061 fs.watch(authorizationFile, (event, filename) => {
1062 if (filename && event === 'change') {
1064 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1065 // Initialize authorizedTags
1066 this.authorizedTags = this.getAuthorizedTags();
1068 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1073 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1076 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1080 private startStationTemplateFileMonitoring(): void {
1082 fs.watch(this.stationTemplateFile, (event, filename): void => {
1083 if (filename && event === 'change') {
1085 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1089 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1090 this.automaticTransactionGenerator) {
1091 this.automaticTransactionGenerator.stop();
1093 this.startAutomaticTransactionGenerator();
1094 if (this.getEnableStatistics()) {
1095 this.performanceStatistics.restart();
1097 this.performanceStatistics.stop();
1099 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1101 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1106 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1110 private getReconnectExponentialDelay(): boolean | undefined {
1111 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1114 private async reconnect(code: number): Promise<void> {
1115 // Stop WebSocket ping
1116 this.stopWebSocketPing();
1118 this.stopHeartbeat();
1119 // Stop the ATG if needed
1120 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1121 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1122 this.automaticTransactionGenerator &&
1123 this.automaticTransactionGenerator.started) {
1124 this.automaticTransactionGenerator.stop();
1126 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1127 this.autoReconnectRetryCount++;
1128 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1129 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
1130 logger.error(`${this.logPrefix()} WebSocket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectTimeout}ms
`);
1131 await Utils.sleep(reconnectDelay);
1132 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1133 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
1134 this.wsConnectionRestarted = true;
1135 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1136 logger.error(`${this.logPrefix()} WebSocket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1140 private initializeConnectorStatus(connectorId: number): void {
1141 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1142 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1143 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1144 this.getConnectorStatus(connectorId).transactionStarted = false;
1145 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1146 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;