1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/RequestResponses';
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 this.heartbeatSetInterval
= setInterval(async () => {
178 await this.ocppRequestService
.sendHeartbeat();
179 }, this.getHeartbeatInterval());
180 logger
.info(this.logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
181 } else if (this.heartbeatSetInterval
) {
182 logger
.info(this.logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this.getHeartbeatInterval()) + ' already started');
184 logger
.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`);
188 public restartHeartbeat(): void {
190 this.stopHeartbeat();
192 this.startHeartbeat();
195 public startMeterValues(connectorId
: number, interval
: number): void {
196 if (connectorId
=== 0) {
197 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`);
200 if (!this.getConnector(connectorId
)) {
201 logger
.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`);
204 if (!this.getConnector(connectorId
)?.transactionStarted
) {
205 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
207 } else if (this.getConnector(connectorId
)?.transactionStarted
&& !this.getConnector(connectorId
)?.transactionId
) {
208 logger
.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
212 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
213 if (this.getEnableStatistics()) {
214 const sendMeterValues
= performance
.timerify(this.ocppRequestService
.sendMeterValues
);
215 this.performanceObserver
.observe({
216 entryTypes
: ['function'],
218 await sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
220 await this.ocppRequestService
.sendMeterValues(connectorId
, this.getConnector(connectorId
).transactionId
, interval
, this.ocppRequestService
);
224 logger
.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
228 public start(): void {
229 this.openWSConnection();
230 // Monitor authorization file
231 this.startAuthorizationFileMonitoring();
232 // Monitor station template file
233 this.startStationTemplateFileMonitoring();
234 // Handle Socket incoming messages
235 this.wsConnection
.on('message', this.onMessage
.bind(this));
236 // Handle Socket error
237 this.wsConnection
.on('error', this.onError
.bind(this));
238 // Handle Socket close
239 this.wsConnection
.on('close', this.onClose
.bind(this));
240 // Handle Socket opening connection
241 this.wsConnection
.on('open', this.onOpen
.bind(this));
242 // Handle Socket ping
243 this.wsConnection
.on('ping', this.onPing
.bind(this));
244 // Handle Socket pong
245 this.wsConnection
.on('pong', this.onPong
.bind(this));
248 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
249 // Stop message sequence
250 await this.stopMessageSequence(reason
);
251 for (const connector
in this.connectors
) {
252 if (Utils
.convertToInt(connector
) > 0) {
253 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
254 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.UNAVAILABLE
;
257 if (this.isWebSocketOpen()) {
258 this.wsConnection
.close();
260 this.bootNotificationResponse
= null;
261 this.hasStopped
= true;
264 public getConfigurationKey(key
: string | StandardParametersKey
, caseInsensitive
= false): ConfigurationKey
{
265 const configurationKey
: ConfigurationKey
= this.configuration
.configurationKey
.find((configElement
) => {
266 if (caseInsensitive
) {
267 return configElement
.key
.toLowerCase() === key
.toLowerCase();
269 return configElement
.key
=== key
;
271 return configurationKey
;
274 public addConfigurationKey(key
: string | StandardParametersKey
, value
: string, readonly = false, visible
= true, reboot
= false): void {
275 const keyFound
= this.getConfigurationKey(key
);
277 this.configuration
.configurationKey
.push({
285 logger
.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound
);
289 public setConfigurationKeyValue(key
: string | StandardParametersKey
, value
: string): void {
290 const keyFound
= this.getConfigurationKey(key
);
292 const keyIndex
= this.configuration
.configurationKey
.indexOf(keyFound
);
293 this.configuration
.configurationKey
[keyIndex
].value
= value
;
295 logger
.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key
, value
});
299 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): boolean {
300 if (!Utils
.isEmptyArray(this.getConnector(connectorId
).chargingProfiles
)) {
301 this.getConnector(connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
302 if (chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
303 || (chargingProfile
.stackLevel
=== cp
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)) {
304 this.getConnector(connectorId
).chargingProfiles
[index
] = cp
;
309 this.getConnector(connectorId
).chargingProfiles
.push(cp
);
313 public resetTransactionOnConnector(connectorId
: number): void {
314 this.initTransactionOnConnector(connectorId
);
315 if (this.getConnector(connectorId
)?.transactionSetInterval
) {
316 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
320 private getChargingStationId(stationTemplate
: ChargingStationTemplate
): string {
321 // In case of multiple instances: add instance index to charging station id
322 let instanceIndex
= process
.env
.CF_INSTANCE_INDEX
? process
.env
.CF_INSTANCE_INDEX
: 0;
323 instanceIndex
= instanceIndex
> 0 ? instanceIndex
: '';
324 const idSuffix
= stationTemplate
.nameSuffix
? stationTemplate
.nameSuffix
: '';
325 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + instanceIndex
.toString() + ('000000000' + this.index
.toString()).substr(('000000000' + this.index
.toString()).length
- 4) + idSuffix
;
328 private buildStationInfo(): ChargingStationInfo
{
329 let stationTemplateFromFile
: ChargingStationTemplate
;
331 // Load template file
332 const fileDescriptor
= fs
.openSync(this.stationTemplateFile
, 'r');
333 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
334 fs
.closeSync(fileDescriptor
);
336 logger
.error('Template file ' + this.stationTemplateFile
+ ' loading error: %j', error
);
339 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
340 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
341 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
342 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
344 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
346 stationInfo
.chargingStationId
= this.getChargingStationId(stationTemplateFromFile
);
347 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
351 private getOCPPVersion(): OCPPVersion
{
352 return this.stationInfo
.ocppVersion
? this.stationInfo
.ocppVersion
: OCPPVersion
.VERSION_16
;
355 private handleUnsupportedVersion(version
: OCPPVersion
) {
356 const errMsg
= `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`;
357 logger
.error(errMsg
);
358 throw new Error(errMsg
);
361 private initialize(): void {
362 this.stationInfo
= this.buildStationInfo();
363 this.bootNotificationRequest
= {
364 chargePointModel
: this.stationInfo
.chargePointModel
,
365 chargePointVendor
: this.stationInfo
.chargePointVendor
,
366 ...!Utils
.isUndefined(this.stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this.stationInfo
.chargeBoxSerialNumberPrefix
},
367 ...!Utils
.isUndefined(this.stationInfo
.firmwareVersion
) && { firmwareVersion
: this.stationInfo
.firmwareVersion
},
369 this.configuration
= this.getTemplateChargingStationConfiguration();
370 this.supervisionUrl
= this.getSupervisionURL();
371 this.wsConnectionUrl
= this.supervisionUrl
+ '/' + this.stationInfo
.chargingStationId
;
372 // Build connectors if needed
373 const maxConnectors
= this.getMaxNumberOfConnectors();
374 if (maxConnectors
<= 0) {
375 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`);
377 const templateMaxConnectors
= this.getTemplateMaxNumberOfConnectors();
378 if (templateMaxConnectors
<= 0) {
379 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`);
381 if (!this.stationInfo
.Connectors
[0]) {
382 logger
.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`);
385 if (maxConnectors
> (this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this.stationInfo
.randomConnectors
) {
386 logger
.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`);
387 this.stationInfo
.randomConnectors
= true;
389 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this.stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
390 // FIXME: Handle shrinking the number of connectors
391 if (!this.connectors
|| (this.connectors
&& this.connectorsConfigurationHash
!== connectorsConfigHash
)) {
392 this.connectorsConfigurationHash
= connectorsConfigHash
;
393 // Add connector Id 0
394 let lastConnector
= '0';
395 for (lastConnector
in this.stationInfo
.Connectors
) {
396 if (Utils
.convertToInt(lastConnector
) === 0 && this.getUseConnectorId0() && this.stationInfo
.Connectors
[lastConnector
]) {
397 this.connectors
[lastConnector
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[lastConnector
]);
398 this.connectors
[lastConnector
].availability
= AvailabilityType
.OPERATIVE
;
399 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
400 this.connectors
[lastConnector
].chargingProfiles
= [];
404 // Generate all connectors
405 if ((this.stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
406 for (let index
= 1; index
<= maxConnectors
; index
++) {
407 const randConnectorID
= this.stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
408 this.connectors
[index
] = Utils
.cloneObject
<Connector
>(this.stationInfo
.Connectors
[randConnectorID
]);
409 this.connectors
[index
].availability
= AvailabilityType
.OPERATIVE
;
410 if (Utils
.isUndefined(this.connectors
[lastConnector
]?.chargingProfiles
)) {
411 this.connectors
[index
].chargingProfiles
= [];
416 // Avoid duplication of connectors related information
417 delete this.stationInfo
.Connectors
;
418 // Initialize transaction attributes on connectors
419 for (const connector
in this.connectors
) {
420 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
421 this.initTransactionOnConnector(Utils
.convertToInt(connector
));
424 switch (this.getOCPPVersion()) {
425 case OCPPVersion
.VERSION_16
:
426 this.ocppIncomingRequestService
= new OCPP16IncomingRequestService(this);
427 this.ocppRequestService
= new OCPP16RequestService(this, new OCPP16ResponseService(this));
430 this.handleUnsupportedVersion(this.getOCPPVersion());
434 this.addConfigurationKey(StandardParametersKey
.NumberOfConnectors
, this.getNumberOfConnectors().toString(), true);
435 if (!this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
)) {
436 this.addConfigurationKey(StandardParametersKey
.MeterValuesSampledData
, MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
438 this.stationInfo
.powerDivider
= this.getPowerDivider();
439 if (this.getEnableStatistics()) {
440 this.statistics
= new Statistics(this.stationInfo
.chargingStationId
);
441 this.performanceObserver
= new PerformanceObserver((list
) => {
442 const entry
= list
.getEntries()[0];
443 this.statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
444 this.performanceObserver
.disconnect();
449 private async onOpen(): Promise
<void> {
450 logger
.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}`);
451 if (!this.isRegistered()) {
452 // Send BootNotification
453 let registrationRetryCount
= 0;
455 this.bootNotificationResponse
= await this.ocppRequestService
.sendBootNotification(this.bootNotificationRequest
.chargePointModel
, this.bootNotificationRequest
.chargePointVendor
, this.bootNotificationRequest
.chargeBoxSerialNumber
, this.bootNotificationRequest
.firmwareVersion
);
456 if (!this.isRegistered()) {
457 registrationRetryCount
++;
458 await Utils
.sleep(this.bootNotificationResponse
?.interval
? this.bootNotificationResponse
.interval
* 1000 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
);
460 } while (!this.isRegistered() && (registrationRetryCount
<= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
462 if (this.isRegistered()) {
463 await this.startMessageSequence();
464 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
465 if (!Utils
.isEmptyArray(this.messageQueue
)) {
466 this.messageQueue
.forEach((message
, index
) => {
467 this.messageQueue
.splice(index
, 1);
468 this.wsConnection
.send(message
);
473 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
475 this.autoReconnectRetryCount
= 0;
476 this.hasSocketRestarted
= false;
479 private async onClose(closeEvent
): Promise
<void> {
480 switch (closeEvent
) {
481 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
482 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
483 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
484 this.autoReconnectRetryCount
= 0;
486 default: // Abnormal close
487 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
488 await this.reconnect(closeEvent
);
493 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
494 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
495 let responseCallback
: (payload
?: Record
<string, unknown
> | string, requestPayload
?: Record
<string, unknown
>) => void;
496 let rejectCallback
: (error
: OCPPError
) => void;
497 let requestPayload
: Record
<string, unknown
>;
501 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
503 // Check the Type of message
504 switch (messageType
) {
506 case MessageType
.CALL_MESSAGE
:
507 if (this.getEnableStatistics()) {
508 this.statistics
.addMessage(commandName
, messageType
);
511 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
514 case MessageType
.CALL_RESULT_MESSAGE
:
516 if (Utils
.isIterable(this.requests
[messageId
])) {
517 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
519 throw new Error(`Response request for message id ${messageId} is not iterable`);
521 if (!responseCallback
) {
523 throw new Error(`Response request for unknown message id ${messageId}`);
525 delete this.requests
[messageId
];
526 responseCallback(commandName
, requestPayload
);
529 case MessageType
.CALL_ERROR_MESSAGE
:
530 if (!this.requests
[messageId
]) {
532 throw new Error(`Error request for unknown message id ${messageId}`);
534 if (Utils
.isIterable(this.requests
[messageId
])) {
535 [, rejectCallback
] = this.requests
[messageId
];
537 throw new Error(`Error request for message id ${messageId} is not iterable`);
539 delete this.requests
[messageId
];
540 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
544 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
545 logger
.error(errMsg
);
546 throw new Error(errMsg
);
550 logger
.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
552 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
556 private onPing(): void {
557 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
560 private onPong(): void {
561 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
564 private async onError(errorEvent
): Promise
<void> {
565 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
566 // pragma switch (errorEvent.code) {
567 // case 'ECONNREFUSED':
568 // await this._reconnect(errorEvent);
573 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
574 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
577 private getAuthorizationFile(): string {
578 return this.stationInfo
.authorizationFile
&& this.stationInfo
.authorizationFile
;
581 private getAuthorizedTags(): string[] {
582 let authorizedTags
: string[] = [];
583 const authorizationFile
= this.getAuthorizationFile();
584 if (authorizationFile
) {
586 // Load authorization file
587 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
588 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
589 fs
.closeSync(fileDescriptor
);
591 logger
.error(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
595 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
597 return authorizedTags
;
600 private getUseConnectorId0(): boolean {
601 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
604 private getNumberOfRunningTransactions(): number {
606 for (const connector
in this.connectors
) {
607 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
615 private getConnectionTimeout(): number {
616 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
617 return this.stationInfo
.connectionTimeout
;
619 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
620 return Configuration
.getConnectionTimeout();
625 // -1 for unlimited, 0 for disabling
626 private getAutoReconnectMaxRetries(): number {
627 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
628 return this.stationInfo
.autoReconnectMaxRetries
;
630 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
631 return Configuration
.getAutoReconnectMaxRetries();
637 private getRegistrationMaxRetries(): number {
638 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
639 return this.stationInfo
.registrationMaxRetries
;
644 private getPowerDivider(): number {
645 let powerDivider
= this.getNumberOfConnectors();
646 if (this.stationInfo
.powerSharedByConnectors
) {
647 powerDivider
= this.getNumberOfRunningTransactions();
652 private getTemplateMaxNumberOfConnectors(): number {
653 return Object.keys(this.stationInfo
.Connectors
).length
;
656 private getMaxNumberOfConnectors(): number {
657 let maxConnectors
= 0;
658 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
659 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
660 // Distribute evenly the number of connectors
661 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
662 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
663 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
665 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
667 return maxConnectors
;
670 private getNumberOfConnectors(): number {
671 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
674 private async startMessageSequence(): Promise
<void> {
675 // Start WebSocket ping
676 this.startWebSocketPing();
678 this.startHeartbeat();
679 // Initialize connectors status
680 for (const connector
in this.connectors
) {
681 if (Utils
.convertToInt(connector
) === 0) {
683 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
684 // Send status in template at startup
685 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
686 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
687 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
688 // Send status in template after reset
689 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
690 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
691 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
692 // Send previous status at template reload
693 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
695 // Send default status
696 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
697 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
701 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
702 if (!this.automaticTransactionGeneration
) {
703 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
705 if (this.automaticTransactionGeneration
.timeToStop
) {
706 await this.automaticTransactionGeneration
.start();
709 if (this.getEnableStatistics()) {
710 this.statistics
.start();
714 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
715 // Stop WebSocket ping
716 this.stopWebSocketPing();
718 this.stopHeartbeat();
720 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
721 this.automaticTransactionGeneration
&&
722 !this.automaticTransactionGeneration
.timeToStop
) {
723 await this.automaticTransactionGeneration
.stop(reason
);
725 for (const connector
in this.connectors
) {
726 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
727 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
728 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getTransactionMeterStop(transactionId
), this.getTransactionIdTag(transactionId
), reason
);
734 private startWebSocketPing(): void {
735 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
) ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
) : 0;
736 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
737 this.webSocketPingSetInterval
= setInterval(() => {
738 if (this.isWebSocketOpen()) {
739 this.wsConnection
.ping((): void => { });
741 }, webSocketPingInterval
* 1000);
742 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
743 } else if (this.webSocketPingSetInterval
) {
744 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
746 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
750 private stopWebSocketPing(): void {
751 if (this.webSocketPingSetInterval
) {
752 clearInterval(this.webSocketPingSetInterval
);
753 this.webSocketPingSetInterval
= null;
757 private getSupervisionURL(): string {
758 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
760 if (!Utils
.isEmptyArray(supervisionUrls
)) {
761 if (Configuration
.getDistributeStationsToTenantsEqually()) {
762 indexUrl
= this.index
% supervisionUrls
.length
;
765 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
767 return supervisionUrls
[indexUrl
];
769 return supervisionUrls
as string;
772 private getHeartbeatInterval(): number {
773 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
774 if (HeartbeatInterval
) {
775 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
777 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
778 if (HeartBeatInterval
) {
779 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
783 private stopHeartbeat(): void {
784 if (this.heartbeatSetInterval
) {
785 clearInterval(this.heartbeatSetInterval
);
786 this.heartbeatSetInterval
= null;
790 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
791 if (Utils
.isUndefined(options
)) {
792 options
= {} as WebSocket
.ClientOptions
;
794 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
795 options
.handshakeTimeout
= this.getConnectionTimeout() * 1000;
797 if (this.isWebSocketOpen() && forceCloseOpened
) {
798 this.wsConnection
.close();
801 switch (this.getOCPPVersion()) {
802 case OCPPVersion
.VERSION_16
:
803 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
806 this.handleUnsupportedVersion(this.getOCPPVersion());
809 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
810 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
813 private startAuthorizationFileMonitoring(): void {
814 fs
.watch(this.getAuthorizationFile()).on('change', (e
) => {
816 logger
.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
817 // Initialize authorizedTags
818 this.authorizedTags
= this.getAuthorizedTags();
820 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
825 private startStationTemplateFileMonitoring(): void {
826 fs
.watch(this.stationTemplateFile
).on('change', async (e
): Promise
<void> => {
828 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
832 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
833 this.automaticTransactionGeneration
) {
834 await this.automaticTransactionGeneration
.stop();
837 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
838 if (!this.automaticTransactionGeneration
) {
839 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
841 if (this.automaticTransactionGeneration
.timeToStop
) {
842 await this.automaticTransactionGeneration
.start();
845 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
847 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
852 private getReconnectExponentialDelay(): boolean {
853 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
856 private async reconnect(error
): Promise
<void> {
858 this.stopHeartbeat();
859 // Stop the ATG if needed
860 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
861 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
862 this.automaticTransactionGeneration
&&
863 !this.automaticTransactionGeneration
.timeToStop
) {
864 this.automaticTransactionGeneration
.stop().catch(() => { });
866 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
867 this.autoReconnectRetryCount
++;
868 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
869 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
870 await Utils
.sleep(reconnectDelay
);
871 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
872 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
873 this.hasSocketRestarted
= true;
874 } else if (this.getAutoReconnectMaxRetries() !== -1) {
875 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
879 private initTransactionOnConnector(connectorId
: number): void {
880 this.getConnector(connectorId
).transactionStarted
= false;
881 this.getConnector(connectorId
).transactionId
= null;
882 this.getConnector(connectorId
).idTag
= null;
883 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;