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 { 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 PerformanceStatistics from
'../utils/PerformanceStatistics';
25 import { StandardParametersKey
} from
'../types/ocpp/Configuration';
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';
32 import path from
'path';
34 export default class ChargingStation
{
35 public stationTemplateFile
: string;
36 public authorizedTags
: string[];
37 public stationInfo
!: ChargingStationInfo
;
38 public connectors
: Connectors
;
39 public configuration
!: ChargingStationConfiguration
;
40 public hasStopped
: boolean;
41 public wsConnection
!: WebSocket
;
42 public requests
: Requests
;
43 public messageQueue
: string[];
44 public performanceStatistics
!: PerformanceStatistics
;
45 public heartbeatSetInterval
!: NodeJS
.Timeout
;
46 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
47 public ocppRequestService
!: OCPPRequestService
;
48 private index
: number;
49 private bootNotificationRequest
!: BootNotificationRequest
;
50 private bootNotificationResponse
!: BootNotificationResponse
| null;
51 private connectorsConfigurationHash
!: string;
52 private supervisionUrl
!: string;
53 private wsConnectionUrl
!: string;
54 private hasSocketRestarted
: boolean;
55 private autoReconnectRetryCount
: number;
56 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
57 private performanceObserver
!: PerformanceObserver
;
58 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
60 constructor(index
: number, stationTemplateFile
: string) {
62 this.stationTemplateFile
= stationTemplateFile
;
63 this.connectors
= {} as Connectors
;
66 this.hasStopped
= false;
67 this.hasSocketRestarted
= false;
68 this.autoReconnectRetryCount
= 0;
70 this.requests
= {} as Requests
;
71 this.messageQueue
= [] as string[];
73 this.authorizedTags
= this.getAuthorizedTags();
76 public logPrefix(): string {
77 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
80 public getRandomTagId(): string {
81 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
82 return this.authorizedTags
[index
];
85 public hasAuthorizedTags(): boolean {
86 return !Utils
.isEmptyArray(this.authorizedTags
);
89 public getEnableStatistics(): boolean | undefined {
90 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
93 public getNumberOfPhases(): number | undefined {
94 switch (this.getCurrentOutType()) {
95 case CurrentOutType
.AC
:
96 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
97 case CurrentOutType
.DC
:
102 public isWebSocketOpen(): boolean {
103 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
106 public isRegistered(): boolean {
107 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
110 public isChargingStationAvailable(): boolean {
111 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
114 public isConnectorAvailable(id
: number): boolean {
115 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
118 public getConnector(id
: number): Connector
{
119 return this.connectors
[id
];
122 public getCurrentOutType(): CurrentOutType
| undefined {
123 return !Utils
.isUndefined(this.stationInfo
.currentOutType
) ? this.stationInfo
.currentOutType
: CurrentOutType
.AC
;
126 public getVoltageOut(): number | undefined {
127 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
128 let defaultVoltageOut
: number;
129 switch (this.getCurrentOutType()) {
130 case CurrentOutType
.AC
:
131 defaultVoltageOut
= VoltageOut
.VOLTAGE_230
;
133 case CurrentOutType
.DC
:
134 defaultVoltageOut
= VoltageOut
.VOLTAGE_400
;
137 logger
.error(errMsg
);
140 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
143 public getTransactionIdTag(transactionId
: number): string | undefined {
144 for (const connector
in this.connectors
) {
145 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
146 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
151 public getTransactionMeterStop(transactionId
: number): number | undefined {
152 for (const connector
in this.connectors
) {
153 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
154 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
159 public getAuthorizeRemoteTxRequests(): boolean {
160 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
161 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
164 public getLocalAuthListEnabled(): boolean {
165 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
166 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
169 public restartWebSocketPing(): void {
170 // Stop WebSocket ping
171 this.stopWebSocketPing();
172 // Start WebSocket ping
173 this.startWebSocketPing();
176 public startHeartbeat(): void {
177 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
178 // eslint-disable-next-line @typescript-eslint/no-misused-promises
179 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
180 await this.ocppRequestService
.sendHeartbeat();
181 }, this.getHeartbeatInterval());
182 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
183 } else if (this.heartbeatSetInterval
) {
184 logger
.info(this.logPrefix() + ' Heartbeat already started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
186 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
190 public restartHeartbeat(): void {
192 this.stopHeartbeat();
194 this.startHeartbeat();
197 public startMeterValues(connectorId
: number, interval
: number): void {
198 if (connectorId
=== 0) {
199 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
202 if (!this.getConnector(connectorId
)) {
203 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
206 if (!this.getConnector(connectorId
)?.transactionStarted
) {
207 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
209 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
210 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
214 // eslint-disable-next-line @typescript-eslint/no-misused-promises
215 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
216 if (this.getEnableStatistics()) {
217 const sendMeterValues
= performance
.timerify(this.ocppRequestService
.sendMeterValues
);
218 this.performanceObserver
.observe({
219 entryTypes
: ['function'],
221 await sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
223 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
227 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`);
231 public start(): void {
232 this.openWSConnection();
233 // Monitor authorization file
234 this.startAuthorizationFileMonitoring();
235 // Monitor station template file
236 this.startStationTemplateFileMonitoring();
237 // Handle Socket incoming messages
238 this.wsConnection
.on('message', this.onMessage
.bind(this));
239 // Handle Socket error
240 this.wsConnection
.on('error', this.onError
.bind(this));
241 // Handle Socket close
242 this.wsConnection
.on('close', this.onClose
.bind(this));
243 // Handle Socket opening connection
244 this.wsConnection
.on('open', this.onOpen
.bind(this));
245 // Handle Socket ping
246 this.wsConnection
.on('ping', this.onPing
.bind(this));
247 // Handle Socket pong
248 this.wsConnection
.on('pong', this.onPong
.bind(this));
251 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
252 // Stop message sequence
253 await this.stopMessageSequence(reason
);
254 for (const connector
in this.connectors
) {
255 if (Utils
.convertToInt(connector
) > 0) {
256 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
257 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
260 if (this.isWebSocketOpen()) {
261 this.wsConnection
.close();
263 this.bootNotificationResponse
= null;
264 this.hasStopped
= true;
267 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
| undefined {
268 const configurationKey
: ConfigurationKey
| undefined = this.configuration
.configurationKey
.find((configElement
) => {
269 if (caseInsensitive
) {
270 return configElement
.key
.toLowerCase() === key
.toLowerCase();
272 return configElement
.key
=== key
;
274 return configurationKey
;
277 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
278 const keyFound
= this.getConfigurationKey(key
);
280 this.configuration
.configurationKey
.push({
288 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
292 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
293 const keyFound
= this.getConfigurationKey(key
);
295 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
296 this.configuration
.configurationKey
[keyIndex
].value
= value
;
298 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
302 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): boolean {
303 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
304 this.getConnector(connectorId
).chargingProfiles
?.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
305 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
306 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
307 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
312 this.getConnector(connectorId
).chargingProfiles
?.push(cp
);
316 public resetTransactionOnConnector(connectorId
: number): void {
317 this.initTransactionOnConnector(connectorId
);
318 this.stopMeterValues(connectorId
);
321 public addToMessageQueue(message
: string): void {
323 // Handle dups in message queue
324 for (const bufferedMessage
of this.messageQueue
) {
325 // Message already in the queue
326 if (message
=== bufferedMessage
) {
333 this.messageQueue
.push(message
);
337 private flushMessageQueue() {
338 if (!Utils
.isEmptyArray(this.messageQueue
)) {
339 this.messageQueue
.forEach((message
, index
) => {
340 this.messageQueue
.splice(index
, 1);
341 this.wsConnection
.send(message
);
346 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
347 // In case of multiple instances: add instance index to charging station id
348 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
? process
.env
.CF_INSTANCE_INDEX
: 0;
349 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
350 const idSuffix
= stationTemplate
.nameSuffix
? stationTemplate
.nameSuffix
: '';
351 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
354 private buildStationInfo(): ChargingStationInfo
{
355 let stationTemplateFromFile
: ChargingStationTemplate
;
357 // Load template file
358 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
359 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
360 fs
.closeSync(fileDescriptor
);
362 logger
.error('Template file ' + this.stationTemplateFile
+ ' loading error: %j', error
);
365 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
366 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
367 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
368 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
370 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
372 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
373 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
377 private getOCPPVersion(): OCPPVersion
{
378 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
381 private handleUnsupportedVersion(version
: OCPPVersion
) {
382 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
383 logger
.error(errMsg
);
384 throw new Error(errMsg
);
387 private initialize(): void {
388 this.stationInfo
= this.buildStationInfo();
389 this.bootNotificationRequest
= {
390 chargePointModel
: this.stationInfo
.chargePointModel
,
391 chargePointVendor
: this.stationInfo
.chargePointVendor
,
392 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
393 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
395 this.configuration
= this.getTemplateChargingStationConfiguration();
396 this.supervisionUrl
= this.getSupervisionURL();
397 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
398 // Build connectors if needed
399 const maxConnectors
= this.getMaxNumberOfConnectors();
400 if (maxConnectors
<= 0) {
401 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
403 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
404 if (templateMaxConnectors
<= 0) {
405 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
407 if (!this.stationInfo
.Connectors
[0]) {
408 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
411 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
412 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
413 this.stationInfo
.randomConnectors
= true;
415 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
416 // FIXME: Handle shrinking the number of connectors
417 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
418 this.connectorsConfigurationHash
= connectorsConfigHash
;
419 // Add connector Id 0
420 let lastConnector
= '0';
421 for (lastConnector
in this.stationInfo
.Connectors
) {
422 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
423 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
424 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
425 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
426 this.connectors
[lastConnector
].chargingProfiles
= [];
430 // Generate all connectors
431 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
432 for (let index
= 1; index
<= maxConnectors
; index
++) {
433 const randConnectorID
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
434 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorID
]);
435 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
436 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
437 this.connectors
[index
].chargingProfiles
= [];
442 // Avoid duplication of connectors related information
443 delete this.stationInfo
.Connectors
;
444 // Initialize transaction attributes on connectors
445 for (const connector
in this.connectors
) {
446 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
447 this.initTransactionOnConnector(Utils
.convertToInt(connector
));
450 switch (this.getOCPPVersion()) {
451 case OCPPVersion
.VERSION_16
:
452 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
453 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
456 this.handleUnsupportedVersion(this.getOCPPVersion());
460 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
461 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
462 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
464 this.stationInfo
.powerDivider
= this.getPowerDivider();
465 if (this.getEnableStatistics()) {
466 this.performanceStatistics
= new PerformanceStatistics(this.stationInfo
.chargingStationId
);
467 this.performanceObserver
= new PerformanceObserver((list
) => {
468 const entry
= list
.getEntries()[0];
469 this.performanceStatistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
470 this.performanceObserver
.disconnect();
475 private async onOpen(): Promise
<void> {
476 logger
.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
477 if (!this.isRegistered()) {
478 // Send BootNotification
479 let registrationRetryCount
= 0;
481 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
,
482 this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
483 if (!this.isRegistered()) {
484 registrationRetryCount
++;
485 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
487 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
489 if (this.isRegistered()) {
490 await this.startMessageSequence();
491 this.hasStopped
&& (this.hasStopped
= false);
492 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
493 this.flushMessageQueue();
496 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
498 this.autoReconnectRetryCount
= 0;
499 this.hasSocketRestarted
= false;
502 private async onClose(closeEvent
: any): Promise
<void> {
503 switch (closeEvent
) {
504 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
505 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
506 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
507 this.autoReconnectRetryCount
= 0;
509 default: // Abnormal close
510 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
511 await this.reconnect(closeEvent
);
516 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
517 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
518 let responseCallback
: (payload
: Record
<string, unknown
> | string, requestPayload
: Record
<string, unknown
>) => void;
519 let rejectCallback
: (error
: OCPPError
) => void;
520 let requestPayload
: Record
<string, unknown
>;
524 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
526 // Check the Type of message
527 switch (messageType
) {
529 case MessageType
.CALL_MESSAGE
:
530 if (this.getEnableStatistics()) {
531 this.performanceStatistics
.addMessage(commandName
, messageType
);
534 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
537 case MessageType
.CALL_RESULT_MESSAGE
:
539 if (Utils
.isIterable(this.requests
[messageId
])) {
540 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
542 throw new Error(`Response request for message id ${messageId} is not iterable`);
544 if (!responseCallback
) {
546 throw new Error(`Response request for unknown message id ${messageId}`);
548 delete this.requests
[messageId
];
549 responseCallback(commandName
, requestPayload
);
552 case MessageType
.CALL_ERROR_MESSAGE
:
553 if (!this.requests
[messageId
]) {
555 throw new Error(`Error request for unknown message id ${messageId}`);
557 if (Utils
.isIterable(this.requests
[messageId
])) {
558 [, rejectCallback
] = this.requests
[messageId
];
560 throw new Error(`Error request for message id ${messageId} is not iterable`);
562 delete this.requests
[messageId
];
563 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
567 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
568 logger
.error(errMsg
);
569 throw new Error(errMsg
);
573 logger
.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
575 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
579 private onPing(): void {
580 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
583 private onPong(): void {
584 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
587 private async onError(errorEvent
: any): Promise
<void> {
588 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
589 // pragma switch (errorEvent.code) {
590 // case 'ECONNREFUSED':
591 // await this._reconnect(errorEvent);
596 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
597 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
600 private getAuthorizationFile(): string | undefined {
601 return this.stationInfo
.authorizationFile
&& path
.join(path
.resolve(__dirname
, '../'), 'assets', path
.basename(this.stationInfo
.authorizationFile
));
604 private getAuthorizedTags(): string[] {
605 let authorizedTags
: string[] = [];
606 const authorizationFile
= this.getAuthorizationFile();
607 if (authorizationFile
) {
609 // Load authorization file
610 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
611 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
612 fs
.closeSync(fileDescriptor
);
614 logger
.error(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
618 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
620 return authorizedTags
;
623 private getUseConnectorId0(): boolean | undefined {
624 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
627 private getNumberOfRunningTransactions(): number {
629 for (const connector
in this.connectors
) {
630 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
638 private getConnectionTimeout(): number | undefined {
639 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
640 return this.stationInfo
.connectionTimeout
;
642 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
643 return Configuration
.getConnectionTimeout();
648 // -1 for unlimited, 0 for disabling
649 private getAutoReconnectMaxRetries(): number | undefined {
650 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
651 return this.stationInfo
.autoReconnectMaxRetries
;
653 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
654 return Configuration
.getAutoReconnectMaxRetries();
660 private getRegistrationMaxRetries(): number | undefined {
661 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
662 return this.stationInfo
.registrationMaxRetries
;
667 private getPowerDivider(): number {
668 let powerDivider
= this.getNumberOfConnectors();
669 if (this.stationInfo
.powerSharedByConnectors
) {
670 powerDivider
= this.getNumberOfRunningTransactions();
675 private getTemplateMaxNumberOfConnectors(): number {
676 return Object.keys(this.stationInfo
.Connectors
).length
;
679 private getMaxNumberOfConnectors(): number {
680 let maxConnectors
= 0;
681 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
682 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
683 // Distribute evenly the number of connectors
684 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
685 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
686 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
688 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
690 return maxConnectors
;
693 private getNumberOfConnectors(): number {
694 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
697 private async startMessageSequence(): Promise
<void> {
698 // Start WebSocket ping
699 this.startWebSocketPing();
701 this.startHeartbeat();
702 // Initialize connectors status
703 for (const connector
in this.connectors
) {
704 if (Utils
.convertToInt(connector
) === 0) {
706 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
707 // Send status in template at startup
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
))?.bootStatus
) {
711 // Send status in template after reset
712 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
713 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
714 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
715 // Send previous status at template reload
716 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
718 // Send default status
719 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
720 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
724 this.startAutomaticTransactionGenerator();
725 if (this.getEnableStatistics()) {
726 this.performanceStatistics
.start();
730 private startAutomaticTransactionGenerator() {
731 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
732 if (!this.automaticTransactionGeneration
) {
733 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
735 if (this.automaticTransactionGeneration
.timeToStop
) {
736 // The ATG might sleep
737 void this.automaticTransactionGeneration
.start();
742 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
743 // Stop WebSocket ping
744 this.stopWebSocketPing();
746 this.stopHeartbeat();
748 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
749 this.automaticTransactionGeneration
&&
750 !this.automaticTransactionGeneration
.timeToStop
) {
751 await this.automaticTransactionGeneration
.stop(reason
);
753 for (const connector
in this.connectors
) {
754 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
755 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
756 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getTransactionMeterStop(transactionId
), this.getTransactionIdTag(transactionId
), reason
);
762 private startWebSocketPing(): void {
763 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
)
764 ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
)
766 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
767 this.webSocketPingSetInterval
= setInterval(() => {
768 if (this.isWebSocketOpen()) {
769 this.wsConnection
.ping((): void => { });
771 }, webSocketPingInterval
* 1000);
772 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
773 } else if (this.webSocketPingSetInterval
) {
774 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
776 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
780 private stopWebSocketPing(): void {
781 if (this.webSocketPingSetInterval
) {
782 clearInterval(this.webSocketPingSetInterval
);
786 private getSupervisionURL(): string {
787 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
789 if (!Utils
.isEmptyArray(supervisionUrls
)) {
790 if (Configuration
.getDistributeStationsToTenantsEqually()) {
791 indexUrl
= this.index
% supervisionUrls
.length
;
794 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
796 return supervisionUrls
[indexUrl
];
798 return supervisionUrls
as string;
801 private getHeartbeatInterval(): number | undefined {
802 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
803 if (HeartbeatInterval
) {
804 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
806 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
807 if (HeartBeatInterval
) {
808 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
812 private stopHeartbeat(): void {
813 if (this.heartbeatSetInterval
) {
814 clearInterval(this.heartbeatSetInterval
);
818 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
819 if (Utils
.isUndefined(options
)) {
820 options
= {} as WebSocket
.ClientOptions
;
822 if (Utils
.isUndefined(options
?.handshakeTimeout
)) {
823 options
.handshakeTimeout
= this.getConnectionTimeout() * 1000;
825 if (this.isWebSocketOpen() && forceCloseOpened
) {
826 this.wsConnection
.close();
829 switch (this.getOCPPVersion()) {
830 case OCPPVersion
.VERSION_16
:
831 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
834 this.handleUnsupportedVersion(this.getOCPPVersion());
837 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
838 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
841 private stopMeterValues(connectorId
: number) {
842 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
843 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
847 private startAuthorizationFileMonitoring(): void {
848 fs
.watch(this.getAuthorizationFile()).on('change', (e
) => {
850 logger
.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
851 // Initialize authorizedTags
852 this.authorizedTags
= this.getAuthorizedTags();
854 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
859 private startStationTemplateFileMonitoring(): void {
860 // eslint-disable-next-line @typescript-eslint/no-misused-promises
861 fs
.watch(this.stationTemplateFile
).on('change', async (e
): Promise
<void> => {
863 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
867 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
868 this.automaticTransactionGeneration
) {
869 await this.automaticTransactionGeneration
.stop();
872 this.startAutomaticTransactionGenerator();
873 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
875 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
880 private getReconnectExponentialDelay(): boolean | undefined {
881 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
884 private async reconnect(error
: any): Promise
<void> {
886 this.stopHeartbeat();
887 // Stop the ATG if needed
888 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
889 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
890 this.automaticTransactionGeneration
&&
891 !this.automaticTransactionGeneration
.timeToStop
) {
892 await this.automaticTransactionGeneration
.stop();
894 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
895 this.autoReconnectRetryCount
++;
896 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
897 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
898 await Utils
.sleep(reconnectDelay
);
899 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
900 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
901 this.hasSocketRestarted
= true;
902 } else if (this.getAutoReconnectMaxRetries() !== -1) {
903 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
907 private initTransactionOnConnector(connectorId
: number): void {
908 this.getConnector(connectorId
).transactionStarted
= false;
909 delete this.getConnector(connectorId
).transactionId
;
910 delete this.getConnector(connectorId
).idTag
;
911 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;