1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { PowerOutType
, 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 { MessageType
} from
'../types/ocpp/MessageType';
16 import { MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
17 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCCP16IncomingRequestService';
18 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
19 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
20 import OCPPError from
'./OcppError';
21 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
22 import OCPPRequestService from
'./ocpp/OCPPRequestService';
23 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
24 import { StandardParametersKey
} from
'../types/ocpp/Configuration';
25 import Statistics from
'../utils/Statistics';
26 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
27 import Utils from
'../utils/Utils';
28 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
29 import crypto from
'crypto';
31 import logger from
'../utils/Logger';
33 export default class ChargingStation
{
34 public stationTemplateFile
: string;
35 public authorizedTags
: string[];
36 public stationInfo
: ChargingStationInfo
;
37 public connectors
: Connectors
;
38 public configuration
: ChargingStationConfiguration
;
39 public hasStopped
: boolean;
40 public wsConnection
: WebSocket
;
41 public requests
: Requests
;
42 public messageQueue
: string[];
43 public statistics
: Statistics
;
44 public heartbeatSetInterval
: NodeJS
.Timeout
;
45 public ocppIncomingRequestService
: OCPPIncomingRequestService
;
46 public ocppRequestService
: OCPPRequestService
;
47 private index
: number;
48 private bootNotificationRequest
: BootNotificationRequest
;
49 private bootNotificationResponse
: BootNotificationResponse
;
50 private connectorsConfigurationHash
: string;
51 private supervisionUrl
: string;
52 private wsConnectionUrl
: string;
53 private hasSocketRestarted
: boolean;
54 private autoReconnectRetryCount
: number;
55 private automaticTransactionGeneration
: AutomaticTransactionGenerator
;
56 private performanceObserver
: PerformanceObserver
;
57 private webSocketPingSetInterval
: NodeJS
.Timeout
;
59 constructor(index
: number, stationTemplateFile
: string) {
61 this.stationTemplateFile
= stationTemplateFile
;
62 this.connectors
= {} as Connectors
;
65 this.hasStopped
= false;
66 this.hasSocketRestarted
= false;
67 this.autoReconnectRetryCount
= 0;
69 this.requests
= {} as Requests
;
70 this.messageQueue
= [] as string[];
72 this.authorizedTags
= this.getAuthorizedTags();
75 public logPrefix(): string {
76 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId}:`);
79 public getRandomTagId(): string {
80 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
81 return this.authorizedTags
[index
];
84 public hasAuthorizedTags(): boolean {
85 return !Utils
.isEmptyArray(this.authorizedTags
);
88 public getEnableStatistics(): boolean {
89 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
92 public getNumberOfPhases(): number {
93 switch (this.getPowerOutType()) {
95 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
101 public isWebSocketOpen(): boolean {
102 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
105 public isRegistered(): boolean {
106 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
109 public isChargingStationAvailable(): boolean {
110 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
113 public isConnectorAvailable(id
: number): boolean {
114 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
117 public getConnector(id
: number): Connector
{
118 return this.connectors
[id
];
121 public getPowerOutType(): PowerOutType
{
122 return !Utils
.isUndefined(this.stationInfo
.powerOutType
) ? this.stationInfo
.powerOutType
: PowerOutType
.AC
;
125 public getVoltageOut(): number {
126 const errMsg
= `${this.logPrefix()} Unknown ${this.getPowerOutType()} powerOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
127 let defaultVoltageOut
: number;
128 switch (this.getPowerOutType()) {
129 case PowerOutType
.AC
:
130 defaultVoltageOut
= VoltageOut
.VOLTAGE_230
;
132 case PowerOutType
.DC
:
133 defaultVoltageOut
= VoltageOut
.VOLTAGE_400
;
136 logger
.error(errMsg
);
139 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
142 public getTransactionIdTag(transactionId
: number): string {
143 for (const connector
in this.connectors
) {
144 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
145 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
150 public getTransactionMeterStop(transactionId
: number): number {
151 for (const connector
in this.connectors
) {
152 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
153 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
158 public getAuthorizeRemoteTxRequests(): boolean {
159 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
160 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
163 public getLocalAuthListEnabled(): boolean {
164 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
165 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
168 public restartWebSocketPing(): void {
169 // Stop WebSocket ping
170 this.stopWebSocketPing();
171 // Start WebSocket ping
172 this.startWebSocketPing();
175 public startHeartbeat(): void {
176 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
177 // eslint-disable-next-line @typescript-eslint/no-misused-promises
178 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
179 await this.ocppRequestService
.sendHeartbeat();
180 }, this.getHeartbeatInterval());
181 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
182 } else if (this.heartbeatSetInterval
) {
183 logger
.info(this.logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()) + ' already started');
185 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
189 public restartHeartbeat(): void {
191 this.stopHeartbeat();
193 this.startHeartbeat();
196 public startMeterValues(connectorId
: number, interval
: number): void {
197 if (connectorId
=== 0) {
198 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
201 if (!this.getConnector(connectorId
)) {
202 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
205 if (!this.getConnector(connectorId
)?.transactionStarted
) {
206 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
208 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
209 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
213 // eslint-disable-next-line @typescript-eslint/no-misused-promises
214 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
215 if (this.getEnableStatistics()) {
216 const sendMeterValues
= performance
.timerify(this.ocppRequestService
.sendMeterValues
);
217 this.performanceObserver
.observe({
218 entryTypes
: ['function'],
220 await sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
222 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
226 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
230 public start(): void {
231 this.openWSConnection();
232 // Monitor authorization file
233 this.startAuthorizationFileMonitoring();
234 // Monitor station template file
235 this.startStationTemplateFileMonitoring();
236 // Handle Socket incoming messages
237 this.wsConnection
.on('message', this.onMessage
.bind(this));
238 // Handle Socket error
239 this.wsConnection
.on('error', this.onError
.bind(this));
240 // Handle Socket close
241 this.wsConnection
.on('close', this.onClose
.bind(this));
242 // Handle Socket opening connection
243 this.wsConnection
.on('open', this.onOpen
.bind(this));
244 // Handle Socket ping
245 this.wsConnection
.on('ping', this.onPing
.bind(this));
246 // Handle Socket pong
247 this.wsConnection
.on('pong', this.onPong
.bind(this));
250 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
251 // Stop message sequence
252 await this.stopMessageSequence(reason
);
253 for (const connector
in this.connectors
) {
254 if (Utils
.convertToInt(connector
) > 0) {
255 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
256 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
259 if (this.isWebSocketOpen()) {
260 this.wsConnection
.close();
262 this.bootNotificationResponse
= null;
263 this.hasStopped
= true;
266 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
{
267 const configurationKey
: ConfigurationKey
= this.configuration
.configurationKey
.find((configElement
) => {
268 if (caseInsensitive
) {
269 return configElement
.key
.toLowerCase() === key
.toLowerCase();
271 return configElement
.key
=== key
;
273 return configurationKey
;
276 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
277 const keyFound
= this.getConfigurationKey(key
);
279 this.configuration
.configurationKey
.push({
287 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
291 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
292 const keyFound
= this.getConfigurationKey(key
);
294 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
295 this.configuration
.configurationKey
[keyIndex
].value
= value
;
297 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
301 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): boolean {
302 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
303 this.getConnector(connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
304 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
305 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
306 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
311 this.getConnector(connectorId
).chargingProfiles
.push(cp
);
315 public resetTransactionOnConnector(connectorId
: number): void {
316 this.initTransactionOnConnector(connectorId
);
317 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
318 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
322 public addMessageToBuffer(message
: string): void {
324 // Handle dups in buffer
325 for (const bufferedMessage
of this.messageQueue
) {
327 if (message
=== bufferedMessage
) {
334 this.messageQueue
.push(message
);
338 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
339 // In case of multiple instances: add instance index to charging station id
340 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
? process
.env
.CF_INSTANCE_INDEX
: 0;
341 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
342 const idSuffix
= stationTemplate
.nameSuffix
? stationTemplate
.nameSuffix
: '';
343 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
346 private buildStationInfo(): ChargingStationInfo
{
347 let stationTemplateFromFile
: ChargingStationTemplate
;
349 // Load template file
350 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
351 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
352 fs
.closeSync(fileDescriptor
);
354 logger
.error('Template file ' + this.stationTemplateFile
+ ' loading error: %j', error
);
357 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
358 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
359 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
360 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
362 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
364 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
365 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
369 private getOCPPVersion(): OCPPVersion
{
370 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
373 private handleUnsupportedVersion(version
: OCPPVersion
) {
374 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
375 logger
.error(errMsg
);
376 throw new Error(errMsg
);
379 private initialize(): void {
380 this.stationInfo
= this.buildStationInfo();
381 this.bootNotificationRequest
= {
382 chargePointModel
: this.stationInfo
.chargePointModel
,
383 chargePointVendor
: this.stationInfo
.chargePointVendor
,
384 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
385 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
387 this.configuration
= this.getTemplateChargingStationConfiguration();
388 this.supervisionUrl
= this.getSupervisionURL();
389 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
390 // Build connectors if needed
391 const maxConnectors
= this.getMaxNumberOfConnectors();
392 if (maxConnectors
<= 0) {
393 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
395 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
396 if (templateMaxConnectors
<= 0) {
397 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
399 if (!this.stationInfo
.Connectors
[0]) {
400 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
403 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
404 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
405 this.stationInfo
.randomConnectors
= true;
407 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
408 // FIXME: Handle shrinking the number of connectors
409 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
410 this.connectorsConfigurationHash
= connectorsConfigHash
;
411 // Add connector Id 0
412 let lastConnector
= '0';
413 for (lastConnector
in this.stationInfo
.Connectors
) {
414 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
415 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
416 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
417 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
418 this.connectors
[lastConnector
].chargingProfiles
= [];
422 // Generate all connectors
423 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
424 for (let index
= 1; index
<= maxConnectors
; index
++) {
425 const randConnectorID
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
426 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorID
]);
427 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
428 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
429 this.connectors
[index
].chargingProfiles
= [];
434 // Avoid duplication of connectors related information
435 delete this.stationInfo
.Connectors
;
436 // Initialize transaction attributes on connectors
437 for (const connector
in this.connectors
) {
438 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
439 this.initTransactionOnConnector(Utils
.convertToInt(connector
));
442 switch (this.getOCPPVersion()) {
443 case OCPPVersion
.VERSION_16
:
444 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
445 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
448 this.handleUnsupportedVersion(this.getOCPPVersion());
452 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
453 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
454 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
456 this.stationInfo
.powerDivider
= this.getPowerDivider();
457 if (this.getEnableStatistics()) {
458 this.statistics
= new Statistics(this.stationInfo
.chargingStationId
);
459 this.performanceObserver
= new PerformanceObserver((list
) => {
460 const entry
= list
.getEntries()[0];
461 this.statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
462 this.performanceObserver
.disconnect();
467 private async onOpen(): Promise
<void> {
468 logger
.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
469 if (!this.isRegistered()) {
470 // Send BootNotification
471 let registrationRetryCount
= 0;
473 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
, this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
474 if (!this.isRegistered()) {
475 registrationRetryCount
++;
476 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
478 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
480 if (this.isRegistered()) {
481 await this.startMessageSequence();
482 this.hasStopped
&& (this.hasStopped
= false);
483 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
484 if (!Utils
.isEmptyArray(this.messageQueue
)) {
485 this.messageQueue
.forEach((message
, index
) => {
486 this.messageQueue
.splice(index
, 1);
487 this.wsConnection
.send(message
);
492 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
494 this.autoReconnectRetryCount
= 0;
495 this.hasSocketRestarted
= false;
498 private async onClose(closeEvent
): Promise
<void> {
499 switch (closeEvent
) {
500 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
501 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
502 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
503 this.autoReconnectRetryCount
= 0;
505 default: // Abnormal close
506 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
507 await this.reconnect(closeEvent
);
512 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
513 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
514 let responseCallback
: (payload
?: Record
<string, unknown
> | string, requestPayload
?: Record
<string, unknown
>) => void;
515 let rejectCallback
: (error
: OCPPError
) => void;
516 let requestPayload
: Record
<string, unknown
>;
520 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
522 // Check the Type of message
523 switch (messageType
) {
525 case MessageType
.CALL_MESSAGE
:
526 if (this.getEnableStatistics()) {
527 this.statistics
.addMessage(commandName
, messageType
);
530 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
533 case MessageType
.CALL_RESULT_MESSAGE
:
535 if (Utils
.isIterable(this.requests
[messageId
])) {
536 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
538 throw new Error(`Response request for message id ${messageId} is not iterable`);
540 if (!responseCallback
) {
542 throw new Error(`Response request for unknown message id ${messageId}`);
544 delete this.requests
[messageId
];
545 responseCallback(commandName
, requestPayload
);
548 case MessageType
.CALL_ERROR_MESSAGE
:
549 if (!this.requests
[messageId
]) {
551 throw new Error(`Error request for unknown message id ${messageId}`);
553 if (Utils
.isIterable(this.requests
[messageId
])) {
554 [, rejectCallback
] = this.requests
[messageId
];
556 throw new Error(`Error request for message id ${messageId} is not iterable`);
558 delete this.requests
[messageId
];
559 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
563 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
564 logger
.error(errMsg
);
565 throw new Error(errMsg
);
569 logger
.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
571 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
575 private onPing(): void {
576 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
579 private onPong(): void {
580 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
583 private async onError(errorEvent
): Promise
<void> {
584 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
585 // pragma switch (errorEvent.code) {
586 // case 'ECONNREFUSED':
587 // await this._reconnect(errorEvent);
592 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
593 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
596 private getAuthorizationFile(): string {
597 return this.stationInfo
.authorizationFile
&& this.stationInfo
.authorizationFile
;
600 private getAuthorizedTags(): string[] {
601 let authorizedTags
: string[] = [];
602 const authorizationFile
= this.getAuthorizationFile();
603 if (authorizationFile
) {
605 // Load authorization file
606 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
607 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
608 fs
.closeSync(fileDescriptor
);
610 logger
.error(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
614 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
616 return authorizedTags
;
619 private getUseConnectorId0(): boolean {
620 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
623 private getNumberOfRunningTransactions(): number {
625 for (const connector
in this.connectors
) {
626 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
634 private getConnectionTimeout(): number {
635 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
636 return this.stationInfo
.connectionTimeout
;
638 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
639 return Configuration
.getConnectionTimeout();
644 // -1 for unlimited, 0 for disabling
645 private getAutoReconnectMaxRetries(): number {
646 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
647 return this.stationInfo
.autoReconnectMaxRetries
;
649 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
650 return Configuration
.getAutoReconnectMaxRetries();
656 private getRegistrationMaxRetries(): number {
657 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
658 return this.stationInfo
.registrationMaxRetries
;
663 private getPowerDivider(): number {
664 let powerDivider
= this.getNumberOfConnectors();
665 if (this.stationInfo
.powerSharedByConnectors
) {
666 powerDivider
= this.getNumberOfRunningTransactions();
671 private getTemplateMaxNumberOfConnectors(): number {
672 return Object.keys(this.stationInfo
.Connectors
).length
;
675 private getMaxNumberOfConnectors(): number {
676 let maxConnectors
= 0;
677 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
678 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
679 // Distribute evenly the number of connectors
680 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
681 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
682 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
684 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
686 return maxConnectors
;
689 private getNumberOfConnectors(): number {
690 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
693 private async startMessageSequence(): Promise
<void> {
694 // Start WebSocket ping
695 this.startWebSocketPing();
697 this.startHeartbeat();
698 // Initialize connectors status
699 for (const connector
in this.connectors
) {
700 if (Utils
.convertToInt(connector
) === 0) {
702 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
703 // Send status in template at startup
704 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
705 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
706 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
707 // Send status in template after reset
708 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
709 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
710 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
711 // Send previous status at template reload
712 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
714 // Send default status
715 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
716 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
720 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
721 if (!this.automaticTransactionGeneration
) {
722 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
724 if (this.automaticTransactionGeneration
.timeToStop
) {
725 await this.automaticTransactionGeneration
.start();
728 if (this.getEnableStatistics()) {
729 this.statistics
.start();
733 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
734 // Stop WebSocket ping
735 this.stopWebSocketPing();
737 this.stopHeartbeat();
739 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
740 this.automaticTransactionGeneration
&&
741 !this.automaticTransactionGeneration
.timeToStop
) {
742 await this.automaticTransactionGeneration
.stop(reason
);
744 for (const connector
in this.connectors
) {
745 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
746 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
747 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getTransactionMeterStop(transactionId
), this.getTransactionIdTag(transactionId
), reason
);
753 private startWebSocketPing(): void {
754 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
) ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
) : 0;
755 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
756 this.webSocketPingSetInterval
= setInterval(() => {
757 if (this.isWebSocketOpen()) {
758 this.wsConnection
.ping((): void => { });
760 }, webSocketPingInterval
* 1000);
761 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
762 } else if (this.webSocketPingSetInterval
) {
763 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
765 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
769 private stopWebSocketPing(): void {
770 if (this.webSocketPingSetInterval
) {
771 clearInterval(this.webSocketPingSetInterval
);
772 this.webSocketPingSetInterval
= null;
776 private getSupervisionURL(): string {
777 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
779 if (!Utils
.isEmptyArray(supervisionUrls
)) {
780 if (Configuration
.getDistributeStationsToTenantsEqually()) {
781 indexUrl
= this.index
% supervisionUrls
.length
;
784 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
786 return supervisionUrls
[indexUrl
];
788 return supervisionUrls
as string;
791 private getHeartbeatInterval(): number {
792 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
793 if (HeartbeatInterval
) {
794 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
796 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
797 if (HeartBeatInterval
) {
798 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
802 private stopHeartbeat(): void {
803 if (this.heartbeatSetInterval
) {
804 clearInterval(this.heartbeatSetInterval
);
805 this.heartbeatSetInterval
= null;
809 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
810 if (Utils
.isUndefined(options
)) {
811 options
= {} as WebSocket
.ClientOptions
;
813 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
814 options
.handshakeTimeout
= this.getConnectionTimeout() * 1000;
816 if (this.isWebSocketOpen() && forceCloseOpened
) {
817 this.wsConnection
.close();
820 switch (this.getOCPPVersion()) {
821 case OCPPVersion
.VERSION_16
:
822 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
825 this.handleUnsupportedVersion(this.getOCPPVersion());
828 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
829 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
832 private startAuthorizationFileMonitoring(): void {
833 fs
.watch(this.getAuthorizationFile()).on('change', (e
) => {
835 logger
.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
836 // Initialize authorizedTags
837 this.authorizedTags
= this.getAuthorizedTags();
839 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
844 private startStationTemplateFileMonitoring(): void {
845 // eslint-disable-next-line @typescript-eslint/no-misused-promises
846 fs
.watch(this.stationTemplateFile
).on('change', async (e
): Promise
<void> => {
848 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
852 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
853 this.automaticTransactionGeneration
) {
854 await this.automaticTransactionGeneration
.stop();
857 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
858 if (!this.automaticTransactionGeneration
) {
859 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
861 if (this.automaticTransactionGeneration
.timeToStop
) {
862 await this.automaticTransactionGeneration
.start();
865 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
867 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
872 private getReconnectExponentialDelay(): boolean {
873 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
876 private async reconnect(error
): Promise
<void> {
878 this.stopHeartbeat();
879 // Stop the ATG if needed
880 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
881 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
882 this.automaticTransactionGeneration
&&
883 !this.automaticTransactionGeneration
.timeToStop
) {
884 this.automaticTransactionGeneration
.stop().catch(() => { });
886 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
887 this.autoReconnectRetryCount
++;
888 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
889 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
890 await Utils
.sleep(reconnectDelay
);
891 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
892 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
893 this.hasSocketRestarted
= true;
894 } else if (this.getAutoReconnectMaxRetries() !== -1) {
895 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
899 private initTransactionOnConnector(connectorId
: number): void {
900 this.getConnector(connectorId
).transactionStarted
= false;
901 this.getConnector(connectorId
).transactionId
= null;
902 this.getConnector(connectorId
).idTag
= null;
903 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;