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 isInPendingState(): boolean {
127 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
130 public isInAcceptedState(): boolean {
131 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
134 public isInRejectedState(): boolean {
135 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
138 public isRegistered(): boolean {
139 return this.isInAcceptedState() || this.isInPendingState();
142 public isChargingStationAvailable(): boolean {
143 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
146 public isConnectorAvailable(id
: number): boolean {
147 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
150 public getNumberOfConnectors(): number {
151 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
154 public getConnectorStatus(id
: number): ConnectorStatus
{
155 return this.connectors
.get(id
);
158 public getCurrentOutType(): CurrentType
| undefined {
159 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
162 public getVoltageOut(): number | undefined {
163 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
164 let defaultVoltageOut
: number;
165 switch (this.getCurrentOutType()) {
167 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
170 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
173 logger
.error(errMsg
);
174 throw new Error(errMsg
);
176 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
179 public getTransactionIdTag(transactionId
: number): string | undefined {
180 for (const connectorId
of this.connectors
.keys()) {
181 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
182 return this.getConnectorStatus(connectorId
).transactionIdTag
;
187 public getOutOfOrderEndMeterValues(): boolean {
188 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
191 public getBeginEndMeterValues(): boolean {
192 return this.stationInfo
.beginEndMeterValues
?? false;
195 public getMeteringPerTransaction(): boolean {
196 return this.stationInfo
.meteringPerTransaction
?? true;
199 public getTransactionDataMeterValues(): boolean {
200 return this.stationInfo
.transactionDataMeterValues
?? false;
203 public getMainVoltageMeterValues(): boolean {
204 return this.stationInfo
.mainVoltageMeterValues
?? true;
207 public getPhaseLineToLineVoltageMeterValues(): boolean {
208 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
211 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
212 if (this.getMeteringPerTransaction()) {
213 for (const connectorId
of this.connectors
.keys()) {
214 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
215 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
219 for (const connectorId
of this.connectors
.keys()) {
220 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
221 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
226 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
227 if (this.getMeteringPerTransaction()) {
228 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
230 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
233 public getAuthorizeRemoteTxRequests(): boolean {
234 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
235 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
238 public getLocalAuthListEnabled(): boolean {
239 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
240 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
243 public restartWebSocketPing(): void {
244 // Stop WebSocket ping
245 this.stopWebSocketPing();
246 // Start WebSocket ping
247 this.startWebSocketPing();
250 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
251 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
252 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
253 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
256 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
257 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`);
260 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
261 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
262 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
263 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
264 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
265 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
266 return sampledValueTemplates[index];
267 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
268 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
269 return sampledValueTemplates[index];
270 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
271 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
272 return sampledValueTemplates[index];
275 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
276 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
277 logger.error(errorMsg);
278 throw new Error(errorMsg);
280 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
283 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
284 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
287 public startHeartbeat(): void {
288 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
289 // eslint-disable-next-line @typescript-eslint/no-misused-promises
290 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
291 await this.ocppRequestService
.sendHeartbeat();
292 }, this.getHeartbeatInterval());
293 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
294 } else if (this.heartbeatSetInterval
) {
295 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
297 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
301 public restartHeartbeat(): void {
303 this.stopHeartbeat();
305 this.startHeartbeat();
308 public startMeterValues(connectorId
: number, interval
: number): void {
309 if (connectorId
=== 0) {
310 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
313 if (!this.getConnectorStatus(connectorId
)) {
314 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
317 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
318 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
320 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
321 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
325 // eslint-disable-next-line @typescript-eslint/no-misused-promises
326 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
327 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
330 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
334 public start(): void {
335 if (this.getEnableStatistics()) {
336 this.performanceStatistics
.start();
338 this.openWSConnection();
339 // Monitor authorization file
340 this.startAuthorizationFileMonitoring();
341 // Monitor station template file
342 this.startStationTemplateFileMonitoring();
343 // Handle WebSocket message
344 this.wsConnection
.on('message', this.onMessage
.bind(this));
345 // Handle WebSocket error
346 this.wsConnection
.on('error', this.onError
.bind(this));
347 // Handle WebSocket close
348 this.wsConnection
.on('close', this.onClose
.bind(this));
349 // Handle WebSocket open
350 this.wsConnection
.on('open', this.onOpen
.bind(this));
351 // Handle WebSocket ping
352 this.wsConnection
.on('ping', this.onPing
.bind(this));
353 // Handle WebSocket pong
354 this.wsConnection
.on('pong', this.onPong
.bind(this));
355 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STARTED
, data
: { id
: this.stationInfo
.chargingStationId
} });
358 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
359 // Stop message sequence
360 await this.stopMessageSequence(reason
);
361 for (const connectorId
of this.connectors
.keys()) {
362 if (connectorId
> 0) {
363 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
364 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
367 if (this.isWebSocketConnectionOpened()) {
368 this.wsConnection
.close();
370 if (this.getEnableStatistics()) {
371 this.performanceStatistics
.stop();
373 this.bootNotificationResponse
= null;
374 parentPort
.postMessage({ id
: ChargingStationWorkerMessageEvents
.STOPPED
, data
: { id
: this.stationInfo
.chargingStationId
} });
378 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
379 return this.configuration
.configurationKey
.find((configElement
) => {
380 if (caseInsensitive
) {
381 return configElement
.key
.toLowerCase() === key
.toLowerCase();
383 return configElement
.key
=== key
;
387 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
388 const keyFound
= this.getConfigurationKey(key
);
389 const readonly = options
.readonly;
390 const visible
= options
.visible
;
391 const reboot
= options
.reboot
;
393 this.configuration
.configurationKey
.push({
401 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
405 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
406 const keyFound
= this.getConfigurationKey(key
);
408 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
409 this.configuration
.configurationKey
[keyIndex
].value
= value
;
411 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
415 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
416 let cpReplaced
= false;
417 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
418 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
419 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
420 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
421 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
426 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
429 public resetConnectorStatus(connectorId
: number): void {
430 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
431 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
432 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
433 this.getConnectorStatus(connectorId
).transactionStarted
= false;
434 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
435 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
436 delete this.getConnectorStatus(connectorId
).transactionId
;
437 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
438 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
439 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
440 this.stopMeterValues(connectorId
);
443 public bufferMessage(message
: string): void {
444 this.messageBuffer
.add(message
);
447 private flushMessageBuffer() {
448 if (this.messageBuffer
.size
> 0) {
449 this.messageBuffer
.forEach((message
) => {
450 // TODO: evaluate the need to track performance
451 this.wsConnection
.send(message
);
452 this.messageBuffer
.delete(message
);
457 private getSupervisionUrlOcppConfiguration(): boolean {
458 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
461 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
462 // In case of multiple instances: add instance index to charging station id
463 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
464 const idSuffix
= stationTemplate
.nameSuffix
?? '';
465 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
468 private buildStationInfo(): ChargingStationInfo
{
469 let stationTemplateFromFile
: ChargingStationTemplate
;
471 // Load template file
472 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
473 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
474 fs
.closeSync(fileDescriptor
);
476 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
478 const chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
479 // Deprecation template keys section
480 this.warnDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', chargingStationId
, 'Use \'supervisionUrls\' instead');
481 this.convertDeprecatedTemplateKey(stationTemplateFromFile
, 'supervisionUrl', 'supervisionUrls');
482 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
483 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
484 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
485 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
486 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
487 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
488 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
489 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
491 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
492 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
493 ? stationTemplateFromFile
.power
* 1000
494 : stationTemplateFromFile
.power
;
496 delete stationInfo
.power
;
497 delete stationInfo
.powerUnit
;
498 stationInfo
.chargingStationId
= chargingStationId
;
499 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
503 private getOcppVersion(): OCPPVersion
{
504 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
507 private handleUnsupportedVersion(version
: OCPPVersion
) {
508 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
509 logger
.error(errMsg
);
510 throw new Error(errMsg
);
513 private initialize(): void {
514 this.stationInfo
= this.buildStationInfo();
515 this.configuration
= this.getTemplateChargingStationConfiguration();
516 delete this.stationInfo
.Configuration
;
517 this.bootNotificationRequest
= {
518 chargePointModel
: this.stationInfo
.chargePointModel
,
519 chargePointVendor
: this.stationInfo
.chargePointVendor
,
520 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
521 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
523 // Build connectors if needed
524 const maxConnectors
= this.getMaxNumberOfConnectors();
525 if (maxConnectors
<= 0) {
526 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
528 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
529 if (templateMaxConnectors
<= 0) {
530 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
532 if (!this.stationInfo
.Connectors
[0]) {
533 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
536 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
537 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
538 this.stationInfo
.randomConnectors
= true;
540 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
541 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
542 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
543 connectorsConfigChanged
&& (this.connectors
.clear());
544 this.connectorsConfigurationHash
= connectorsConfigHash
;
545 // Add connector Id 0
546 let lastConnector
= '0';
547 for (lastConnector
in this.stationInfo
.Connectors
) {
548 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
549 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
550 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
551 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
552 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
553 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
557 // Generate all connectors
558 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
559 for (let index
= 1; index
<= maxConnectors
; index
++) {
560 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
561 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
562 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
563 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
564 this.getConnectorStatus(index
).chargingProfiles
= [];
569 // Avoid duplication of connectors related information
570 delete this.stationInfo
.Connectors
;
571 // Initialize transaction attributes on connectors
572 for (const connectorId
of this.connectors
.keys()) {
573 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
574 this.initializeConnectorStatus(connectorId
);
577 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionUrl().href
+ '/' + this.stationInfo
.chargingStationId
);
578 switch (this.getOcppVersion()) {
579 case OCPPVersion
.VERSION_16
:
580 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
581 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
584 this.handleUnsupportedVersion(this.getOcppVersion());
588 this.initOcppParameters();
589 if (this.stationInfo
.autoRegister
) {
590 this.bootNotificationResponse
= {
591 currentTime
: new Date().toISOString(),
592 interval
: this.getHeartbeatInterval() / 1000,
593 status: RegistrationStatus
.ACCEPTED
596 this.stationInfo
.powerDivider
= this.getPowerDivider();
597 if (this.getEnableStatistics()) {
598 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
602 private initOcppParameters(): void {
603 if (this.getSupervisionUrlOcppConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
604 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionUrl().href
, { reboot
: true });
606 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
607 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
609 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
610 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
611 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
613 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
614 const connectorPhaseRotation
= [];
615 for (const connectorId
of this.connectors
.keys()) {
617 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
618 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
619 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
620 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
622 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
623 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
624 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
625 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
628 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
630 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
631 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
633 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
634 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
635 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
637 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
638 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
642 private async onOpen(): Promise
<void> {
643 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
644 if (!this.isRegistered()) {
645 // Send BootNotification
646 let registrationRetryCount
= 0;
648 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
649 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
650 if (!this.isRegistered()) {
651 registrationRetryCount
++;
652 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
654 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
656 if (this.isRegistered() && this.stationInfo
.autoRegister
) {
657 await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
658 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
660 if (this.isInAcceptedState()) {
661 await this.startMessageSequence();
662 this.stopped
&& (this.stopped
= false);
663 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
664 this.flushMessageBuffer();
666 } else if (this.isInPendingState()) {
667 // The central server shall issue a TriggerMessage to the charging station for the boot notification at the end of its configuration process
668 while (!this.isInAcceptedState()) {
669 await Utils
.sleep(Constants
.CHARGING_STATION_DEFAULT_START_SEQUENCE_DELAY
);
671 await this.startMessageSequence();
672 this.stopped
&& (this.stopped
= false);
673 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
674 this.flushMessageBuffer();
677 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
679 this.autoReconnectRetryCount
= 0;
680 this.wsConnectionRestarted
= false;
683 private async onClose(code
: number, reason
: string): Promise
<void> {
686 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
687 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
688 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
689 this.autoReconnectRetryCount
= 0;
693 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
694 await this.reconnect(code
);
699 private async onMessage(data
: Data
): Promise
<void> {
700 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
701 let responseCallback
: (payload
: JsonType
| string, requestPayload
: JsonType
| OCPPError
) => void;
702 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
703 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
704 let requestPayload
: JsonType
| OCPPError
;
705 let cachedRequest
: CachedRequest
;
708 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
709 if (Utils
.isIterable(request
)) {
711 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
713 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
715 // Check the Type of message
716 switch (messageType
) {
718 case MessageType
.CALL_MESSAGE
:
719 if (this.getEnableStatistics()) {
720 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
723 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
726 case MessageType
.CALL_RESULT_MESSAGE
:
728 cachedRequest
= this.requests
.get(messageId
);
729 if (Utils
.isIterable(cachedRequest
)) {
730 [responseCallback
, , , requestPayload
] = cachedRequest
;
732 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
734 if (!responseCallback
) {
736 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
738 responseCallback(commandName
, requestPayload
);
741 case MessageType
.CALL_ERROR_MESSAGE
:
742 cachedRequest
= this.requests
.get(messageId
);
743 if (Utils
.isIterable(cachedRequest
)) {
744 [, rejectCallback
, requestCommandName
] = cachedRequest
;
746 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
748 if (!rejectCallback
) {
750 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
752 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
756 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
757 logger
.error(errMsg
);
758 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
762 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
764 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
768 private onPing(): void {
769 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
772 private onPong(): void {
773 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
776 private async onError(error
: WSError
): Promise
<void> {
777 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
778 // switch (error.code) {
779 // case 'ECONNREFUSED':
780 // await this.reconnect(error);
785 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
786 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
789 private getAuthorizationFile(): string | undefined {
790 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
793 private getAuthorizedTags(): string[] {
794 let authorizedTags
: string[] = [];
795 const authorizationFile
= this.getAuthorizationFile();
796 if (authorizationFile
) {
798 // Load authorization file
799 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
800 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
801 fs
.closeSync(fileDescriptor
);
803 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
806 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
808 return authorizedTags
;
811 private getUseConnectorId0(): boolean | undefined {
812 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
815 private getNumberOfRunningTransactions(): number {
817 for (const connectorId
of this.connectors
.keys()) {
818 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
826 private getConnectionTimeout(): number | undefined {
827 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
828 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
830 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
833 // -1 for unlimited, 0 for disabling
834 private getAutoReconnectMaxRetries(): number | undefined {
835 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
836 return this.stationInfo
.autoReconnectMaxRetries
;
838 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
839 return Configuration
.getAutoReconnectMaxRetries();
845 private getRegistrationMaxRetries(): number | undefined {
846 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
847 return this.stationInfo
.registrationMaxRetries
;
852 private getPowerDivider(): number {
853 let powerDivider
= this.getNumberOfConnectors();
854 if (this.stationInfo
.powerSharedByConnectors
) {
855 powerDivider
= this.getNumberOfRunningTransactions();
860 private getTemplateMaxNumberOfConnectors(): number {
861 return Object.keys(this.stationInfo
.Connectors
).length
;
864 private getMaxNumberOfConnectors(): number {
865 let maxConnectors
: number;
866 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
867 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
868 // Distribute evenly the number of connectors
869 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
870 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
871 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
873 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
875 return maxConnectors
;
878 private async startMessageSequence(): Promise
<void> {
879 // Start WebSocket ping
880 this.startWebSocketPing();
882 this.startHeartbeat();
883 // Initialize connectors status
884 for (const connectorId
of this.connectors
.keys()) {
885 if (connectorId
=== 0) {
887 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
888 // Send status in template at startup
889 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
890 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
891 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
892 // Send status in template after reset
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) {
896 // Send previous status at template reload
897 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
899 // Send default status
900 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
901 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
905 this.startAutomaticTransactionGenerator();
908 private startAutomaticTransactionGenerator() {
909 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
910 if (!this.automaticTransactionGenerator
) {
911 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
913 if (!this.automaticTransactionGenerator
.started
) {
914 this.automaticTransactionGenerator
.start();
919 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
920 // Stop WebSocket ping
921 this.stopWebSocketPing();
923 this.stopHeartbeat();
925 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
926 this.automaticTransactionGenerator
&&
927 this.automaticTransactionGenerator
.started
) {
928 this.automaticTransactionGenerator
.stop();
930 for (const connectorId
of this.connectors
.keys()) {
931 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
932 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
933 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
934 this.getTransactionIdTag(transactionId
), reason
);
940 private startWebSocketPing(): void {
941 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
942 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
944 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
945 this.webSocketPingSetInterval
= setInterval(() => {
946 if (this.isWebSocketConnectionOpened()) {
947 this.wsConnection
.ping((): void => { /* This is intentional */ });
949 }, webSocketPingInterval
* 1000);
950 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
951 } else if (this.webSocketPingSetInterval
) {
952 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
954 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
958 private stopWebSocketPing(): void {
959 if (this.webSocketPingSetInterval
) {
960 clearInterval(this.webSocketPingSetInterval
);
964 private warnDeprecatedTemplateKey(template
: ChargingStationTemplate
, key
: string, chargingStationId
: string, logMsgToAppend
= ''): void {
965 if (!Utils
.isUndefined(template
[key
])) {
966 logger
.warn(`${Utils.logPrefix(` ${chargingStationId} |`)} Deprecated template key
'${key}' usage
in file
'${this.stationTemplateFile}'${logMsgToAppend && '. ' + logMsgToAppend}
`);
970 private convertDeprecatedTemplateKey(template: ChargingStationTemplate, deprecatedKey: string, key: string): void {
971 if (!Utils.isUndefined(template[deprecatedKey])) {
972 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
973 template[key] = template[deprecatedKey];
974 delete template[deprecatedKey];
978 private getConfiguredSupervisionUrl(): URL {
979 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls());
980 if (!Utils.isEmptyArray(supervisionUrls)) {
982 switch (Configuration.getSupervisionUrlDistribution()) {
983 case SupervisionUrlDistribution.ROUND_ROBIN:
984 urlIndex = (this.index - 1) % supervisionUrls.length;
986 case SupervisionUrlDistribution.RANDOM:
988 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
990 case SupervisionUrlDistribution.SEQUENTIAL:
991 if (this.index <= supervisionUrls.length) {
992 urlIndex = this.index - 1;
994 logger.warn(`${this.logPrefix()} No more configured supervision urls available
, using the first one
`);
998 logger.error(`${this.logPrefix()} Unknown supervision url distribution
'${Configuration.getSupervisionUrlDistribution()}' from values
'${SupervisionUrlDistribution.toString()}', defaulting to ${SupervisionUrlDistribution.ROUND_ROBIN}
`);
999 urlIndex = (this.index - 1) % supervisionUrls.length;
1002 return new URL(supervisionUrls[urlIndex]);
1004 return new URL(supervisionUrls as string);
1007 private getHeartbeatInterval(): number | undefined {
1008 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1009 if (HeartbeatInterval) {
1010 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1012 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1013 if (HeartBeatInterval) {
1014 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1016 !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set
, using
default value
: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}
`);
1017 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1020 private stopHeartbeat(): void {
1021 if (this.heartbeatSetInterval) {
1022 clearInterval(this.heartbeatSetInterval);
1026 private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
1027 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1028 if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
1029 options.auth = `${this.stationInfo.supervisionUser}
:${this.stationInfo.supervisionPassword}
`;
1031 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1032 this.wsConnection.close();
1034 let protocol: string;
1035 switch (this.getOcppVersion()) {
1036 case OCPPVersion.VERSION_16:
1037 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1040 this.handleUnsupportedVersion(this.getOcppVersion());
1043 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1044 logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString());
1047 private stopMeterValues(connectorId: number) {
1048 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1049 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1053 private startAuthorizationFileMonitoring(): void {
1054 const authorizationFile = this.getAuthorizationFile();
1055 if (authorizationFile) {
1057 fs.watch(authorizationFile, (event, filename) => {
1058 if (filename && event === 'change') {
1060 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
1061 // Initialize authorizedTags
1062 this.authorizedTags = this.getAuthorizedTags();
1064 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1069 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error as NodeJS.ErrnoException);
1072 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
1076 private startStationTemplateFileMonitoring(): void {
1078 fs.watch(this.stationTemplateFile, (event, filename): void => {
1079 if (filename && event === 'change') {
1081 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
1085 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
1086 this.automaticTransactionGenerator) {
1087 this.automaticTransactionGenerator.stop();
1089 this.startAutomaticTransactionGenerator();
1090 if (this.getEnableStatistics()) {
1091 this.performanceStatistics.restart();
1093 this.performanceStatistics.stop();
1095 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1097 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1102 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
1106 private getReconnectExponentialDelay(): boolean | undefined {
1107 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1110 private async reconnect(code: number): Promise<void> {
1111 // Stop WebSocket ping
1112 this.stopWebSocketPing();
1114 this.stopHeartbeat();
1115 // Stop the ATG if needed
1116 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1117 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1118 this.automaticTransactionGenerator &&
1119 this.automaticTransactionGenerator.started) {
1120 this.automaticTransactionGenerator.stop();
1122 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1123 this.autoReconnectRetryCount++;
1124 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1125 const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
1126 logger.error(`${this.logPrefix()} WebSocket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectTimeout}ms
`);
1127 await Utils.sleep(reconnectDelay);
1128 logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1129 this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
1130 this.wsConnectionRestarted = true;
1131 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1132 logger.error(`${this.logPrefix()} WebSocket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1136 private initializeConnectorStatus(connectorId: number): void {
1137 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1138 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1139 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1140 this.getConnectorStatus(connectorId).transactionStarted = false;
1141 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1142 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;