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 this.hasStopped
&& (this.hasStopped
= false);
465 if (this.hasSocketRestarted
&& this.isWebSocketOpen()) {
466 if (!Utils
.isEmptyArray(this.messageQueue
)) {
467 this.messageQueue
.forEach((message
, index
) => {
468 this.messageQueue
.splice(index
, 1);
469 this.wsConnection
.send(message
);
474 logger
.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`);
476 this.autoReconnectRetryCount
= 0;
477 this.hasSocketRestarted
= false;
480 private async onClose(closeEvent
): Promise
<void> {
481 switch (closeEvent
) {
482 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
: // Normal close
483 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
484 logger
.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
485 this.autoReconnectRetryCount
= 0;
487 default: // Abnormal close
488 logger
.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
489 await this.reconnect(closeEvent
);
494 private async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
495 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
]: IncomingRequest
= [0, '', '' as IncomingRequestCommand
, {}, {}];
496 let responseCallback
: (payload
?: Record
<string, unknown
> | string, requestPayload
?: Record
<string, unknown
>) => void;
497 let rejectCallback
: (error
: OCPPError
) => void;
498 let requestPayload
: Record
<string, unknown
>;
502 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString()) as IncomingRequest
;
504 // Check the Type of message
505 switch (messageType
) {
507 case MessageType
.CALL_MESSAGE
:
508 if (this.getEnableStatistics()) {
509 this.statistics
.addMessage(commandName
, messageType
);
512 await this.ocppIncomingRequestService
.handleRequest(messageId
, commandName
, commandPayload
);
515 case MessageType
.CALL_RESULT_MESSAGE
:
517 if (Utils
.isIterable(this.requests
[messageId
])) {
518 [responseCallback
, , requestPayload
] = this.requests
[messageId
];
520 throw new Error(`Response request for message id ${messageId} is not iterable`);
522 if (!responseCallback
) {
524 throw new Error(`Response request for unknown message id ${messageId}`);
526 delete this.requests
[messageId
];
527 responseCallback(commandName
, requestPayload
);
530 case MessageType
.CALL_ERROR_MESSAGE
:
531 if (!this.requests
[messageId
]) {
533 throw new Error(`Error request for unknown message id ${messageId}`);
535 if (Utils
.isIterable(this.requests
[messageId
])) {
536 [, rejectCallback
] = this.requests
[messageId
];
538 throw new Error(`Error request for message id ${messageId} is not iterable`);
540 delete this.requests
[messageId
];
541 rejectCallback(new OCPPError(commandName
, commandPayload
.toString(), errorDetails
));
545 errMsg
= `${this.logPrefix()} Wrong message type ${messageType}`;
546 logger
.error(errMsg
);
547 throw new Error(errMsg
);
551 logger
.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent
, error
, this.requests
[messageId
]);
553 messageType
!== MessageType
.CALL_ERROR_MESSAGE
&& await this.ocppRequestService
.sendError(messageId
, error
, commandName
);
557 private onPing(): void {
558 logger
.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
561 private onPong(): void {
562 logger
.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
565 private async onError(errorEvent
): Promise
<void> {
566 logger
.error(this.logPrefix() + ' Socket error: %j', errorEvent
);
567 // pragma switch (errorEvent.code) {
568 // case 'ECONNREFUSED':
569 // await this._reconnect(errorEvent);
574 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
575 return this.stationInfo
.Configuration
? this.stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
578 private getAuthorizationFile(): string {
579 return this.stationInfo
.authorizationFile
&& this.stationInfo
.authorizationFile
;
582 private getAuthorizedTags(): string[] {
583 let authorizedTags
: string[] = [];
584 const authorizationFile
= this.getAuthorizationFile();
585 if (authorizationFile
) {
587 // Load authorization file
588 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
589 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
590 fs
.closeSync(fileDescriptor
);
592 logger
.error(this.logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
596 logger
.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile
);
598 return authorizedTags
;
601 private getUseConnectorId0(): boolean {
602 return !Utils
.isUndefined(this.stationInfo
.useConnectorId0
) ? this.stationInfo
.useConnectorId0
: true;
605 private getNumberOfRunningTransactions(): number {
607 for (const connector
in this.connectors
) {
608 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
616 private getConnectionTimeout(): number {
617 if (!Utils
.isUndefined(this.stationInfo
.connectionTimeout
)) {
618 return this.stationInfo
.connectionTimeout
;
620 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
621 return Configuration
.getConnectionTimeout();
626 // -1 for unlimited, 0 for disabling
627 private getAutoReconnectMaxRetries(): number {
628 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
629 return this.stationInfo
.autoReconnectMaxRetries
;
631 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
632 return Configuration
.getAutoReconnectMaxRetries();
638 private getRegistrationMaxRetries(): number {
639 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
640 return this.stationInfo
.registrationMaxRetries
;
645 private getPowerDivider(): number {
646 let powerDivider
= this.getNumberOfConnectors();
647 if (this.stationInfo
.powerSharedByConnectors
) {
648 powerDivider
= this.getNumberOfRunningTransactions();
653 private getTemplateMaxNumberOfConnectors(): number {
654 return Object.keys(this.stationInfo
.Connectors
).length
;
657 private getMaxNumberOfConnectors(): number {
658 let maxConnectors
= 0;
659 if (!Utils
.isEmptyArray(this.stationInfo
.numberOfConnectors
)) {
660 const numberOfConnectors
= this.stationInfo
.numberOfConnectors
as number[];
661 // Distribute evenly the number of connectors
662 maxConnectors
= numberOfConnectors
[(this.index
- 1) % numberOfConnectors
.length
];
663 } else if (!Utils
.isUndefined(this.stationInfo
.numberOfConnectors
)) {
664 maxConnectors
= this.stationInfo
.numberOfConnectors
as number;
666 maxConnectors
= this.stationInfo
.Connectors
[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
668 return maxConnectors
;
671 private getNumberOfConnectors(): number {
672 return this.connectors
[0] ? Object.keys(this.connectors
).length
- 1 : Object.keys(this.connectors
).length
;
675 private async startMessageSequence(): Promise
<void> {
676 // Start WebSocket ping
677 this.startWebSocketPing();
679 this.startHeartbeat();
680 // Initialize connectors status
681 for (const connector
in this.connectors
) {
682 if (Utils
.convertToInt(connector
) === 0) {
684 } else if (!this.hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
))?.status && this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
685 // Send status in template at startup
686 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
687 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
688 } else if (this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.bootStatus
) {
689 // Send status in template after reset
690 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
691 this.getConnector(Utils
.convertToInt(connector
)).status = this.getConnector(Utils
.convertToInt(connector
)).bootStatus
;
692 } else if (!this.hasStopped
&& this.getConnector(Utils
.convertToInt(connector
))?.status) {
693 // Send previous status at template reload
694 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
696 // Send default status
697 await this.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
698 this.getConnector(Utils
.convertToInt(connector
)).status = ChargePointStatus
.AVAILABLE
;
702 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
703 if (!this.automaticTransactionGeneration
) {
704 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
706 if (this.automaticTransactionGeneration
.timeToStop
) {
707 await this.automaticTransactionGeneration
.start();
710 if (this.getEnableStatistics()) {
711 this.statistics
.start();
715 private async stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
716 // Stop WebSocket ping
717 this.stopWebSocketPing();
719 this.stopHeartbeat();
721 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
722 this.automaticTransactionGeneration
&&
723 !this.automaticTransactionGeneration
.timeToStop
) {
724 await this.automaticTransactionGeneration
.stop(reason
);
726 for (const connector
in this.connectors
) {
727 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
728 const transactionId
= this.getConnector(Utils
.convertToInt(connector
)).transactionId
;
729 await this.ocppRequestService
.sendStopTransaction(transactionId
, this.getTransactionMeterStop(transactionId
), this.getTransactionIdTag(transactionId
), reason
);
735 private startWebSocketPing(): void {
736 const webSocketPingInterval
: number = this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
) ? Utils
.convertToInt(this.getConfigurationKey(StandardParametersKey
.WebSocketPingInterval
).value
) : 0;
737 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
738 this.webSocketPingSetInterval
= setInterval(() => {
739 if (this.isWebSocketOpen()) {
740 this.wsConnection
.ping((): void => { });
742 }, webSocketPingInterval
* 1000);
743 logger
.info(this.logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
744 } else if (this.webSocketPingSetInterval
) {
745 logger
.info(this.logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
747 logger
.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
751 private stopWebSocketPing(): void {
752 if (this.webSocketPingSetInterval
) {
753 clearInterval(this.webSocketPingSetInterval
);
754 this.webSocketPingSetInterval
= null;
758 private getSupervisionURL(): string {
759 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(this.stationInfo
.supervisionURL
? this.stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
761 if (!Utils
.isEmptyArray(supervisionUrls
)) {
762 if (Configuration
.getDistributeStationsToTenantsEqually()) {
763 indexUrl
= this.index
% supervisionUrls
.length
;
766 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
768 return supervisionUrls
[indexUrl
];
770 return supervisionUrls
as string;
773 private getHeartbeatInterval(): number {
774 const HeartbeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartbeatInterval
);
775 if (HeartbeatInterval
) {
776 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
778 const HeartBeatInterval
= this.getConfigurationKey(StandardParametersKey
.HeartBeatInterval
);
779 if (HeartBeatInterval
) {
780 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
784 private stopHeartbeat(): void {
785 if (this.heartbeatSetInterval
) {
786 clearInterval(this.heartbeatSetInterval
);
787 this.heartbeatSetInterval
= null;
791 private openWSConnection(options
?: WebSocket
.ClientOptions
, forceCloseOpened
= false): void {
792 if (Utils
.isUndefined(options
)) {
793 options
= {} as WebSocket
.ClientOptions
;
795 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
796 options
.handshakeTimeout
= this.getConnectionTimeout() * 1000;
798 if (this.isWebSocketOpen() && forceCloseOpened
) {
799 this.wsConnection
.close();
802 switch (this.getOCPPVersion()) {
803 case OCPPVersion
.VERSION_16
:
804 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
807 this.handleUnsupportedVersion(this.getOCPPVersion());
810 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
811 logger
.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl
);
814 private startAuthorizationFileMonitoring(): void {
815 fs
.watch(this.getAuthorizationFile()).on('change', (e
) => {
817 logger
.debug(this.logPrefix() + ' Authorization file ' + this.getAuthorizationFile() + ' have changed, reload');
818 // Initialize authorizedTags
819 this.authorizedTags
= this.getAuthorizedTags();
821 logger
.error(this.logPrefix() + ' Authorization file monitoring error: %j', error
);
826 private startStationTemplateFileMonitoring(): void {
827 fs
.watch(this.stationTemplateFile
).on('change', async (e
): Promise
<void> => {
829 logger
.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile
+ ' have changed, reload');
833 if (!this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
834 this.automaticTransactionGeneration
) {
835 await this.automaticTransactionGeneration
.stop();
838 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
) {
839 if (!this.automaticTransactionGeneration
) {
840 this.automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
842 if (this.automaticTransactionGeneration
.timeToStop
) {
843 await this.automaticTransactionGeneration
.start();
846 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
848 logger
.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error
);
853 private getReconnectExponentialDelay(): boolean {
854 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
) ? this.stationInfo
.reconnectExponentialDelay
: false;
857 private async reconnect(error
): Promise
<void> {
859 this.stopHeartbeat();
860 // Stop the ATG if needed
861 if (this.stationInfo
.AutomaticTransactionGenerator
.enable
&&
862 this.stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
863 this.automaticTransactionGeneration
&&
864 !this.automaticTransactionGeneration
.timeToStop
) {
865 this.automaticTransactionGeneration
.stop().catch(() => { });
867 if (this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
868 this.autoReconnectRetryCount
++;
869 const reconnectDelay
= (this.getReconnectExponentialDelay() ? Utils
.exponentialDelay(this.autoReconnectRetryCount
) : this.getConnectionTimeout() * 1000);
870 logger
.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
871 await Utils
.sleep(reconnectDelay
);
872 logger
.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount
.toString());
873 this.openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
874 this.hasSocketRestarted
= true;
875 } else if (this.getAutoReconnectMaxRetries() !== -1) {
876 logger
.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
880 private initTransactionOnConnector(connectorId
: number): void {
881 this.getConnector(connectorId
).transactionStarted
= false;
882 this.getConnector(connectorId
).transactionId
= null;
883 this.getConnector(connectorId
).idTag
= null;
884 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;