1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { CurrentOutType
, VoltageOut
} from
'../types/ChargingStationTemplate';
4 import Connectors
, { Connector
} from
'../types/Connectors';
5 import { PerformanceObserver
, performance
} from
'perf_hooks';
6 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
7 import WebSocket
, { MessageEvent
} from
'ws';
9 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
10 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
11 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
12 import ChargingStationInfo from
'../types/ChargingStationInfo';
13 import Configuration from
'../utils/Configuration';
14 import Constants from
'../utils/Constants';
15 import FileUtils from
'../utils/FileUtils';
16 import { MessageType
} from
'../types/ocpp/MessageType';
17 import { MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
18 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCCP16IncomingRequestService';
19 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
20 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
21 import OCPPError from
'./OcppError';
22 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
23 import OCPPRequestService from
'./ocpp/OCPPRequestService';
24 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
25 import PerformanceStatistics from
'../utils/PerformanceStatistics';
26 import { StandardParametersKey
} from
'../types/ocpp/Configuration';
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 getTransactionMeterStop(transactionId
: number): number | undefined {
153 for (const connector
in this.connectors
) {
154 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
155 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
160 public getAuthorizeRemoteTxRequests(): boolean {
161 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
162 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
165 public getLocalAuthListEnabled(): boolean {
166 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
167 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
170 public restartWebSocketPing(): void {
171 // Stop WebSocket ping
172 this.stopWebSocketPing();
173 // Start WebSocket ping
174 this.startWebSocketPing();
177 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
178 return this.stationInfo
.AutomaticTransactionGenerator
.requireAuthorize
?? true;
181 public startHeartbeat(): void {
182 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
183 // eslint-disable-next-line @typescript-eslint/no-misused-promises
184 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
185 await this.ocppRequestService
.sendHeartbeat();
186 }, this.getHeartbeatInterval());
187 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
188 } else if (this.heartbeatSetInterval
) {
189 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
191 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
195 public restartHeartbeat(): void {
197 this.stopHeartbeat();
199 this.startHeartbeat();
202 public startMeterValues(connectorId
: number, interval
: number): void {
203 if (connectorId
=== 0) {
204 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
207 if (!this.getConnector(connectorId
)) {
208 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
211 if (!this.getConnector(connectorId
)?.transactionStarted
) {
212 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
214 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
215 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
219 // eslint-disable-next-line @typescript-eslint/no-misused-promises
220 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
221 if (this.getEnableStatistics()) {
222 const sendMeterValues
= performance
.timerify(this.ocppRequestService
.sendMeterValues
);
223 this.performanceObserver
.observe({
224 entryTypes
: ['function'],
226 await sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
228 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
232 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
236 public start(): void {
237 this.openWSConnection();
238 // Monitor authorization file
239 this.startAuthorizationFileMonitoring();
240 // Monitor station template file
241 this.startStationTemplateFileMonitoring();
242 // Handle Socket incoming messages
243 this.wsConnection
.on('message', this.onMessage
.bind(this));
244 // Handle Socket error
245 this.wsConnection
.on('error', this.onError
.bind(this));
246 // Handle Socket close
247 this.wsConnection
.on('close', this.onClose
.bind(this));
248 // Handle Socket opening connection
249 this.wsConnection
.on('open', this.onOpen
.bind(this));
250 // Handle Socket ping
251 this.wsConnection
.on('ping', this.onPing
.bind(this));
252 // Handle Socket pong
253 this.wsConnection
.on('pong', this.onPong
.bind(this));
256 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
257 // Stop message sequence
258 await this.stopMessageSequence(reason
);
259 for (const connector
in this.connectors
) {
260 if (Utils
.convertToInt(connector
) > 0) {
261 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
262 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
265 if (this.isWebSocketOpen()) {
266 this.wsConnection
.close();
268 this.bootNotificationResponse
= null;
269 this.hasStopped
= true;
272 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
273 const configurationKey
: ConfigurationKey
| undefined = this.configuration
.configurationKey
.find((configElement
) => {
274 if (caseInsensitive
) {
275 return configElement
.key
.toLowerCase() === key
.toLowerCase();
277 return configElement
.key
=== key
;
279 return configurationKey
;
282 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
283 const keyFound
= this.getConfigurationKey(key
);
285 this.configuration
.configurationKey
.push({
293 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
297 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
298 const keyFound
= this.getConfigurationKey(key
);
300 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
301 this.configuration
.configurationKey
[keyIndex
].value
= value
;
303 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
307 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): boolean {
308 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
309 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
310 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
311 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
312 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
317 this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
321 public resetTransactionOnConnector(connectorId
: number): void {
322 this.initTransactionOnConnector(connectorId
);
323 this.stopMeterValues(connectorId
);
326 public addToMessageQueue(message
: string): void {
328 // Handle dups in message queue
329 for (const bufferedMessage
of this.messageQueue
) {
330 // Message already in the queue
331 if (message
=== bufferedMessage
) {
338 this.messageQueue
.push(message
);
342 private flushMessageQueue() {
343 if (!Utils
.isEmptyArray(this.messageQueue
)) {
344 this.messageQueue
.forEach((message
, index
) => {
345 this.messageQueue
.splice(index
, 1);
346 this.wsConnection
.send(message
);
351 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
352 // In case of multiple instances: add instance index to charging station id
353 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
? process
.env
.CF_INSTANCE_INDEX
: 0;
354 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
355 const idSuffix
= stationTemplate
.nameSuffix
? stationTemplate
.nameSuffix
: '';
356 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
359 private buildStationInfo(): ChargingStationInfo
{
360 let stationTemplateFromFile
: ChargingStationTemplate
;
362 // Load template file
363 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
364 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
365 fs
.closeSync(fileDescriptor
);
367 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
369 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
370 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
371 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
372 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
374 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
376 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
377 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
381 private getOCPPVersion(): OCPPVersion
{
382 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
385 private handleUnsupportedVersion(version
: OCPPVersion
) {
386 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
387 logger
.error(errMsg
);
388 throw new Error(errMsg
);
391 private initialize(): void {
392 this.stationInfo
= this.buildStationInfo();
393 this.bootNotificationRequest
= {
394 chargePointModel
: this.stationInfo
.chargePointModel
,
395 chargePointVendor
: this.stationInfo
.chargePointVendor
,
396 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
397 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
399 this.configuration
= this.getTemplateChargingStationConfiguration();
400 this.supervisionUrl
= this.getSupervisionURL();
401 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
402 // Build connectors if needed
403 const maxConnectors
= this.getMaxNumberOfConnectors();
404 if (maxConnectors
<= 0) {
405 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
407 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
408 if (templateMaxConnectors
<= 0) {
409 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
411 if (!this.stationInfo
.Connectors
[0]) {
412 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
415 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
416 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
417 this.stationInfo
.randomConnectors
= true;
419 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
420 // FIXME: Handle shrinking the number of connectors
421 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
422 this.connectorsConfigurationHash
= connectorsConfigHash
;
423 // Add connector Id 0
424 let lastConnector
= '0';
425 for (lastConnector
in this.stationInfo
.Connectors
) {
426 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
427 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
428 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
429 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
430 this.connectors
[lastConnector
].chargingProfiles
= [];
434 // Generate all connectors
435 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
436 for (let index
= 1; index
<= maxConnectors
; index
++) {
437 const randConnectorID
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
438 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorID
]);
439 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
440 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
441 this.connectors
[index
].chargingProfiles
= [];
446 // Avoid duplication of connectors related information
447 delete this.stationInfo
.Connectors
;
448 // Initialize transaction attributes on connectors
449 for (const connector
in this.connectors
) {
450 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
451 this.initTransactionOnConnector(Utils
.convertToInt(connector
));
454 switch (this.getOCPPVersion()) {
455 case OCPPVersion
.VERSION_16
:
456 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
457 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
460 this.handleUnsupportedVersion(this.getOCPPVersion());
464 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
465 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
466 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
468 this.stationInfo
.powerDivider
= this.getPowerDivider();
469 if (this.getEnableStatistics()) {
470 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
);
471 this.performanceObserver
= new PerformanceObserver((list
) => {
472 const entry
= list
.getEntries()[0];
473 this.performanceStatistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
474 this.performanceObserver
.disconnect();
479 private async onOpen(): Promise
<void> {
480 logger
.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
481 if (!this.isRegistered()) {
482 // Send BootNotification
483 let registrationRetryCount
= 0;
485 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
486 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
487 if (!this.isRegistered()) {
488 registrationRetryCount
++;
489 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
491 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
493 if (this.isRegistered()) {
494 await this.startMessageSequence();
495 this.hasStopped
&& (this.hasStopped
= false);
496 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
497 this.flushMessageQueue();
500 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
502 this.autoReconnectRetryCount
= 0;
503 this.hasSocketRestarted
= false;
506 private async onClose(closeEvent
: any): Promise
<void> {
507 switch (closeEvent
) {
508 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
509 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
510 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
511 this.autoReconnectRetryCount
= 0;
513 default: // Abnormal close
514 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
515 await this.reconnect(closeEvent
);
520 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
521 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
522 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
523 let rejectCallback
: (error
: OCPPError
) => void;
524 let requestPayload
: Record
<string, unknown
>;
528 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
530 // Check the Type of message
531 switch (messageType
) {
533 case MessageType
.CALL_MESSAGE
:
534 if (this.getEnableStatistics()) {
535 this.performanceStatistics
.addMessage(commandName
, messageType
);
538 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
541 case MessageType
.CALL_RESULT_MESSAGE
:
543 if (Utils
.isIterable(this.requests
[messageId
])) {
544 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
546 throw new Error(`Response request for message id ${messageId} is not iterable`);
548 if (!responseCallback
) {
550 throw new Error(`Response request for unknown message id ${messageId}`);
552 delete this.requests
[messageId
];
553 responseCallback(commandName
, requestPayload
);
556 case MessageType
.CALL_ERROR_MESSAGE
:
557 if (!this.requests
[messageId
]) {
559 throw new Error(`Error request for unknown message id ${messageId}`);
561 if (Utils
.isIterable(this.requests
[messageId
])) {
562 [, rejectCallback
] = this.requests
[messageId
];
564 throw new Error(`Error request for message id ${messageId} is not iterable`);
566 delete this.requests
[messageId
];
567 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
571 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
572 logger
.error(errMsg
);
573 throw new Error(errMsg
);
577 logger
.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
579 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
583 private onPing(): void {
584 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
587 private onPong(): void {
588 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
591 private async onError(errorEvent
: any): Promise
<void> {
592 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
593 // switch (errorEvent.code) {
594 // case 'ECONNREFUSED':
595 // await this._reconnect(errorEvent);
600 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
601 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
604 private getAuthorizationFile(): string | undefined {
605 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
608 private getAuthorizedTags(): string[] {
609 let authorizedTags
: string[] = [];
610 const authorizationFile
= this.getAuthorizationFile();
611 if (authorizationFile
) {
613 // Load authorization file
614 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
615 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
616 fs
.closeSync(fileDescriptor
);
618 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
621 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
623 return authorizedTags
;
626 private getUseConnectorId0(): boolean | undefined {
627 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
630 private getNumberOfRunningTransactions(): number {
632 for (const connector
in this.connectors
) {
633 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
641 private getConnectionTimeout(): number | undefined {
642 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
643 return this.stationInfo
.connectionTimeout
;
645 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
646 return Configuration
.getConnectionTimeout();
651 // -1 for unlimited, 0 for disabling
652 private getAutoReconnectMaxRetries(): number | undefined {
653 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
654 return this.stationInfo
.autoReconnectMaxRetries
;
656 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
657 return Configuration
.getAutoReconnectMaxRetries();
663 private getRegistrationMaxRetries(): number | undefined {
664 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
665 return this.stationInfo
.registrationMaxRetries
;
670 private getPowerDivider(): number {
671 let powerDivider
= this.getNumberOfConnectors();
672 if (this.stationInfo
.powerSharedByConnectors
) {
673 powerDivider
= this.getNumberOfRunningTransactions();
678 private getTemplateMaxNumberOfConnectors(): number {
679 return Object.keys(this.stationInfo
.Connectors
).length
;
682 private getMaxNumberOfConnectors(): number {
683 let maxConnectors
= 0;
684 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
685 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
686 // Distribute evenly the number of connectors
687 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
688 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
689 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
691 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
693 return maxConnectors
;
696 private getNumberOfConnectors(): number {
697 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
700 private async startMessageSequence(): Promise
<void> {
701 // Start WebSocket ping
702 this.startWebSocketPing();
704 this.startHeartbeat();
705 // Initialize connectors status
706 for (const connector
in this.connectors
) {
707 if (Utils
.convertToInt(connector
) === 0) {
709 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
710 // Send status in template at startup
711 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
712 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
713 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
714 // Send status in template after reset
715 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
716 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
717 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
718 // Send previous status at template reload
719 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
721 // Send default status
722 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
723 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
727 this.startAutomaticTransactionGenerator();
728 if (this.getEnableStatistics()) {
729 this.performanceStatistics
.start();
733 private startAutomaticTransactionGenerator() {
734 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
735 if (!this.automaticTransactionGeneration
) {
736 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
738 if (this.automaticTransactionGeneration
.timeToStop
) {
739 // The ATG might sleep
740 void this.automaticTransactionGeneration
.start();
745 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
746 // Stop WebSocket ping
747 this.stopWebSocketPing();
749 this.stopHeartbeat();
751 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
752 this.automaticTransactionGeneration
&&
753 !this.automaticTransactionGeneration
.timeToStop
) {
754 await this.automaticTransactionGeneration
.stop(reason
);
756 for (const connector
in this.connectors
) {
757 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
758 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
759 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getTransactionMeterStop(transactionId
), this.getTransactionIdTag(transactionId
), reason
);
765 private startWebSocketPing(): void {
766 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
767 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
769 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
770 this.webSocketPingSetInterval
= setInterval(() => {
771 if (this.isWebSocketOpen()) {
772 this.wsConnection
.ping((): void => { });
774 }, webSocketPingInterval
* 1000);
775 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
776 } else if (this.webSocketPingSetInterval
) {
777 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
779 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
783 private stopWebSocketPing(): void {
784 if (this.webSocketPingSetInterval
) {
785 clearInterval(this.webSocketPingSetInterval
);
789 private getSupervisionURL(): string {
790 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
792 if (!Utils
.isEmptyArray(supervisionUrls
)) {
793 if (Configuration
.getDistributeStationsToTenantsEqually()) {
794 indexUrl
= this.index
% supervisionUrls
.length
;
797 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
799 return supervisionUrls
[indexUrl
];
801 return supervisionUrls
as string;
804 private getHeartbeatInterval(): number | undefined {
805 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
806 if (HeartbeatInterval
) {
807 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
809 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
810 if (HeartBeatInterval
) {
811 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
815 private stopHeartbeat(): void {
816 if (this.heartbeatSetInterval
) {
817 clearInterval(this.heartbeatSetInterval
);
821 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
822 options
?? {} as WebSocket
.ClientOptions
;
823 options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
824 if (this.isWebSocketOpen() && forceCloseOpened
) {
825 this.wsConnection
.close();
828 switch (this.getOCPPVersion()) {
829 case OCPPVersion
.VERSION_16
:
830 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
833 this.handleUnsupportedVersion(this.getOCPPVersion());
836 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
837 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
840 private stopMeterValues(connectorId
: number) {
841 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
842 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
846 private startAuthorizationFileMonitoring(): void {
847 const authorizationFile
= this.getAuthorizationFile();
848 if (authorizationFile
) {
850 fs
.watch(authorizationFile
).on('change', (e
) => {
852 logger
.debug(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' have changed, reload');
853 // Initialize authorizedTags
854 this.authorizedTags
= this.getAuthorizedTags();
856 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
860 FileUtils
.handleFileException(this.logPrefix(), 'Authorization', authorizationFile
, error
);
863 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
+ '. Not monitoring changes');
867 private startStationTemplateFileMonitoring(): void {
869 // eslint-disable-next-line @typescript-eslint/no-misused-promises
870 fs
.watch(this.stationTemplateFile
).on('change', async (e
): Promise
<void> => {
872 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
876 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
877 this.automaticTransactionGeneration
) {
878 await this.automaticTransactionGeneration
.stop();
881 this.startAutomaticTransactionGenerator();
882 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
884 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
888 FileUtils
.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile
, error
);
892 private getReconnectExponentialDelay(): boolean | undefined {
893 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
896 private async reconnect(error
: any): Promise
<void> {
898 this.stopHeartbeat();
899 // Stop the ATG if needed
900 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
901 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
902 this.automaticTransactionGeneration
&&
903 !this.automaticTransactionGeneration
.timeToStop
) {
904 await this.automaticTransactionGeneration
.stop();
906 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
907 this.autoReconnectRetryCount
++;
908 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
909 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
910 await Utils
.sleep(reconnectDelay
);
911 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
912 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
913 this.hasSocketRestarted
= true;
914 } else if (this.getAutoReconnectMaxRetries() !== -1) {
915 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
919 private initTransactionOnConnector(connectorId
: number): void {
920 this.getConnector(connectorId
).transactionStarted
= false;
921 delete this.getConnector(connectorId
).transactionId
;
922 delete this.getConnector(connectorId
).idTag
;
923 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;