1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { CurrentOutType
, PowerUnits
, VoltageOut
} from
'../types/ChargingStationTemplate';
4 import { ConnectorPhaseRotation
, StandardParametersKey
, SupportedFeatureProfiles
} from
'../types/ocpp/Configuration';
5 import Connectors
, { Connector
, SampledValueTemplate
} from
'../types/Connectors';
6 import { MeterValueMeasurand
, MeterValuePhase
} from
'../types/ocpp/MeterValues';
7 import { PerformanceObserver
, performance
} from
'perf_hooks';
8 import Requests
, { AvailabilityType
, BootNotificationRequest
, IncomingRequest
, IncomingRequestCommand
} from
'../types/ocpp/Requests';
9 import WebSocket
, { MessageEvent
} from
'ws';
11 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
12 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
13 import { ChargingProfile
} from
'../types/ocpp/ChargingProfile';
14 import ChargingStationInfo from
'../types/ChargingStationInfo';
15 import Configuration from
'../utils/Configuration';
16 import Constants from
'../utils/Constants';
17 import FileUtils from
'../utils/FileUtils';
18 import { MessageType
} from
'../types/ocpp/MessageType';
19 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCCP16IncomingRequestService';
20 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
21 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
22 import OCPPError from
'./OcppError';
23 import OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
24 import OCPPRequestService from
'./ocpp/OCPPRequestService';
25 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
26 import PerformanceStatistics from
'../utils/PerformanceStatistics';
27 import { StopTransactionReason
} from
'../types/ocpp/Transaction';
28 import Utils from
'../utils/Utils';
29 import { WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
30 import crypto from
'crypto';
32 import logger from
'../utils/Logger';
33 import path from
'path';
35 export default class ChargingStation
{
36 public stationTemplateFile
: string;
37 public authorizedTags
: string[];
38 public stationInfo
!: ChargingStationInfo
;
39 public connectors
: Connectors
;
40 public configuration
!: ChargingStationConfiguration
;
41 public hasStopped
: boolean;
42 public wsConnection
!: WebSocket
;
43 public requests
: Requests
;
44 public messageQueue
: string[];
45 public performanceStatistics
!: PerformanceStatistics
;
46 public heartbeatSetInterval
!: NodeJS
.Timeout
;
47 public ocppIncomingRequestService
!: OCPPIncomingRequestService
;
48 public ocppRequestService
!: OCPPRequestService
;
49 private index
: number;
50 private bootNotificationRequest
!: BootNotificationRequest
;
51 private bootNotificationResponse
!: BootNotificationResponse
| null;
52 private connectorsConfigurationHash
!: string;
53 private supervisionUrl
!: string;
54 private wsConnectionUrl
!: string;
55 private hasSocketRestarted
: boolean;
56 private autoReconnectRetryCount
: number;
57 private automaticTransactionGeneration
!: AutomaticTransactionGenerator
;
58 private performanceObserver
!: PerformanceObserver
;
59 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
61 constructor(index
: number, stationTemplateFile
: string) {
63 this.stationTemplateFile
= stationTemplateFile
;
64 this.connectors
= {} as Connectors
;
67 this.hasStopped
= false;
68 this.hasSocketRestarted
= false;
69 this.autoReconnectRetryCount
= 0;
71 this.requests
= {} as Requests
;
72 this.messageQueue
= [] as string[];
74 this.authorizedTags
= this.getAuthorizedTags();
77 public logPrefix(): string {
78 return Utils
.logPrefix(` ${this.stationInfo.chargingStationId} |`);
81 public getRandomTagId(): string {
82 const index
= Math.floor(Math.random() * this.authorizedTags
.length
);
83 return this.authorizedTags
[index
];
86 public hasAuthorizedTags(): boolean {
87 return !Utils
.isEmptyArray(this.authorizedTags
);
90 public getEnableStatistics(): boolean | undefined {
91 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
) ? this.stationInfo
.enableStatistics
: true;
94 public getNumberOfPhases(): number | undefined {
95 switch (this.getCurrentOutType()) {
96 case CurrentOutType
.AC
:
97 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
98 case CurrentOutType
.DC
:
103 public isWebSocketOpen(): boolean {
104 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
107 public isRegistered(): boolean {
108 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
111 public isChargingStationAvailable(): boolean {
112 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
115 public isConnectorAvailable(id
: number): boolean {
116 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
119 public getConnector(id
: number): Connector
{
120 return this.connectors
[id
];
123 public getCurrentOutType(): CurrentOutType
| undefined {
124 return this.stationInfo
.currentOutType
?? CurrentOutType
.AC
;
127 public getVoltageOut(): number | undefined {
128 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
129 let defaultVoltageOut
: number;
130 switch (this.getCurrentOutType()) {
131 case CurrentOutType
.AC
:
132 defaultVoltageOut
= VoltageOut
.VOLTAGE_230
;
134 case CurrentOutType
.DC
:
135 defaultVoltageOut
= VoltageOut
.VOLTAGE_400
;
138 logger
.error(errMsg
);
141 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
144 public getTransactionIdTag(transactionId
: number): string | undefined {
145 for (const connector
in this.connectors
) {
146 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
147 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
152 public getOutOfOrderEndMeterValues(): boolean {
153 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
156 public getBeginEndMeterValues(): boolean {
157 return this.stationInfo
.beginEndMeterValues
?? false;
160 public getMeteringPerTransaction(): boolean {
161 return this.stationInfo
.meteringPerTransaction
?? true;
164 public getTransactionDataMeterValues(): boolean {
165 return this.stationInfo
.transactionDataMeterValues
?? false;
168 public getMainVoltageMeterValues(): boolean {
169 return this.stationInfo
.mainVoltageMeterValues
?? true;
172 public getPhaseLineToLineVoltageMeterValues(): boolean {
173 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
176 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
177 if (this.getMeteringPerTransaction()) {
178 for (const connector
in this.connectors
) {
179 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
180 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
184 for (const connector
in this.connectors
) {
185 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
186 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
191 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
192 if (this.getMeteringPerTransaction()) {
193 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
195 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
198 public getAuthorizeRemoteTxRequests(): boolean {
199 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
200 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
203 public getLocalAuthListEnabled(): boolean {
204 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
205 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
208 public restartWebSocketPing(): void {
209 // Stop WebSocket ping
210 this.stopWebSocketPing();
211 // Start WebSocket ping
212 this.startWebSocketPing();
215 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
216 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
217 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
218 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
221 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
222 logger.warn(`${this.logPrefix()} Trying to get MeterValues measurand ${measurand} ${phase ? `on phase ${phase}
` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`);
225 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
226 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
227 if (phase
&& sampledValueTemplates
[index
]?.phase
=== phase
&& sampledValueTemplates
[index
]?.measurand
=== measurand
228 && this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(measurand
)) {
229 return sampledValueTemplates
[index
];
230 } else if (!phase
&& !sampledValueTemplates
[index
].phase
&& sampledValueTemplates
[index
]?.measurand
=== measurand
231 && this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(measurand
)) {
232 return sampledValueTemplates
[index
];
233 } else if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
234 && (!sampledValueTemplates
[index
].measurand
|| sampledValueTemplates
[index
].measurand
=== measurand
)) {
235 return sampledValueTemplates
[index
];
238 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
239 logger
.error(`${this.logPrefix()} Missing MeterValues for default measurand ${measurand} in template on connectorId ${connectorId}`);
241 logger
.debug(`${this.logPrefix()} No MeterValues for measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
244 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
245 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
248 public startHeartbeat(): void {
249 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
250 // eslint-disable-next-line @typescript-eslint/no-misused-promises
251 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
252 await this.ocppRequestService.sendHeartbeat();
253 }, this.getHeartbeatInterval());
254 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
255 } else if (this.heartbeatSetInterval) {
256 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
258 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}
, not starting the heartbeat
`);
262 public restartHeartbeat(): void {
264 this.stopHeartbeat();
266 this.startHeartbeat();
269 public startMeterValues(connectorId: number, interval: number): void {
270 if (connectorId === 0) {
271 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}
`);
274 if (!this.getConnector(connectorId)) {
275 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}
`);
278 if (!this.getConnector(connectorId)?.transactionStarted) {
279 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId}
with no transaction started
`);
281 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
282 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId}
with no transaction id
`);
286 // eslint-disable-next-line @typescript-eslint/no-misused-promises
287 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
288 if (this.getEnableStatistics()) {
289 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
290 this.performanceObserver.observe({
291 entryTypes: ['function'],
293 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
295 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
299 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}
, not sending MeterValues
`);
303 public start(): void {
304 this.openWSConnection();
305 // Monitor authorization file
306 this.startAuthorizationFileMonitoring();
307 // Monitor station template file
308 this.startStationTemplateFileMonitoring();
309 // Handle Socket incoming messages
310 this.wsConnection.on('message', this.onMessage.bind(this));
311 // Handle Socket error
312 this.wsConnection.on('error', this.onError.bind(this));
313 // Handle Socket close
314 this.wsConnection.on('close', this.onClose.bind(this));
315 // Handle Socket opening connection
316 this.wsConnection.on('open', this.onOpen.bind(this));
317 // Handle Socket ping
318 this.wsConnection.on('ping', this.onPing.bind(this));
319 // Handle Socket pong
320 this.wsConnection.on('pong', this.onPong.bind(this));
323 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
324 // Stop message sequence
325 await this.stopMessageSequence(reason);
326 for (const connector in this.connectors) {
327 if (Utils.convertToInt(connector) > 0) {
328 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
329 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
332 if (this.isWebSocketOpen()) {
333 this.wsConnection.close();
335 this.bootNotificationResponse = null;
336 this.hasStopped = true;
339 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
340 const configurationKey: ConfigurationKey | undefined = this.configuration.configurationKey.find((configElement) => {
341 if (caseInsensitive) {
342 return configElement.key.toLowerCase() === key.toLowerCase();
344 return configElement.key === key;
346 return configurationKey;
349 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
350 const keyFound = this.getConfigurationKey(key);
352 this.configuration.configurationKey.push({
360 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key
: %j
`, keyFound);
364 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
365 const keyFound = this.getConfigurationKey(key);
367 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
368 this.configuration.configurationKey[keyIndex].value = value;
370 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key
: %j
`, { key, value });
374 public setChargingProfile(connectorId: number, cp: ChargingProfile): boolean {
375 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
376 this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
377 if (chargingProfile.chargingProfileId === cp.chargingProfileId
378 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
379 this.getConnector(connectorId).chargingProfiles[index] = cp;
384 this.getConnector(connectorId).chargingProfiles?.push(cp);
388 public resetTransactionOnConnector(connectorId: number): void {
389 this.getConnector(connectorId).transactionStarted = false;
390 delete this.getConnector(connectorId).transactionId;
391 delete this.getConnector(connectorId).idTag;
392 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
393 delete this.getConnector(connectorId).transactionBeginMeterValue;
394 this.stopMeterValues(connectorId);
397 public addToMessageQueue(message: string): void {
399 // Handle dups in message queue
400 for (const bufferedMessage of this.messageQueue) {
401 // Message already in the queue
402 if (message === bufferedMessage) {
409 this.messageQueue.push(message);
413 private flushMessageQueue() {
414 if (!Utils.isEmptyArray(this.messageQueue)) {
415 this.messageQueue.forEach((message, index) => {
416 this.messageQueue.splice(index, 1);
417 this.wsConnection.send(message);
422 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
423 // In case of multiple instances: add instance index to charging station id
424 let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
425 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
426 const idSuffix = stationTemplate.nameSuffix ?? '';
427 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
430 private buildStationInfo(): ChargingStationInfo {
431 let stationTemplateFromFile: ChargingStationTemplate;
433 // Load template file
434 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
435 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
436 fs.closeSync(fileDescriptor);
438 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
440 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
441 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
442 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
443 const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length);
444 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
445 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
446 : stationTemplateFromFile.power[powerArrayRandomIndex];
448 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
449 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
450 ? stationTemplateFromFile.power * 1000
451 : stationTemplateFromFile.power;
453 delete stationInfo.power;
454 delete stationInfo.powerUnit;
455 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
456 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
460 private getOCPPVersion(): OCPPVersion {
461 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
464 private handleUnsupportedVersion(version: OCPPVersion) {
465 const errMsg = `${this.logPrefix()} Unsupported protocol version
'${version}' configured
in template file ${this.stationTemplateFile}
`;
466 logger.error(errMsg);
467 throw new Error(errMsg);
470 private initialize(): void {
471 this.stationInfo = this.buildStationInfo();
472 this.bootNotificationRequest = {
473 chargePointModel: this.stationInfo.chargePointModel,
474 chargePointVendor: this.stationInfo.chargePointVendor,
475 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
476 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
478 this.configuration = this.getTemplateChargingStationConfiguration();
479 this.supervisionUrl = this.getSupervisionURL();
480 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
481 // Build connectors if needed
482 const maxConnectors = this.getMaxNumberOfConnectors();
483 if (maxConnectors <= 0) {
484 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with ${maxConnectors} connectors
`);
486 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
487 if (templateMaxConnectors <= 0) {
488 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector configuration
`);
490 if (!this.stationInfo.Connectors[0]) {
491 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector Id
0 configuration
`);
494 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
495 logger.warn(`${this.logPrefix()}
Number of connectors exceeds the
number of connector configurations
in template ${this.stationTemplateFile}
, forcing random connector configurations affectation
`);
496 this.stationInfo.randomConnectors = true;
498 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
499 // FIXME: Handle shrinking the number of connectors
500 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
501 this.connectorsConfigurationHash = connectorsConfigHash;
502 // Add connector Id 0
503 let lastConnector = '0';
504 for (lastConnector in this.stationInfo.Connectors) {
505 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
506 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
507 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
508 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
509 this.connectors[lastConnector].chargingProfiles = [];
513 // Generate all connectors
514 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
515 for (let index = 1; index <= maxConnectors; index++) {
516 const randConnectorID = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
517 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorID]);
518 this.connectors[index].availability = AvailabilityType.OPERATIVE;
519 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
520 this.connectors[index].chargingProfiles = [];
525 // Avoid duplication of connectors related information
526 delete this.stationInfo.Connectors;
527 // Initialize transaction attributes on connectors
528 for (const connector in this.connectors) {
529 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
530 this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
533 switch (this.getOCPPVersion()) {
534 case OCPPVersion.VERSION_16:
535 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
536 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
539 this.handleUnsupportedVersion(this.getOCPPVersion());
543 this.initOCPPParameters();
544 this.stationInfo.powerDivider = this.getPowerDivider();
545 if (this.getEnableStatistics()) {
546 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId);
547 this.performanceObserver = new PerformanceObserver((list) => {
548 const entry = list.getEntries()[0];
549 this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
550 this.performanceObserver.disconnect();
555 private initOCPPParameters(): void {
556 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
557 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core}
,${SupportedFeatureProfiles.Local_Auth_List_Management}
,${SupportedFeatureProfiles.Smart_Charging}
`);
559 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
560 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
561 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
563 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
564 const connectorPhaseRotation = [];
565 for (const connector in this.connectors) {
567 if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) {
568 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
569 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) {
570 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
572 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) {
573 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
574 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) {
575 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
578 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
580 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
581 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
583 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
584 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
585 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
587 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
588 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
592 private async onOpen(): Promise<void> {
593 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}
`);
594 if (!this.isRegistered()) {
595 // Send BootNotification
596 let registrationRetryCount = 0;
598 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
599 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
600 if (!this.isRegistered()) {
601 registrationRetryCount++;
602 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
604 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
606 if (this.isRegistered()) {
607 await this.startMessageSequence();
608 this.hasStopped && (this.hasStopped = false);
609 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
610 this.flushMessageQueue();
613 logger.error(`${this.logPrefix()} Registration failure
: max retries
reached (${this.getRegistrationMaxRetries()}
) or retry
disabled (${this.getRegistrationMaxRetries()}
)`);
615 this.autoReconnectRetryCount = 0;
616 this.hasSocketRestarted = false;
619 private async onClose(closeEvent: any): Promise<void> {
620 switch (closeEvent) {
621 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
622 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
623 logger.info(`${this.logPrefix()} Socket normally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
624 this.autoReconnectRetryCount = 0;
626 default: // Abnormal close
627 logger.error(`${this.logPrefix()} Socket abnormally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
628 await this.reconnect(closeEvent);
633 private async onMessage(messageEvent: MessageEvent): Promise<void> {
634 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
635 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
636 let rejectCallback: (error: OCPPError) => void;
637 let requestPayload: Record<string, unknown>;
641 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
642 // Check the Type of message
643 switch (messageType) {
645 case MessageType.CALL_MESSAGE:
646 if (this.getEnableStatistics()) {
647 this.performanceStatistics.addMessage(commandName, messageType);
650 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
653 case MessageType.CALL_RESULT_MESSAGE:
655 if (Utils.isIterable(this.requests[messageId])) {
656 [responseCallback, , requestPayload] = this.requests[messageId];
658 throw new Error(`Response request
for message id ${messageId}
is not iterable
`);
660 if (!responseCallback) {
662 throw new Error(`Response request
for unknown message id ${messageId}
`);
664 delete this.requests[messageId];
665 responseCallback(commandName, requestPayload);
668 case MessageType.CALL_ERROR_MESSAGE:
669 if (!this.requests[messageId]) {
671 throw new Error(`Error request
for unknown message id ${messageId}
`);
673 if (Utils.isIterable(this.requests[messageId])) {
674 [, rejectCallback] = this.requests[messageId];
676 throw new Error(`Error request
for message id ${messageId}
is not iterable
`);
678 delete this.requests[messageId];
679 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
683 errMsg = `${this.logPrefix()} Wrong message
type ${messageType}
`;
684 logger.error(errMsg);
685 throw new Error(errMsg);
689 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
691 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
695 private onPing(): void {
696 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
699 private onPong(): void {
700 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
703 private async onError(errorEvent: any): Promise<void> {
704 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
705 // switch (errorEvent.code) {
706 // case 'ECONNREFUSED':
707 // await this._reconnect(errorEvent);
712 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
713 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
716 private getAuthorizationFile(): string | undefined {
717 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
720 private getAuthorizedTags(): string[] {
721 let authorizedTags: string[] = [];
722 const authorizationFile = this.getAuthorizationFile();
723 if (authorizationFile) {
725 // Load authorization file
726 const fileDescriptor = fs.openSync(authorizationFile, 'r');
727 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
728 fs.closeSync(fileDescriptor);
730 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
733 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
735 return authorizedTags;
738 private getUseConnectorId0(): boolean | undefined {
739 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
742 private getNumberOfRunningTransactions(): number {
744 for (const connector in this.connectors) {
745 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
753 private getConnectionTimeout(): number | undefined {
754 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
755 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
757 return Constants.DEFAULT_CONNECTION_TIMEOUT;
760 // -1 for unlimited, 0 for disabling
761 private getAutoReconnectMaxRetries(): number | undefined {
762 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
763 return this.stationInfo.autoReconnectMaxRetries;
765 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
766 return Configuration.getAutoReconnectMaxRetries();
772 private getRegistrationMaxRetries(): number | undefined {
773 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
774 return this.stationInfo.registrationMaxRetries;
779 private getPowerDivider(): number {
780 let powerDivider = this.getNumberOfConnectors();
781 if (this.stationInfo.powerSharedByConnectors) {
782 powerDivider = this.getNumberOfRunningTransactions();
787 private getTemplateMaxNumberOfConnectors(): number {
788 return Object.keys(this.stationInfo.Connectors).length;
791 private getMaxNumberOfConnectors(): number {
792 let maxConnectors = 0;
793 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
794 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
795 // Distribute evenly the number of connectors
796 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
797 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
798 maxConnectors = this.stationInfo.numberOfConnectors as number;
800 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
802 return maxConnectors;
805 private getNumberOfConnectors(): number {
806 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
809 private async startMessageSequence(): Promise<void> {
810 // Start WebSocket ping
811 this.startWebSocketPing();
813 this.startHeartbeat();
814 // Initialize connectors status
815 for (const connector in this.connectors) {
816 if (Utils.convertToInt(connector) === 0) {
818 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
819 // Send status in template at startup
820 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
821 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
822 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
823 // Send status in template after reset
824 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
825 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
826 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
827 // Send previous status at template reload
828 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
830 // Send default status
831 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
832 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
836 this.startAutomaticTransactionGenerator();
837 if (this.getEnableStatistics()) {
838 this.performanceStatistics.start();
842 private startAutomaticTransactionGenerator() {
843 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
844 if (!this.automaticTransactionGeneration) {
845 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
847 if (this.automaticTransactionGeneration.timeToStop) {
848 // The ATG might sleep
849 void this.automaticTransactionGeneration.start();
854 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
855 // Stop WebSocket ping
856 this.stopWebSocketPing();
858 this.stopHeartbeat();
860 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
861 this.automaticTransactionGeneration &&
862 !this.automaticTransactionGeneration.timeToStop) {
863 await this.automaticTransactionGeneration.stop(reason);
865 for (const connector in this.connectors) {
866 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
867 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
868 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
869 this.getTransactionIdTag(transactionId), reason);
875 private startWebSocketPing(): void {
876 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
877 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
879 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
880 this.webSocketPingSetInterval = setInterval(() => {
881 if (this.isWebSocketOpen()) {
882 this.wsConnection.ping((): void => { });
884 }, webSocketPingInterval * 1000);
885 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
886 } else if (this.webSocketPingSetInterval) {
887 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
889 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}
, not starting the WebSocket ping
`);
893 private stopWebSocketPing(): void {
894 if (this.webSocketPingSetInterval) {
895 clearInterval(this.webSocketPingSetInterval);
899 private getSupervisionURL(): string {
900 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
902 if (!Utils.isEmptyArray(supervisionUrls)) {
903 if (Configuration.getDistributeStationsToTenantsEqually()) {
904 indexUrl = this.index % supervisionUrls.length;
907 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
909 return supervisionUrls[indexUrl];
911 return supervisionUrls as string;
914 private getHeartbeatInterval(): number | undefined {
915 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
916 if (HeartbeatInterval) {
917 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
919 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
920 if (HeartBeatInterval) {
921 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
925 private stopHeartbeat(): void {
926 if (this.heartbeatSetInterval) {
927 clearInterval(this.heartbeatSetInterval);
931 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
932 options ?? {} as WebSocket.ClientOptions;
933 options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
934 if (this.isWebSocketOpen() && forceCloseOpened) {
935 this.wsConnection.close();
938 switch (this.getOCPPVersion()) {
939 case OCPPVersion.VERSION_16:
940 protocol = 'ocpp' + OCPPVersion.VERSION_16;
943 this.handleUnsupportedVersion(this.getOCPPVersion());
946 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
947 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
950 private stopMeterValues(connectorId: number) {
951 if (this.getConnector(connectorId)?.transactionSetInterval) {
952 clearInterval(this.getConnector(connectorId).transactionSetInterval);
956 private startAuthorizationFileMonitoring(): void {
957 const authorizationFile = this.getAuthorizationFile();
958 if (authorizationFile) {
960 fs.watch(authorizationFile).on('change', () => {
962 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
963 // Initialize authorizedTags
964 this.authorizedTags = this.getAuthorizedTags();
966 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
970 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
973 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
977 private startStationTemplateFileMonitoring(): void {
979 // eslint-disable-next-line @typescript-eslint/no-misused-promises
980 fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => {
982 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
986 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
987 this.automaticTransactionGeneration) {
988 await this.automaticTransactionGeneration.stop();
991 this.startAutomaticTransactionGenerator();
992 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
994 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
998 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
1002 private getReconnectExponentialDelay(): boolean | undefined {
1003 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1006 private async reconnect(error: any): Promise<void> {
1008 this.stopHeartbeat();
1009 // Stop the ATG if needed
1010 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1011 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1012 this.automaticTransactionGeneration &&
1013 !this.automaticTransactionGeneration.timeToStop) {
1014 await this.automaticTransactionGeneration.stop();
1016 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1017 this.autoReconnectRetryCount++;
1018 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1019 logger.error(`${this.logPrefix()} Socket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectDelay - 100}ms
`);
1020 await Utils.sleep(reconnectDelay);
1021 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1022 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
1023 this.hasSocketRestarted = true;
1024 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1025 logger.error(`${this.logPrefix()} Socket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1029 private initTransactionAttributesOnConnector(connectorId: number): void {
1030 this.getConnector(connectorId).transactionStarted = false;
1031 this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
1032 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;