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
)).transactionIdTag
;
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.debug(`${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).authorized = false;
390 this.getConnector(connectorId).transactionStarted = false;
391 delete this.getConnector(connectorId).authorizeIdTag;
392 delete this.getConnector(connectorId).transactionId;
393 delete this.getConnector(connectorId).transactionIdTag;
394 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
395 delete this.getConnector(connectorId).transactionBeginMeterValue;
396 this.stopMeterValues(connectorId);
399 public addToMessageQueue(message: string): void {
401 // Handle dups in message queue
402 for (const bufferedMessage of this.messageQueue) {
403 // Message already in the queue
404 if (message === bufferedMessage) {
411 this.messageQueue.push(message);
415 private flushMessageQueue() {
416 if (!Utils.isEmptyArray(this.messageQueue)) {
417 this.messageQueue.forEach((message, index) => {
418 this.messageQueue.splice(index, 1);
419 this.wsConnection.send(message);
424 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
425 // In case of multiple instances: add instance index to charging station id
426 let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
427 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
428 const idSuffix = stationTemplate.nameSuffix ?? '';
429 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
432 private buildStationInfo(): ChargingStationInfo {
433 let stationTemplateFromFile: ChargingStationTemplate;
435 // Load template file
436 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
437 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
438 fs.closeSync(fileDescriptor);
440 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
442 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
443 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
444 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
445 const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length);
446 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
447 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
448 : stationTemplateFromFile.power[powerArrayRandomIndex];
450 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
451 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
452 ? stationTemplateFromFile.power * 1000
453 : stationTemplateFromFile.power;
455 delete stationInfo.power;
456 delete stationInfo.powerUnit;
457 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
458 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
462 private getOCPPVersion(): OCPPVersion {
463 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
466 private handleUnsupportedVersion(version: OCPPVersion) {
467 const errMsg = `${this.logPrefix()} Unsupported protocol version
'${version}' configured
in template file ${this.stationTemplateFile}
`;
468 logger.error(errMsg);
469 throw new Error(errMsg);
472 private initialize(): void {
473 this.stationInfo = this.buildStationInfo();
474 this.bootNotificationRequest = {
475 chargePointModel: this.stationInfo.chargePointModel,
476 chargePointVendor: this.stationInfo.chargePointVendor,
477 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
478 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
480 this.configuration = this.getTemplateChargingStationConfiguration();
481 this.supervisionUrl = this.getSupervisionURL();
482 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
483 // Build connectors if needed
484 const maxConnectors = this.getMaxNumberOfConnectors();
485 if (maxConnectors <= 0) {
486 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with ${maxConnectors} connectors
`);
488 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
489 if (templateMaxConnectors <= 0) {
490 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector configuration
`);
492 if (!this.stationInfo.Connectors[0]) {
493 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector Id
0 configuration
`);
496 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
497 logger.warn(`${this.logPrefix()}
Number of connectors exceeds the
number of connector configurations
in template ${this.stationTemplateFile}
, forcing random connector configurations affectation
`);
498 this.stationInfo.randomConnectors = true;
500 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
501 // FIXME: Handle shrinking the number of connectors
502 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
503 this.connectorsConfigurationHash = connectorsConfigHash;
504 // Add connector Id 0
505 let lastConnector = '0';
506 for (lastConnector in this.stationInfo.Connectors) {
507 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
508 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
509 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
510 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
511 this.connectors[lastConnector].chargingProfiles = [];
515 // Generate all connectors
516 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
517 for (let index = 1; index <= maxConnectors; index++) {
518 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
519 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]);
520 this.connectors[index].availability = AvailabilityType.OPERATIVE;
521 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
522 this.connectors[index].chargingProfiles = [];
527 // Avoid duplication of connectors related information
528 delete this.stationInfo.Connectors;
529 // Initialize transaction attributes on connectors
530 for (const connector in this.connectors) {
531 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
532 this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
535 switch (this.getOCPPVersion()) {
536 case OCPPVersion.VERSION_16:
537 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
538 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
541 this.handleUnsupportedVersion(this.getOCPPVersion());
545 this.initOCPPParameters();
546 this.stationInfo.powerDivider = this.getPowerDivider();
547 if (this.getEnableStatistics()) {
548 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId);
549 this.performanceObserver = new PerformanceObserver((list) => {
550 const entry = list.getEntries()[0];
551 this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
552 this.performanceObserver.disconnect();
557 private initOCPPParameters(): void {
558 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
559 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core}
,${SupportedFeatureProfiles.Local_Auth_List_Management}
,${SupportedFeatureProfiles.Smart_Charging}
`);
561 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
562 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
563 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
565 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
566 const connectorPhaseRotation = [];
567 for (const connector in this.connectors) {
569 if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) {
570 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
571 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) {
572 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
574 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) {
575 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
576 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) {
577 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
580 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
582 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
583 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
585 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
586 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
587 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
589 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
590 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
594 private async onOpen(): Promise<void> {
595 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}
`);
596 if (!this.isRegistered()) {
597 // Send BootNotification
598 let registrationRetryCount = 0;
600 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
601 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
602 if (!this.isRegistered()) {
603 registrationRetryCount++;
604 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
606 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
608 if (this.isRegistered()) {
609 await this.startMessageSequence();
610 this.hasStopped && (this.hasStopped = false);
611 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
612 this.flushMessageQueue();
615 logger.error(`${this.logPrefix()} Registration failure
: max retries
reached (${this.getRegistrationMaxRetries()}
) or retry
disabled (${this.getRegistrationMaxRetries()}
)`);
617 this.autoReconnectRetryCount = 0;
618 this.hasSocketRestarted = false;
621 private async onClose(closeEvent: any): Promise<void> {
622 switch (closeEvent) {
623 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
624 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
625 logger.info(`${this.logPrefix()} Socket normally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
626 this.autoReconnectRetryCount = 0;
628 default: // Abnormal close
629 logger.error(`${this.logPrefix()} Socket abnormally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
630 await this.reconnect(closeEvent);
635 private async onMessage(messageEvent: MessageEvent): Promise<void> {
636 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
637 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
638 let rejectCallback: (error: OCPPError) => void;
639 let requestPayload: Record<string, unknown>;
643 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
644 // Check the Type of message
645 switch (messageType) {
647 case MessageType.CALL_MESSAGE:
648 if (this.getEnableStatistics()) {
649 this.performanceStatistics.addMessage(commandName, messageType);
652 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
655 case MessageType.CALL_RESULT_MESSAGE:
657 if (Utils.isIterable(this.requests[messageId])) {
658 [responseCallback, , requestPayload] = this.requests[messageId];
660 throw new Error(`Response request
for message id ${messageId}
is not iterable
`);
662 if (!responseCallback) {
664 throw new Error(`Response request
for unknown message id ${messageId}
`);
666 delete this.requests[messageId];
667 responseCallback(commandName, requestPayload);
670 case MessageType.CALL_ERROR_MESSAGE:
671 if (!this.requests[messageId]) {
673 throw new Error(`Error request
for unknown message id ${messageId}
`);
675 if (Utils.isIterable(this.requests[messageId])) {
676 [, rejectCallback] = this.requests[messageId];
678 throw new Error(`Error request
for message id ${messageId}
is not iterable
`);
680 delete this.requests[messageId];
681 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
685 errMsg = `${this.logPrefix()} Wrong message
type ${messageType}
`;
686 logger.error(errMsg);
687 throw new Error(errMsg);
691 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
693 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
697 private onPing(): void {
698 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
701 private onPong(): void {
702 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
705 private async onError(errorEvent: any): Promise<void> {
706 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
707 // switch (errorEvent.code) {
708 // case 'ECONNREFUSED':
709 // await this._reconnect(errorEvent);
714 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
715 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
718 private getAuthorizationFile(): string | undefined {
719 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
722 private getAuthorizedTags(): string[] {
723 let authorizedTags: string[] = [];
724 const authorizationFile = this.getAuthorizationFile();
725 if (authorizationFile) {
727 // Load authorization file
728 const fileDescriptor = fs.openSync(authorizationFile, 'r');
729 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
730 fs.closeSync(fileDescriptor);
732 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
735 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
737 return authorizedTags;
740 private getUseConnectorId0(): boolean | undefined {
741 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
744 private getNumberOfRunningTransactions(): number {
746 for (const connector in this.connectors) {
747 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
755 private getConnectionTimeout(): number | undefined {
756 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
757 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
759 return Constants.DEFAULT_CONNECTION_TIMEOUT;
762 // -1 for unlimited, 0 for disabling
763 private getAutoReconnectMaxRetries(): number | undefined {
764 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
765 return this.stationInfo.autoReconnectMaxRetries;
767 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
768 return Configuration.getAutoReconnectMaxRetries();
774 private getRegistrationMaxRetries(): number | undefined {
775 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
776 return this.stationInfo.registrationMaxRetries;
781 private getPowerDivider(): number {
782 let powerDivider = this.getNumberOfConnectors();
783 if (this.stationInfo.powerSharedByConnectors) {
784 powerDivider = this.getNumberOfRunningTransactions();
789 private getTemplateMaxNumberOfConnectors(): number {
790 return Object.keys(this.stationInfo.Connectors).length;
793 private getMaxNumberOfConnectors(): number {
794 let maxConnectors = 0;
795 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
796 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
797 // Distribute evenly the number of connectors
798 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
799 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
800 maxConnectors = this.stationInfo.numberOfConnectors as number;
802 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
804 return maxConnectors;
807 private getNumberOfConnectors(): number {
808 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
811 private async startMessageSequence(): Promise<void> {
812 // Start WebSocket ping
813 this.startWebSocketPing();
815 this.startHeartbeat();
816 // Initialize connectors status
817 for (const connector in this.connectors) {
818 if (Utils.convertToInt(connector) === 0) {
820 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
821 // Send status in template at startup
822 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
823 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
824 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
825 // Send status in template after reset
826 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
827 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
828 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
829 // Send previous status at template reload
830 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
832 // Send default status
833 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
834 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
838 this.startAutomaticTransactionGenerator();
839 if (this.getEnableStatistics()) {
840 this.performanceStatistics.start();
844 private startAutomaticTransactionGenerator() {
845 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
846 if (!this.automaticTransactionGeneration) {
847 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
849 if (this.automaticTransactionGeneration.timeToStop) {
850 // The ATG might sleep
851 void this.automaticTransactionGeneration.start();
856 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
857 // Stop WebSocket ping
858 this.stopWebSocketPing();
860 this.stopHeartbeat();
862 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
863 this.automaticTransactionGeneration &&
864 !this.automaticTransactionGeneration.timeToStop) {
865 await this.automaticTransactionGeneration.stop(reason);
867 for (const connector in this.connectors) {
868 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
869 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
870 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
871 this.getTransactionIdTag(transactionId), reason);
877 private startWebSocketPing(): void {
878 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
879 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
881 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
882 this.webSocketPingSetInterval = setInterval(() => {
883 if (this.isWebSocketOpen()) {
884 this.wsConnection.ping((): void => { });
886 }, webSocketPingInterval * 1000);
887 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
888 } else if (this.webSocketPingSetInterval) {
889 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
891 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}
, not starting the WebSocket ping
`);
895 private stopWebSocketPing(): void {
896 if (this.webSocketPingSetInterval) {
897 clearInterval(this.webSocketPingSetInterval);
901 private getSupervisionURL(): string {
902 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
904 if (!Utils.isEmptyArray(supervisionUrls)) {
905 if (Configuration.getDistributeStationsToTenantsEqually()) {
906 indexUrl = this.index % supervisionUrls.length;
909 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
911 return supervisionUrls[indexUrl];
913 return supervisionUrls as string;
916 private getHeartbeatInterval(): number | undefined {
917 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
918 if (HeartbeatInterval) {
919 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
921 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
922 if (HeartBeatInterval) {
923 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
927 private stopHeartbeat(): void {
928 if (this.heartbeatSetInterval) {
929 clearInterval(this.heartbeatSetInterval);
933 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
934 options ?? {} as WebSocket.ClientOptions;
935 options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
936 if (this.isWebSocketOpen() && forceCloseOpened) {
937 this.wsConnection.close();
940 switch (this.getOCPPVersion()) {
941 case OCPPVersion.VERSION_16:
942 protocol = 'ocpp' + OCPPVersion.VERSION_16;
945 this.handleUnsupportedVersion(this.getOCPPVersion());
948 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
949 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
952 private stopMeterValues(connectorId: number) {
953 if (this.getConnector(connectorId)?.transactionSetInterval) {
954 clearInterval(this.getConnector(connectorId).transactionSetInterval);
958 private startAuthorizationFileMonitoring(): void {
959 const authorizationFile = this.getAuthorizationFile();
960 if (authorizationFile) {
962 fs.watch(authorizationFile).on('change', () => {
964 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
965 // Initialize authorizedTags
966 this.authorizedTags = this.getAuthorizedTags();
968 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
972 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
975 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
979 private startStationTemplateFileMonitoring(): void {
981 // eslint-disable-next-line @typescript-eslint/no-misused-promises
982 fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => {
984 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
988 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
989 this.automaticTransactionGeneration) {
990 await this.automaticTransactionGeneration.stop();
993 this.startAutomaticTransactionGenerator();
994 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
996 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1000 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
1004 private getReconnectExponentialDelay(): boolean | undefined {
1005 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1008 private async reconnect(error: any): Promise<void> {
1010 this.stopHeartbeat();
1011 // Stop the ATG if needed
1012 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1013 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1014 this.automaticTransactionGeneration &&
1015 !this.automaticTransactionGeneration.timeToStop) {
1016 await this.automaticTransactionGeneration.stop();
1018 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1019 this.autoReconnectRetryCount++;
1020 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1021 logger.error(`${this.logPrefix()} Socket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectDelay - 100}ms
`);
1022 await Utils.sleep(reconnectDelay);
1023 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1024 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
1025 this.hasSocketRestarted = true;
1026 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1027 logger.error(`${this.logPrefix()} Socket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1031 private initTransactionAttributesOnConnector(connectorId: number): void {
1032 this.getConnector(connectorId).authorized = false;
1033 this.getConnector(connectorId).transactionStarted = false;
1034 this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
1035 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;