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 { ConnectorStatus
, SampledValueTemplate
} from
'../types/Connectors';
9 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
10 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
11 import WebSocket
, { ClientOptions
, Data
, OPEN
} from
'ws';
13 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
14 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
15 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
16 import ChargingStationInfo from
'../types/ChargingStationInfo';
17 import { ClientRequestArgs
} from
'http';
18 import Configuration from
'../utils/Configuration';
19 import Constants from
'../utils/Constants';
20 import { ErrorType
} from
'../types/ocpp/ErrorType';
21 import FileUtils from
'../utils/FileUtils';
22 import { MessageType
} from
'../types/ocpp/MessageType';
23 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
24 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
25 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
26 import OCPPError from
'./ocpp/OCPPError';
27 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
28 import OCPPRequestService from
'./ocpp/OCPPRequestService';
29 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
30 import PerformanceStatistics from
'../performance/PerformanceStatistics';
31 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
32 import { URL
} from
'url';
33 import Utils from
'../utils/Utils';
34 import crypto from
'crypto';
36 import logger from
'../utils/Logger';
37 import path from
'path';
39 export default class ChargingStation
{
40 public readonly stationTemplateFile
: string;
41 public authorizedTags
: string[];
42 public stationInfo
!: ChargingStationInfo
;
43 public readonly connectors
: Map
<number, ConnectorStatus
>;
44 public configuration
!: ChargingStationConfiguration
;
45 public wsConnection
!: WebSocket
;
46 public readonly requests
: Map
<string, CachedRequest
>;
47 public performanceStatistics
!: PerformanceStatistics
;
48 public heartbeatSetInterval
!: NodeJS
.Timeout
;
49 public ocppRequestService
!: OCPPRequestService
;
50 private readonly index
: number;
51 private bootNotificationRequest
!: BootNotificationRequest
;
52 private bootNotificationResponse
!: BootNotificationResponse
| null;
53 private connectorsConfigurationHash
!: string;
54 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
55 private readonly messageBuffer
: Set
<string>;
56 private wsConfiguredConnectionUrl
!: URL
;
57 private wsConnectionRestarted
: boolean;
58 private stopped
: boolean;
59 private autoReconnectRetryCount
: number;
60 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
61 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
63 constructor(index
: number, stationTemplateFile
: string) {
65 this.stationTemplateFile
= stationTemplateFile
;
66 this.connectors
= new Map
<number, ConnectorStatus
>();
70 this.wsConnectionRestarted
= false;
71 this.autoReconnectRetryCount
= 0;
73 this.requests
= new Map
<string, CachedRequest
>();
74 this.messageBuffer
= new Set
<string>();
76 this.authorizedTags
= this.getAuthorizedTags();
79 get
wsConnectionUrl(): URL
{
80 return this.getSupervisionURLOCPPConfiguration() ? new URL(this.getConfigurationKey(this.stationInfo
.supervisionURLOCPPKey
?? VendorDefaultParametersKey
.ConnectionUrl
).value
+ '/' + this.stationInfo
.chargingStationId
) : this.wsConfiguredConnectionUrl
;
83 public logPrefix(): string {
84 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
87 public getBootNotificationRequest(): BootNotificationRequest
{
88 return this.bootNotificationRequest
;
91 public getRandomIdTag(): string {
92 const index
= Math.floor(Utils
.secureRandom() * this.authorizedTags
.length
);
93 return this.authorizedTags
[index
];
96 public hasAuthorizedTags(): boolean {
97 return !Utils
.isEmptyArray(this.authorizedTags
);
100 public getEnableStatistics(): boolean | undefined {
101 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
104 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
105 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
108 public getNumberOfPhases(): number | undefined {
109 switch (this.getCurrentOutType()) {
111 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
117 public isWebSocketConnectionOpened(): boolean {
118 return this.wsConnection
?.readyState
=== OPEN
;
121 public isRegistered(): boolean {
122 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
125 public isChargingStationAvailable(): boolean {
126 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
129 public isConnectorAvailable(id
: number): boolean {
130 return this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
133 public getNumberOfConnectors(): number {
134 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
137 public getConnectorStatus(id
: number): ConnectorStatus
{
138 return this.connectors
.get(id
);
141 public getCurrentOutType(): CurrentType
| undefined {
142 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
145 public getVoltageOut(): number | undefined {
146 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
147 let defaultVoltageOut
: number;
148 switch (this.getCurrentOutType()) {
150 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
153 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
156 logger
.error(errMsg
);
157 throw new Error(errMsg
);
159 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
162 public getTransactionIdTag(transactionId
: number): string | undefined {
163 for (const connectorId
of this.connectors
.keys()) {
164 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
165 return this.getConnectorStatus(connectorId
).transactionIdTag
;
170 public getOutOfOrderEndMeterValues(): boolean {
171 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
174 public getBeginEndMeterValues(): boolean {
175 return this.stationInfo
.beginEndMeterValues
?? false;
178 public getMeteringPerTransaction(): boolean {
179 return this.stationInfo
.meteringPerTransaction
?? true;
182 public getTransactionDataMeterValues(): boolean {
183 return this.stationInfo
.transactionDataMeterValues
?? false;
186 public getMainVoltageMeterValues(): boolean {
187 return this.stationInfo
.mainVoltageMeterValues
?? true;
190 public getPhaseLineToLineVoltageMeterValues(): boolean {
191 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
194 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
195 if (this.getMeteringPerTransaction()) {
196 for (const connectorId
of this.connectors
.keys()) {
197 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
198 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
202 for (const connectorId
of this.connectors
.keys()) {
203 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
204 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
209 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
210 if (this.getMeteringPerTransaction()) {
211 return this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
;
213 return this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
;
216 public getAuthorizeRemoteTxRequests(): boolean {
217 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
218 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
221 public getLocalAuthListEnabled(): boolean {
222 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
223 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
226 public restartWebSocketPing(): void {
227 // Stop WebSocket ping
228 this.stopWebSocketPing();
229 // Start WebSocket ping
230 this.startWebSocketPing();
233 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
234 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
235 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
236 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
239 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
240 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`);
243 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnectorStatus(connectorId
).MeterValues
;
244 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
245 if (!Constants
.SUPPORTED_MEASURANDS
.includes(sampledValueTemplates
[index
]?.measurand
?? MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
)) {
246 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
247 } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand
248 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
249 return sampledValueTemplates[index];
250 } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand
251 && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
252 return sampledValueTemplates[index];
253 } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
254 && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) {
255 return sampledValueTemplates[index];
258 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
259 const errorMsg = `${this.logPrefix()} Missing MeterValues
for default measurand
'${measurand}' in template on connectorId ${connectorId}
`;
260 logger.error(errorMsg);
261 throw new Error(errorMsg);
263 logger.debug(`${this.logPrefix()} No MeterValues
for measurand
'${measurand}' ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId}`);
266 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
267 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
270 public startHeartbeat(): void {
271 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
272 // eslint-disable-next-line @typescript-eslint/no-misused-promises
273 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
274 await this.ocppRequestService
.sendHeartbeat();
275 }, this.getHeartbeatInterval());
276 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
277 } else if (this.heartbeatSetInterval
) {
278 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval()));
280 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
284 public restartHeartbeat(): void {
286 this.stopHeartbeat();
288 this.startHeartbeat();
291 public startMeterValues(connectorId
: number, interval
: number): void {
292 if (connectorId
=== 0) {
293 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
296 if (!this.getConnectorStatus(connectorId
)) {
297 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
300 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
301 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
303 } else if (this.getConnectorStatus(connectorId
)?.transactionStarted
&& !this.getConnectorStatus(connectorId
)?.transactionId
) {
304 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
308 // eslint-disable-next-line @typescript-eslint/no-misused-promises
309 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
310 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnectorStatus(connectorId
).transactionId
, interval
);
313 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.formatDurationMilliSeconds(interval) : interval}, not sending MeterValues`);
317 public start(): void {
318 if (this.getEnableStatistics()) {
319 this.performanceStatistics
.start();
321 this.openWSConnection();
322 // Monitor authorization file
323 this.startAuthorizationFileMonitoring();
324 // Monitor station template file
325 this.startStationTemplateFileMonitoring();
326 // Handle WebSocket message
327 this.wsConnection
.on('message', this.onMessage
.bind(this));
328 // Handle WebSocket error
329 this.wsConnection
.on('error', this.onError
.bind(this));
330 // Handle WebSocket close
331 this.wsConnection
.on('close', this.onClose
.bind(this));
332 // Handle WebSocket open
333 this.wsConnection
.on('open', this.onOpen
.bind(this));
334 // Handle WebSocket ping
335 this.wsConnection
.on('ping', this.onPing
.bind(this));
336 // Handle WebSocket pong
337 this.wsConnection
.on('pong', this.onPong
.bind(this));
340 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
341 // Stop message sequence
342 await this.stopMessageSequence(reason
);
343 for (const connectorId
of this.connectors
.keys()) {
344 if (connectorId
> 0) {
345 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.UNAVAILABLE
);
346 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
349 if (this.isWebSocketConnectionOpened()) {
350 this.wsConnection
.close();
352 if (this.getEnableStatistics()) {
353 this.performanceStatistics
.stop();
355 this.bootNotificationResponse
= null;
359 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
360 return this.configuration
.configurationKey
.find((configElement
) => {
361 if (caseInsensitive
) {
362 return configElement
.key
.toLowerCase() === key
.toLowerCase();
364 return configElement
.key
=== key
;
368 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, options
: { readonly?: boolean, visible
?: boolean, reboot
?: boolean } = { readonly: false, visible
: true, reboot
: false }): void {
369 const keyFound
= this.getConfigurationKey(key
);
370 const readonly = options
.readonly;
371 const visible
= options
.visible
;
372 const reboot
= options
.reboot
;
374 this.configuration
.configurationKey
.push({
382 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
386 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
387 const keyFound
= this.getConfigurationKey(key
);
389 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
390 this.configuration
.configurationKey
[keyIndex
].value
= value
;
392 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
396 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
397 let cpReplaced
= false;
398 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
399 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
400 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
401 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
402 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
407 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
410 public resetConnectorStatus(connectorId
: number): void {
411 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
412 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
413 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
414 this.getConnectorStatus(connectorId
).transactionStarted
= false;
415 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
416 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
417 delete this.getConnectorStatus(connectorId
).transactionId
;
418 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
419 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
420 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
421 this.stopMeterValues(connectorId
);
424 public bufferMessage(message
: string): void {
425 this.messageBuffer
.add(message
);
428 private flushMessageBuffer() {
429 if (this.messageBuffer
.size
> 0) {
430 this.messageBuffer
.forEach((message
) => {
431 // TODO: evaluate the need to track performance
432 this.wsConnection
.send(message
);
433 this.messageBuffer
.delete(message
);
438 private getSupervisionURLOCPPConfiguration(): boolean {
439 return this.stationInfo
.supervisionURLOCPPConfiguration
?? false;
442 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
443 // In case of multiple instances: add instance index to charging station id
444 const instanceIndex
= process
.env
.CF_INSTANCE_INDEX
?? 0;
445 const idSuffix
= stationTemplate
.nameSuffix
?? '';
446 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
449 private buildStationInfo(): ChargingStationInfo
{
450 let stationTemplateFromFile
: ChargingStationTemplate
;
452 // Load template file
453 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
454 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
455 fs
.closeSync(fileDescriptor
);
457 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
459 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
460 stationInfo
.wsOptions
= stationTemplateFromFile
?.wsOptions
?? {};
461 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
462 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
463 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplateFromFile
.power
.length
);
464 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
465 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
466 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
468 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
469 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
470 ? stationTemplateFromFile
.power
* 1000
471 : stationTemplateFromFile
.power
;
473 delete stationInfo
.power
;
474 delete stationInfo
.powerUnit
;
475 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
476 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
480 private getOCPPVersion(): OCPPVersion
{
481 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
484 private handleUnsupportedVersion(version
: OCPPVersion
) {
485 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
486 logger
.error(errMsg
);
487 throw new Error(errMsg
);
490 private initialize(): void {
491 this.stationInfo
= this.buildStationInfo();
492 this.configuration
= this.getTemplateChargingStationConfiguration();
493 delete this.stationInfo
.Configuration
;
494 this.bootNotificationRequest
= {
495 chargePointModel
: this.stationInfo
.chargePointModel
,
496 chargePointVendor
: this.stationInfo
.chargePointVendor
,
497 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
498 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
500 // Build connectors if needed
501 const maxConnectors
= this.getMaxNumberOfConnectors();
502 if (maxConnectors
<= 0) {
503 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
505 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
506 if (templateMaxConnectors
<= 0) {
507 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
509 if (!this.stationInfo
.Connectors
[0]) {
510 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
513 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
514 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
515 this.stationInfo
.randomConnectors
= true;
517 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
518 const connectorsConfigChanged
= this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
519 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
520 connectorsConfigChanged
&& (this.connectors
.clear());
521 this.connectorsConfigurationHash
= connectorsConfigHash
;
522 // Add connector Id 0
523 let lastConnector
= '0';
524 for (lastConnector
in this.stationInfo
.Connectors
) {
525 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
526 if (lastConnectorId
=== 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
527 this.connectors
.set(lastConnectorId
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[lastConnector
]));
528 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
529 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
530 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
534 // Generate all connectors
535 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
536 for (let index
= 1; index
<= maxConnectors
; index
++) {
537 const randConnectorId
= this.stationInfo
.randomConnectors
? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1) : index
;
538 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(this.stationInfo
.Connectors
[randConnectorId
]));
539 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
540 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
541 this.getConnectorStatus(index
).chargingProfiles
= [];
546 // Avoid duplication of connectors related information
547 delete this.stationInfo
.Connectors
;
548 // Initialize transaction attributes on connectors
549 for (const connectorId
of this.connectors
.keys()) {
550 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
551 this.initializeConnectorStatus(connectorId
);
554 this.wsConfiguredConnectionUrl
= new URL(this.getConfiguredSupervisionURL().href
+ '/' + this.stationInfo
.chargingStationId
);
555 switch (this.getOCPPVersion()) {
556 case OCPPVersion
.VERSION_16
:
557 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
558 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
561 this.handleUnsupportedVersion(this.getOCPPVersion());
565 this.initOCPPParameters();
566 if (this.stationInfo
.autoRegister
) {
567 this.bootNotificationResponse
= {
568 currentTime
: new Date().toISOString(),
569 interval
: this.getHeartbeatInterval() / 1000,
570 status: RegistrationStatus
.ACCEPTED
573 this.stationInfo
.powerDivider
= this.getPowerDivider();
574 if (this.getEnableStatistics()) {
575 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
, this.wsConnectionUrl
);
579 private initOCPPParameters(): void {
580 if (this.getSupervisionURLOCPPConfiguration() && !this.getConfigurationKey(this.stationInfo
.supervisionURLOCPPKey
?? VendorDefaultParametersKey
.ConnectionUrl
)) {
581 this.addConfigurationKey(VendorDefaultParametersKey
.ConnectionUrl
, this.getConfiguredSupervisionURL().href
, { reboot
: true });
583 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
584 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
586 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), { readonly: true });
587 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
588 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
590 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
591 const connectorPhaseRotation
= [];
592 for (const connectorId
of this.connectors
.keys()) {
594 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
595 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
596 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
597 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
599 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
600 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
601 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
602 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
605 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
607 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
608 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
610 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
611 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
612 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
614 if (!this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
615 this.addConfigurationKey(StandardParametersKey
.ConnectionTimeOut
, Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString());
619 private async onOpen(): Promise
<void> {
620 logger
.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`);
621 if (!this.isRegistered()) {
622 // Send BootNotification
623 let registrationRetryCount
= 0;
625 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
626 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
627 if (!this.isRegistered()) {
628 registrationRetryCount
++;
629 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
631 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
633 if (this.isRegistered()) {
634 await this.startMessageSequence();
635 this.stopped
&& (this.stopped
= false);
636 if (this.wsConnectionRestarted
&& this.isWebSocketConnectionOpened()) {
637 this.flushMessageBuffer();
640 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
642 this.autoReconnectRetryCount
= 0;
643 this.wsConnectionRestarted
= false;
646 private async onClose(code
: number, reason
: string): Promise
<void> {
649 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
650 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
651 logger
.info(`${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
652 this.autoReconnectRetryCount
= 0;
656 logger
.error(`${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(code)}' and reason '${reason}'`);
657 await this.reconnect(code
);
662 private async onMessage(data
: Data
): Promise
<void> {
663 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
664 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
665 let rejectCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
666 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
667 let requestPayload
: Record
<string, unknown
>;
668 let cachedRequest
: CachedRequest
;
671 const request
= JSON
.parse(data
.toString()) as IncomingRequest
;
672 if (Utils
.isIterable(request
)) {
674 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = request
;
676 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming request is not iterable', commandName
);
678 // Check the Type of message
679 switch (messageType
) {
681 case MessageType
.CALL_MESSAGE
:
682 if (this.getEnableStatistics()) {
683 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
686 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
689 case MessageType
.CALL_RESULT_MESSAGE
:
691 cachedRequest
= this.requests
.get(messageId
);
692 if (Utils
.isIterable(cachedRequest
)) {
693 [responseCallback
, , , requestPayload
] = cachedRequest
;
695 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} response is not iterable`, commandName
);
697 if (!responseCallback
) {
699 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Response for unknown message id ${messageId}`, commandName
);
701 responseCallback(commandName
, requestPayload
);
704 case MessageType
.CALL_ERROR_MESSAGE
:
705 cachedRequest
= this.requests
.get(messageId
);
706 if (Utils
.isIterable(cachedRequest
)) {
707 [, rejectCallback
, requestCommandName
] = cachedRequest
;
709 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, `Cached request for message id ${messageId} error response is not iterable`);
711 if (!rejectCallback
) {
713 throw new OCPPError(ErrorType
.INTERNAL_ERROR
, `Error response for unknown message id ${messageId}`, requestCommandName
);
715 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), requestCommandName
, errorDetails
));
719 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
720 logger
.error(errMsg
);
721 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
725 logger
.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data
.toString(), this.requests
.get(messageId
), error
);
727 messageType
=== MessageType
.CALL_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
as OCPPError
, commandName
);
731 private onPing(): void {
732 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
735 private onPong(): void {
736 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
739 private async onError(error
: WSError
): Promise
<void> {
740 logger
.error(this.logPrefix() + ' WebSocket error: %j', error
);
741 // switch (error.code) {
742 // case 'ECONNREFUSED':
743 // await this.reconnect(error);
748 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
749 return this.stationInfo
.Configuration
?? {} as ChargingStationConfiguration
;
752 private getAuthorizationFile(): string | undefined {
753 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
756 private getAuthorizedTags(): string[] {
757 let authorizedTags
: string[] = [];
758 const authorizationFile
= this.getAuthorizationFile();
759 if (authorizationFile
) {
761 // Load authorization file
762 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
763 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
764 fs
.closeSync(fileDescriptor
);
766 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
769 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
771 return authorizedTags
;
774 private getUseConnectorId0(): boolean | undefined {
775 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
778 private getNumberOfRunningTransactions(): number {
780 for (const connectorId
of this.connectors
.keys()) {
781 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
789 private getConnectionTimeout(): number | undefined {
790 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
791 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
793 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
796 // -1 for unlimited, 0 for disabling
797 private getAutoReconnectMaxRetries(): number | undefined {
798 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
799 return this.stationInfo
.autoReconnectMaxRetries
;
801 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
802 return Configuration
.getAutoReconnectMaxRetries();
808 private getRegistrationMaxRetries(): number | undefined {
809 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
810 return this.stationInfo
.registrationMaxRetries
;
815 private getPowerDivider(): number {
816 let powerDivider
= this.getNumberOfConnectors();
817 if (this.stationInfo
.powerSharedByConnectors
) {
818 powerDivider
= this.getNumberOfRunningTransactions();
823 private getTemplateMaxNumberOfConnectors(): number {
824 return Object.keys(this.stationInfo
.Connectors
).length
;
827 private getMaxNumberOfConnectors(): number {
828 let maxConnectors
= 0;
829 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
830 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
831 // Distribute evenly the number of connectors
832 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
833 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
834 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
836 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
838 return maxConnectors
;
841 private async startMessageSequence(): Promise
<void> {
842 // Start WebSocket ping
843 this.startWebSocketPing();
845 this.startHeartbeat();
846 // Initialize connectors status
847 for (const connectorId
of this.connectors
.keys()) {
848 if (connectorId
=== 0) {
850 } else if (!this.stopped
&& !this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
851 // Send status in template at startup
852 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
853 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
854 } else if (this.stopped
&& this.getConnectorStatus(connectorId
)?.status && this.getConnectorStatus(connectorId
)?.bootStatus
) {
855 // Send status in template after reset
856 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).bootStatus
);
857 this.getConnectorStatus(connectorId
).status = this.getConnectorStatus(connectorId
).bootStatus
;
858 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
859 // Send previous status at template reload
860 await this.ocppRequestService
.sendStatusNotification(connectorId
, this.getConnectorStatus(connectorId
).status);
862 // Send default status
863 await this.ocppRequestService
.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
864 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
868 this.startAutomaticTransactionGenerator();
871 private startAutomaticTransactionGenerator() {
872 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
873 if (!this.automaticTransactionGenerator
) {
874 this.automaticTransactionGenerator
= new AutomaticTransactionGenerator(this);
876 if (!this.automaticTransactionGenerator
.started
) {
877 this.automaticTransactionGenerator
.start();
882 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
883 // Stop WebSocket ping
884 this.stopWebSocketPing();
886 this.stopHeartbeat();
888 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
889 this.automaticTransactionGenerator
&&
890 this.automaticTransactionGenerator
.started
) {
891 this.automaticTransactionGenerator
.stop();
893 for (const connectorId
of this.connectors
.keys()) {
894 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
895 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
896 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
897 this.getTransactionIdTag(transactionId
), reason
);
903 private startWebSocketPing(): void {
904 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
905 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
907 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
908 this.webSocketPingSetInterval
= setInterval(() => {
909 if (this.isWebSocketConnectionOpened()) {
910 this.wsConnection
.ping((): void => { /* This is intentional */ });
912 }, webSocketPingInterval
* 1000);
913 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.formatDurationSeconds(webSocketPingInterval
));
914 } else if (this.webSocketPingSetInterval
) {
915 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.formatDurationSeconds(webSocketPingInterval
) + ' already started');
917 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.formatDurationSeconds(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
921 private stopWebSocketPing(): void {
922 if (this.webSocketPingSetInterval
) {
923 clearInterval(this.webSocketPingSetInterval
);
927 private getConfiguredSupervisionURL(): URL
{
928 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
?? Configuration
.getSupervisionURLs());
930 if (!Utils
.isEmptyArray(supervisionUrls
)) {
931 if (Configuration
.getDistributeStationsToTenantsEqually()) {
932 indexUrl
= this.index
% supervisionUrls
.length
;
935 indexUrl
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
937 return new URL(supervisionUrls
[indexUrl
]);
939 return new URL(supervisionUrls
as string);
942 private getHeartbeatInterval(): number | undefined {
943 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
944 if (HeartbeatInterval
) {
945 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
947 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
948 if (HeartBeatInterval
) {
949 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
951 !this.stationInfo
.autoRegister
&& logger
.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`);
952 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
955 private stopHeartbeat(): void {
956 if (this.heartbeatSetInterval
) {
957 clearInterval(this.heartbeatSetInterval
);
961 private openWSConnection(options
: ClientOptions
& ClientRequestArgs
= this.stationInfo
.wsOptions
, forceCloseOpened
= false): void {
962 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
963 if (!Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) && !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)) {
964 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
966 if (this.isWebSocketConnectionOpened() && forceCloseOpened
) {
967 this.wsConnection
.close();
969 let protocol
: string;
970 switch (this.getOCPPVersion()) {
971 case OCPPVersion
.VERSION_16
:
972 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
975 this.handleUnsupportedVersion(this.getOCPPVersion());
978 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
979 logger
.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl
.toString());
982 private stopMeterValues(connectorId
: number) {
983 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
984 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
988 private startAuthorizationFileMonitoring(): void {
989 const authorizationFile
= this.getAuthorizationFile();
990 if (authorizationFile
) {
992 fs
.watch(authorizationFile
, (event
, filename
) => {
993 if (filename
&& event
=== 'change') {
995 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
996 // Initialize authorizedTags
997 this.authorizedTags
= this.getAuthorizedTags();
999 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
1004 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
as NodeJS
.ErrnoException
);
1007 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
1011 private startStationTemplateFileMonitoring(): void {
1013 fs
.watch(this.stationTemplateFile
, (event
, filename
): void => {
1014 if (filename
&& event
=== 'change') {
1016 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
1020 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1021 this.automaticTransactionGenerator
) {
1022 this.automaticTransactionGenerator
.stop();
1024 this.startAutomaticTransactionGenerator();
1025 if (this.getEnableStatistics()) {
1026 this.performanceStatistics
.restart();
1028 this.performanceStatistics
.stop();
1030 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1032 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
1037 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
as NodeJS
.ErrnoException
);
1041 private getReconnectExponentialDelay(): boolean | undefined {
1042 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
1045 private async reconnect(code
: number): Promise
<void> {
1046 // Stop WebSocket ping
1047 this.stopWebSocketPing();
1049 this.stopHeartbeat();
1050 // Stop the ATG if needed
1051 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
1052 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
1053 this.automaticTransactionGenerator
&&
1054 this.automaticTransactionGenerator
.started
) {
1055 this.automaticTransactionGenerator
.stop();
1057 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1058 this.autoReconnectRetryCount
++;
1059 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
1060 const reconnectTimeout
= (reconnectDelay
- 100) > 0 && reconnectDelay
;
1061 logger
.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
1062 await Utils
.sleep(reconnectDelay
);
1063 logger
.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
1064 this.openWSConnection({ ...this.stationInfo
.wsOptions
, handshakeTimeout
: reconnectTimeout
}, true);
1065 this.wsConnectionRestarted
= true;
1066 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1067 logger
.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
1071 private initializeConnectorStatus(connectorId
: number): void {
1072 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
1073 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
1074 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
1075 this.getConnectorStatus(connectorId
).transactionStarted
= false;
1076 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
1077 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;