1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { CurrentOutType
, PowerUnits
, VoltageOut
} from
'../types/ChargingStationTemplate';
4 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
5 import Connectors
, { Connector
} from
'../types/Connectors';
6 import { PerformanceObserver
, performance
} from
'perf_hooks';
7 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
8 import WebSocket
, { MessageEvent
} from
'ws';
10 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
11 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
12 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
13 import ChargingStationInfo from
'../types/ChargingStationInfo';
14 import Configuration from
'../utils/Configuration';
15 import Constants from
'../utils/Constants';
16 import FileUtils from
'../utils/FileUtils';
17 import { MessageType
} from
'../types/ocpp/MessageType';
18 import { MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
19 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCCP16IncomingRequestService';
20 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
21 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
22 import OCPPError from
'./OcppError';
23 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
24 import OCPPRequestService from
'./ocpp/OCPPRequestService';
25 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
26 import PerformanceStatistics from
'../utils/PerformanceStatistics';
27 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
28 import Utils from
'../utils/Utils';
29 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
30 import crypto from
'crypto';
32 import logger from
'../utils/Logger';
33 import path from
'path';
35 export default class ChargingStation
{
36 public stationTemplateFile
: string;
37 public authorizedTags
: string[];
38 public stationInfo
!: ChargingStationInfo
;
39 public connectors
: Connectors
;
40 public configuration
!: ChargingStationConfiguration
;
41 public hasStopped
: boolean;
42 public wsConnection
!: WebSocket
;
43 public requests
: Requests
;
44 public messageQueue
: string[];
45 public performanceStatistics
!: PerformanceStatistics
;
46 public heartbeatSetInterval
!: NodeJS
.Timeout
;
47 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
48 public ocppRequestService
!: OCPPRequestService
;
49 private index
: number;
50 private bootNotificationRequest
!: BootNotificationRequest
;
51 private bootNotificationResponse
!: BootNotificationResponse
| null;
52 private connectorsConfigurationHash
!: string;
53 private supervisionUrl
!: string;
54 private wsConnectionUrl
!: string;
55 private hasSocketRestarted
: boolean;
56 private autoReconnectRetryCount
: number;
57 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
58 private performanceObserver
!: PerformanceObserver
;
59 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
61 constructor(index
: number, stationTemplateFile
: string) {
63 this.stationTemplateFile
= stationTemplateFile
;
64 this.connectors
= {} as Connectors
;
67 this.hasStopped
= false;
68 this.hasSocketRestarted
= false;
69 this.autoReconnectRetryCount
= 0;
71 this.requests
= {} as Requests
;
72 this.messageQueue
= [] as string[];
74 this.authorizedTags
= this.getAuthorizedTags();
77 public logPrefix(): string {
78 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
81 public getRandomTagId(): string {
82 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
83 return this.authorizedTags
[index
];
86 public hasAuthorizedTags(): boolean {
87 return !Utils
.isEmptyArray(this.authorizedTags
);
90 public getEnableStatistics(): boolean | undefined {
91 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
94 public getNumberOfPhases(): number | undefined {
95 switch (this.getCurrentOutType()) {
96 case CurrentOutType
.AC
:
97 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
98 case CurrentOutType
.DC
:
103 public isWebSocketOpen(): boolean {
104 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
107 public isRegistered(): boolean {
108 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
111 public isChargingStationAvailable(): boolean {
112 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
115 public isConnectorAvailable(id
: number): boolean {
116 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
119 public getConnector(id
: number): Connector
{
120 return this.connectors
[id
];
123 public getCurrentOutType(): CurrentOutType
| undefined {
124 return !Utils
.isUndefined(this.stationInfo
.currentOutType
) ? this.stationInfo
.currentOutType
: CurrentOutType
.AC
;
127 public getVoltageOut(): number | undefined {
128 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
129 let defaultVoltageOut
: number;
130 switch (this.getCurrentOutType()) {
131 case CurrentOutType
.AC
:
132 defaultVoltageOut
= VoltageOut
.VOLTAGE_230
;
134 case CurrentOutType
.DC
:
135 defaultVoltageOut
= VoltageOut
.VOLTAGE_400
;
138 logger
.error(errMsg
);
141 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
144 public getTransactionIdTag(transactionId
: number): string | undefined {
145 for (const connector
in this.connectors
) {
146 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
147 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
152 public getOutOfOrderEndMeterValues(): boolean {
153 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
156 public getBeginEndMeterValues(): boolean {
157 return this.stationInfo
.beginEndMeterValues
?? false;
160 public getMeteringPerTransaction(): boolean {
161 return this.stationInfo
.meteringPerTransaction
?? true;
164 public getTransactionDataMeterValues(): boolean {
165 return this.stationInfo
.transactionDataMeterValues
?? false;
168 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
169 if (this.getMeteringPerTransaction()) {
170 for (const connector
in this.connectors
) {
171 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
172 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
176 for (const connector
in this.connectors
) {
177 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
178 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
183 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
184 if (this.getMeteringPerTransaction()) {
185 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
187 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
190 public getAuthorizeRemoteTxRequests(): boolean {
191 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
192 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
195 public getLocalAuthListEnabled(): boolean {
196 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
197 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
200 public restartWebSocketPing(): void {
201 // Stop WebSocket ping
202 this.stopWebSocketPing();
203 // Start WebSocket ping
204 this.startWebSocketPing();
207 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
208 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
211 public startHeartbeat(): void {
212 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
213 // eslint-disable-next-line @typescript-eslint/no-misused-promises
214 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
215 await this.ocppRequestService
.sendHeartbeat();
216 }, this.getHeartbeatInterval());
217 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
218 } else if (this.heartbeatSetInterval
) {
219 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
221 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
225 public restartHeartbeat(): void {
227 this.stopHeartbeat();
229 this.startHeartbeat();
232 public startMeterValues(connectorId
: number, interval
: number): void {
233 if (connectorId
=== 0) {
234 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
237 if (!this.getConnector(connectorId
)) {
238 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
241 if (!this.getConnector(connectorId
)?.transactionStarted
) {
242 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
244 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
245 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
249 // eslint-disable-next-line @typescript-eslint/no-misused-promises
250 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
251 if (this.getEnableStatistics()) {
252 const sendMeterValues
= performance
.timerify(this.ocppRequestService
.sendMeterValues
);
253 this.performanceObserver
.observe({
254 entryTypes
: ['function'],
256 await sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
258 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
262 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
266 public start(): void {
267 this.openWSConnection();
268 // Monitor authorization file
269 this.startAuthorizationFileMonitoring();
270 // Monitor station template file
271 this.startStationTemplateFileMonitoring();
272 // Handle Socket incoming messages
273 this.wsConnection
.on('message', this.onMessage
.bind(this));
274 // Handle Socket error
275 this.wsConnection
.on('error', this.onError
.bind(this));
276 // Handle Socket close
277 this.wsConnection
.on('close', this.onClose
.bind(this));
278 // Handle Socket opening connection
279 this.wsConnection
.on('open', this.onOpen
.bind(this));
280 // Handle Socket ping
281 this.wsConnection
.on('ping', this.onPing
.bind(this));
282 // Handle Socket pong
283 this.wsConnection
.on('pong', this.onPong
.bind(this));
286 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
287 // Stop message sequence
288 await this.stopMessageSequence(reason
);
289 for (const connector
in this.connectors
) {
290 if (Utils
.convertToInt(connector
) > 0) {
291 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
292 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
295 if (this.isWebSocketOpen()) {
296 this.wsConnection
.close();
298 this.bootNotificationResponse
= null;
299 this.hasStopped
= true;
302 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
303 const configurationKey
: ConfigurationKey
| undefined = this.configuration
.configurationKey
.find((configElement
) => {
304 if (caseInsensitive
) {
305 return configElement
.key
.toLowerCase() === key
.toLowerCase();
307 return configElement
.key
=== key
;
309 return configurationKey
;
312 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
313 const keyFound
= this.getConfigurationKey(key
);
315 this.configuration
.configurationKey
.push({
323 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
327 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
328 const keyFound
= this.getConfigurationKey(key
);
330 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
331 this.configuration
.configurationKey
[keyIndex
].value
= value
;
333 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
337 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): boolean {
338 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
339 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
340 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
341 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
342 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
347 this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
351 public resetTransactionOnConnector(connectorId
: number): void {
352 this.getConnector(connectorId
).transactionStarted
= false;
353 delete this.getConnector(connectorId
).transactionId
;
354 delete this.getConnector(connectorId
).idTag
;
355 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
356 delete this.getConnector(connectorId
).transactionBeginMeterValue
;
357 this.stopMeterValues(connectorId
);
360 public addToMessageQueue(message
: string): void {
362 // Handle dups in message queue
363 for (const bufferedMessage
of this.messageQueue
) {
364 // Message already in the queue
365 if (message
=== bufferedMessage
) {
372 this.messageQueue
.push(message
);
376 private flushMessageQueue() {
377 if (!Utils
.isEmptyArray(this.messageQueue
)) {
378 this.messageQueue
.forEach((message
, index
) => {
379 this.messageQueue
.splice(index
, 1);
380 this.wsConnection
.send(message
);
385 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
386 // In case of multiple instances: add instance index to charging station id
387 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
? process
.env
.CF_INSTANCE_INDEX
: 0;
388 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
389 const idSuffix
= stationTemplate
.nameSuffix
? stationTemplate
.nameSuffix
: '';
390 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
393 private buildStationInfo(): ChargingStationInfo
{
394 let stationTemplateFromFile
: ChargingStationTemplate
;
396 // Load template file
397 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
398 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
399 fs
.closeSync(fileDescriptor
);
401 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
403 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
?? {} as ChargingStationInfo
;
404 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
405 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
406 const powerArrayRandomIndex
= Math.floor(Math.random() * stationTemplateFromFile
.power
.length
);
407 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
408 ? stationTemplateFromFile
.power
[powerArrayRandomIndex
] * 1000
409 : stationTemplateFromFile
.power
[powerArrayRandomIndex
];
411 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number;
412 stationInfo
.maxPower
= stationTemplateFromFile
.powerUnit
=== PowerUnits
.KILO_WATT
413 ? stationTemplateFromFile
.power
* 1000
414 : stationTemplateFromFile
.power
;
416 delete stationInfo
.power
;
417 delete stationInfo
.powerUnit
;
418 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
419 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
423 private getOCPPVersion(): OCPPVersion
{
424 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
427 private handleUnsupportedVersion(version
: OCPPVersion
) {
428 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
429 logger
.error(errMsg
);
430 throw new Error(errMsg
);
433 private initialize(): void {
434 this.stationInfo
= this.buildStationInfo();
435 this.bootNotificationRequest
= {
436 chargePointModel
: this.stationInfo
.chargePointModel
,
437 chargePointVendor
: this.stationInfo
.chargePointVendor
,
438 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
439 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
441 this.configuration
= this.getTemplateChargingStationConfiguration();
442 this.supervisionUrl
= this.getSupervisionURL();
443 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
444 // Build connectors if needed
445 const maxConnectors
= this.getMaxNumberOfConnectors();
446 if (maxConnectors
<= 0) {
447 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
449 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
450 if (templateMaxConnectors
<= 0) {
451 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
453 if (!this.stationInfo
.Connectors
[0]) {
454 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
457 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
458 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
459 this.stationInfo
.randomConnectors
= true;
461 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
462 // FIXME: Handle shrinking the number of connectors
463 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
464 this.connectorsConfigurationHash
= connectorsConfigHash
;
465 // Add connector Id 0
466 let lastConnector
= '0';
467 for (lastConnector
in this.stationInfo
.Connectors
) {
468 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
469 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
470 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
471 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
472 this.connectors
[lastConnector
].chargingProfiles
= [];
476 // Generate all connectors
477 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
478 for (let index
= 1; index
<= maxConnectors
; index
++) {
479 const randConnectorID
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
480 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorID
]);
481 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
482 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
483 this.connectors
[index
].chargingProfiles
= [];
488 // Avoid duplication of connectors related information
489 delete this.stationInfo
.Connectors
;
490 // Initialize transaction attributes on connectors
491 for (const connector
in this.connectors
) {
492 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
493 this.initTransactionAttributesOnConnector(Utils
.convertToInt(connector
));
496 switch (this.getOCPPVersion()) {
497 case OCPPVersion
.VERSION_16
:
498 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
499 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
502 this.handleUnsupportedVersion(this.getOCPPVersion());
506 if (!this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
)) {
507 this.addConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`);
509 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
510 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
511 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
513 if (!this.getConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
)) {
514 const connectorPhaseRotation
= [];
515 for (const connector
in this.connectors
) {
517 if (Utils
.convertToInt(connector
) === 0 && this.getNumberOfPhases() === 0) {
518 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
519 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 0) {
520 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
522 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 1) {
523 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`);
524 } else if (Utils
.convertToInt(connector
) > 0 && this.getNumberOfPhases() === 3) {
525 connectorPhaseRotation
.push(`${connector}.${ConnectorPhaseRotation.RST}`);
528 this.addConfigurationKey(StandardParametersKey
.ConnectorPhaseRotation
, connectorPhaseRotation
.toString());
530 if (!this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
)) {
531 this.addConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
, 'true');
533 if (!this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
)
534 && this.getConfigurationKey(StandardParametersKey
.SupportedFeatureProfiles
).value
.includes(SupportedFeatureProfiles
.Local_Auth_List_Management
)) {
535 this.addConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
, 'false');
537 this.stationInfo
.powerDivider
= this.getPowerDivider();
538 if (this.getEnableStatistics()) {
539 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
);
540 this.performanceObserver
= new PerformanceObserver((list
) => {
541 const entry
= list
.getEntries()[0];
542 this.performanceStatistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
543 this.performanceObserver
.disconnect();
548 private async onOpen(): Promise
<void> {
549 logger
.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
550 if (!this.isRegistered()) {
551 // Send BootNotification
552 let registrationRetryCount
= 0;
554 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
555 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
556 if (!this.isRegistered()) {
557 registrationRetryCount
++;
558 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
560 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
562 if (this.isRegistered()) {
563 await this.startMessageSequence();
564 this.hasStopped
&& (this.hasStopped
= false);
565 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
566 this.flushMessageQueue();
569 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
571 this.autoReconnectRetryCount
= 0;
572 this.hasSocketRestarted
= false;
575 private async onClose(closeEvent
: any): Promise
<void> {
576 switch (closeEvent
) {
577 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
578 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
579 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
580 this.autoReconnectRetryCount
= 0;
582 default: // Abnormal close
583 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
584 await this.reconnect(closeEvent
);
589 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
590 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
591 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
592 let rejectCallback
: (error
: OCPPError
) => void;
593 let requestPayload
: Record
<string, unknown
>;
597 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
598 // Check the Type of message
599 switch (messageType
) {
601 case MessageType
.CALL_MESSAGE
:
602 if (this.getEnableStatistics()) {
603 this.performanceStatistics
.addMessage(commandName
, messageType
);
606 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
609 case MessageType
.CALL_RESULT_MESSAGE
:
611 if (Utils
.isIterable(this.requests
[messageId
])) {
612 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
614 throw new Error(`Response request for message id ${messageId} is not iterable`);
616 if (!responseCallback
) {
618 throw new Error(`Response request for unknown message id ${messageId}`);
620 delete this.requests
[messageId
];
621 responseCallback(commandName
, requestPayload
);
624 case MessageType
.CALL_ERROR_MESSAGE
:
625 if (!this.requests
[messageId
]) {
627 throw new Error(`Error request for unknown message id ${messageId}`);
629 if (Utils
.isIterable(this.requests
[messageId
])) {
630 [, rejectCallback
] = this.requests
[messageId
];
632 throw new Error(`Error request for message id ${messageId} is not iterable`);
634 delete this.requests
[messageId
];
635 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
639 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
640 logger
.error(errMsg
);
641 throw new Error(errMsg
);
645 logger
.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
647 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
651 private onPing(): void {
652 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
655 private onPong(): void {
656 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
659 private async onError(errorEvent
: any): Promise
<void> {
660 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
661 // switch (errorEvent.code) {
662 // case 'ECONNREFUSED':
663 // await this._reconnect(errorEvent);
668 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
669 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
672 private getAuthorizationFile(): string | undefined {
673 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
676 private getAuthorizedTags(): string[] {
677 let authorizedTags
: string[] = [];
678 const authorizationFile
= this.getAuthorizationFile();
679 if (authorizationFile
) {
681 // Load authorization file
682 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
683 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
684 fs
.closeSync(fileDescriptor
);
686 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
689 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
691 return authorizedTags
;
694 private getUseConnectorId0(): boolean | undefined {
695 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
698 private getNumberOfRunningTransactions(): number {
700 for (const connector
in this.connectors
) {
701 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
709 private getConnectionTimeout(): number | undefined {
710 if (this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
)) {
711 return parseInt(this.getConfigurationKey(StandardParametersKey
.ConnectionTimeOut
).value
) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
;
713 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
714 return this.stationInfo
.connectionTimeout
;
716 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
717 return Configuration
.getConnectionTimeout();
719 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
722 // -1 for unlimited, 0 for disabling
723 private getAutoReconnectMaxRetries(): number | undefined {
724 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
725 return this.stationInfo
.autoReconnectMaxRetries
;
727 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
728 return Configuration
.getAutoReconnectMaxRetries();
734 private getRegistrationMaxRetries(): number | undefined {
735 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
736 return this.stationInfo
.registrationMaxRetries
;
741 private getPowerDivider(): number {
742 let powerDivider
= this.getNumberOfConnectors();
743 if (this.stationInfo
.powerSharedByConnectors
) {
744 powerDivider
= this.getNumberOfRunningTransactions();
749 private getTemplateMaxNumberOfConnectors(): number {
750 return Object.keys(this.stationInfo
.Connectors
).length
;
753 private getMaxNumberOfConnectors(): number {
754 let maxConnectors
= 0;
755 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
756 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
757 // Distribute evenly the number of connectors
758 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
759 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
760 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
762 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
764 return maxConnectors
;
767 private getNumberOfConnectors(): number {
768 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
771 private async startMessageSequence(): Promise
<void> {
772 // Start WebSocket ping
773 this.startWebSocketPing();
775 this.startHeartbeat();
776 // Initialize connectors status
777 for (const connector
in this.connectors
) {
778 if (Utils
.convertToInt(connector
) === 0) {
780 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
781 // Send status in template at startup
782 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
783 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
784 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
785 // Send status in template after reset
786 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
787 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
788 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
789 // Send previous status at template reload
790 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
792 // Send default status
793 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
794 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
798 this.startAutomaticTransactionGenerator();
799 if (this.getEnableStatistics()) {
800 this.performanceStatistics
.start();
804 private startAutomaticTransactionGenerator() {
805 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
806 if (!this.automaticTransactionGeneration
) {
807 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
809 if (this.automaticTransactionGeneration
.timeToStop
) {
810 // The ATG might sleep
811 void this.automaticTransactionGeneration
.start();
816 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
817 // Stop WebSocket ping
818 this.stopWebSocketPing();
820 this.stopHeartbeat();
822 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
823 this.automaticTransactionGeneration
&&
824 !this.automaticTransactionGeneration
.timeToStop
) {
825 await this.automaticTransactionGeneration
.stop(reason
);
827 for (const connector
in this.connectors
) {
828 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
829 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
830 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getEnergyActiveImportRegisterByTransactionId(transactionId
),
831 this.getTransactionIdTag(transactionId
), reason
);
837 private startWebSocketPing(): void {
838 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
839 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
841 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
842 this.webSocketPingSetInterval
= setInterval(() => {
843 if (this.isWebSocketOpen()) {
844 this.wsConnection
.ping((): void => { });
846 }, webSocketPingInterval
* 1000);
847 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
848 } else if (this.webSocketPingSetInterval
) {
849 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
851 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
855 private stopWebSocketPing(): void {
856 if (this.webSocketPingSetInterval
) {
857 clearInterval(this.webSocketPingSetInterval
);
861 private getSupervisionURL(): string {
862 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
864 if (!Utils
.isEmptyArray(supervisionUrls
)) {
865 if (Configuration
.getDistributeStationsToTenantsEqually()) {
866 indexUrl
= this.index
% supervisionUrls
.length
;
869 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
871 return supervisionUrls
[indexUrl
];
873 return supervisionUrls
as string;
876 private getHeartbeatInterval(): number | undefined {
877 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
878 if (HeartbeatInterval
) {
879 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
881 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
882 if (HeartBeatInterval
) {
883 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
887 private stopHeartbeat(): void {
888 if (this.heartbeatSetInterval
) {
889 clearInterval(this.heartbeatSetInterval
);
893 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
894 options
?? {} as WebSocket
.ClientOptions
;
895 options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
896 if (this.isWebSocketOpen() && forceCloseOpened
) {
897 this.wsConnection
.close();
900 switch (this.getOCPPVersion()) {
901 case OCPPVersion
.VERSION_16
:
902 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
905 this.handleUnsupportedVersion(this.getOCPPVersion());
908 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
909 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
912 private stopMeterValues(connectorId
: number) {
913 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
914 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
918 private startAuthorizationFileMonitoring(): void {
919 const authorizationFile
= this.getAuthorizationFile();
920 if (authorizationFile
) {
922 fs
.watch(authorizationFile
).on('change', () => {
924 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
925 // Initialize authorizedTags
926 this.authorizedTags
= this.getAuthorizedTags();
928 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
932 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
935 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
939 private startStationTemplateFileMonitoring(): void {
941 // eslint-disable-next-line @typescript-eslint/no-misused-promises
942 fs
.watch(this.stationTemplateFile
).on('change', async (): Promise
<void> => {
944 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
948 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
949 this.automaticTransactionGeneration
) {
950 await this.automaticTransactionGeneration
.stop();
953 this.startAutomaticTransactionGenerator();
954 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
956 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
960 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
964 private getReconnectExponentialDelay(): boolean | undefined {
965 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
968 private async reconnect(error
: any): Promise
<void> {
970 this.stopHeartbeat();
971 // Stop the ATG if needed
972 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
973 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
974 this.automaticTransactionGeneration
&&
975 !this.automaticTransactionGeneration
.timeToStop
) {
976 await this.automaticTransactionGeneration
.stop();
978 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
979 this.autoReconnectRetryCount
++;
980 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
981 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
982 await Utils
.sleep(reconnectDelay
);
983 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
984 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
985 this.hasSocketRestarted
= true;
986 } else if (this.getAutoReconnectMaxRetries() !== -1) {
987 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
991 private initTransactionAttributesOnConnector(connectorId
: number): void {
992 this.getConnector(connectorId
).transactionStarted
= false;
993 this.getConnector(connectorId
).energyActiveImportRegisterValue
= 0;
994 this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;