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 !Utils
.isUndefined(this.stationInfo
.currentOutType
) ? 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 getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
173 if (this.getMeteringPerTransaction()) {
174 for (const connector
in this.connectors
) {
175 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
176 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
180 for (const connector
in this.connectors
) {
181 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
182 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
187 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
188 if (this.getMeteringPerTransaction()) {
189 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
191 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
194 public getAuthorizeRemoteTxRequests(): boolean {
195 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
196 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
199 public getLocalAuthListEnabled(): boolean {
200 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
201 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
204 public restartWebSocketPing(): void {
205 // Stop WebSocket ping
206 this.stopWebSocketPing();
207 // Start WebSocket ping
208 this.startWebSocketPing();
211 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
212 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
213 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
214 logger
.warn(`${this.logPrefix()} Unsupported MeterValues measurand ${measurand} in template on connectorId ${connectorId}`);
217 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
218 let defaultMeasurandFound
= false;
219 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
220 if (phase
&& sampledValueTemplates
[index
]?.phase
=== phase
&& sampledValueTemplates
[index
]?.measurand
=== measurand
221 && this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(measurand
)) {
222 return sampledValueTemplates
[index
];
223 } else if (!phase
&& !sampledValueTemplates
[index
].phase
&& sampledValueTemplates
[index
]?.measurand
=== measurand
224 && this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(measurand
)) {
225 return sampledValueTemplates
[index
];
226 } else if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
227 && (!sampledValueTemplates
[index
].measurand
|| sampledValueTemplates
[index
].measurand
=== measurand
)) {
228 defaultMeasurandFound
= true;
229 return sampledValueTemplates
[index
];
232 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&& !defaultMeasurandFound
) {
233 logger
.error(`${this.logPrefix()} Missing MeterValues for default measurand ${MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} in template on connectorId ${connectorId}`);
235 logger
.debug(`${this.logPrefix()} No MeterValues for measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
238 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
239 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
242 public startHeartbeat(): void {
243 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
244 // eslint-disable-next-line @typescript-eslint/no-misused-promises
245 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
246 await this.ocppRequestService.sendHeartbeat();
247 }, this.getHeartbeatInterval());
248 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
249 } else if (this.heartbeatSetInterval) {
250 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
252 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}
, not starting the heartbeat
`);
256 public restartHeartbeat(): void {
258 this.stopHeartbeat();
260 this.startHeartbeat();
263 public startMeterValues(connectorId: number, interval: number): void {
264 if (connectorId === 0) {
265 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}
`);
268 if (!this.getConnector(connectorId)) {
269 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}
`);
272 if (!this.getConnector(connectorId)?.transactionStarted) {
273 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId}
with no transaction started
`);
275 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
276 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId}
with no transaction id
`);
280 // eslint-disable-next-line @typescript-eslint/no-misused-promises
281 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
282 if (this.getEnableStatistics()) {
283 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
284 this.performanceObserver.observe({
285 entryTypes: ['function'],
287 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
289 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
293 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}
, not sending MeterValues
`);
297 public start(): void {
298 this.openWSConnection();
299 // Monitor authorization file
300 this.startAuthorizationFileMonitoring();
301 // Monitor station template file
302 this.startStationTemplateFileMonitoring();
303 // Handle Socket incoming messages
304 this.wsConnection.on('message', this.onMessage.bind(this));
305 // Handle Socket error
306 this.wsConnection.on('error', this.onError.bind(this));
307 // Handle Socket close
308 this.wsConnection.on('close', this.onClose.bind(this));
309 // Handle Socket opening connection
310 this.wsConnection.on('open', this.onOpen.bind(this));
311 // Handle Socket ping
312 this.wsConnection.on('ping', this.onPing.bind(this));
313 // Handle Socket pong
314 this.wsConnection.on('pong', this.onPong.bind(this));
317 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
318 // Stop message sequence
319 await this.stopMessageSequence(reason);
320 for (const connector in this.connectors) {
321 if (Utils.convertToInt(connector) > 0) {
322 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
323 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
326 if (this.isWebSocketOpen()) {
327 this.wsConnection.close();
329 this.bootNotificationResponse = null;
330 this.hasStopped = true;
333 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
334 const configurationKey: ConfigurationKey | undefined = this.configuration.configurationKey.find((configElement) => {
335 if (caseInsensitive) {
336 return configElement.key.toLowerCase() === key.toLowerCase();
338 return configElement.key === key;
340 return configurationKey;
343 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
344 const keyFound = this.getConfigurationKey(key);
346 this.configuration.configurationKey.push({
354 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key
: %j
`, keyFound);
358 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
359 const keyFound = this.getConfigurationKey(key);
361 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
362 this.configuration.configurationKey[keyIndex].value = value;
364 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key
: %j
`, { key, value });
368 public setChargingProfile(connectorId: number, cp: ChargingProfile): boolean {
369 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
370 this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
371 if (chargingProfile.chargingProfileId === cp.chargingProfileId
372 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
373 this.getConnector(connectorId).chargingProfiles[index] = cp;
378 this.getConnector(connectorId).chargingProfiles?.push(cp);
382 public resetTransactionOnConnector(connectorId: number): void {
383 this.getConnector(connectorId).transactionStarted = false;
384 delete this.getConnector(connectorId).transactionId;
385 delete this.getConnector(connectorId).idTag;
386 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
387 delete this.getConnector(connectorId).transactionBeginMeterValue;
388 this.stopMeterValues(connectorId);
391 public addToMessageQueue(message: string): void {
393 // Handle dups in message queue
394 for (const bufferedMessage of this.messageQueue) {
395 // Message already in the queue
396 if (message === bufferedMessage) {
403 this.messageQueue.push(message);
407 private flushMessageQueue() {
408 if (!Utils.isEmptyArray(this.messageQueue)) {
409 this.messageQueue.forEach((message, index) => {
410 this.messageQueue.splice(index, 1);
411 this.wsConnection.send(message);
416 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
417 // In case of multiple instances: add instance index to charging station id
418 let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
419 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
420 const idSuffix = stationTemplate.nameSuffix ?? '';
421 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
424 private buildStationInfo(): ChargingStationInfo {
425 let stationTemplateFromFile: ChargingStationTemplate;
427 // Load template file
428 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
429 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
430 fs.closeSync(fileDescriptor);
432 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
434 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
435 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
436 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
437 const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length);
438 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
439 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
440 : stationTemplateFromFile.power[powerArrayRandomIndex];
442 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
443 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
444 ? stationTemplateFromFile.power * 1000
445 : stationTemplateFromFile.power;
447 delete stationInfo.power;
448 delete stationInfo.powerUnit;
449 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
450 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
454 private getOCPPVersion(): OCPPVersion {
455 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
458 private handleUnsupportedVersion(version: OCPPVersion) {
459 const errMsg = `${this.logPrefix()} Unsupported protocol version
'${version}' configured
in template file ${this.stationTemplateFile}
`;
460 logger.error(errMsg);
461 throw new Error(errMsg);
464 private initialize(): void {
465 this.stationInfo = this.buildStationInfo();
466 this.bootNotificationRequest = {
467 chargePointModel: this.stationInfo.chargePointModel,
468 chargePointVendor: this.stationInfo.chargePointVendor,
469 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
470 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
472 this.configuration = this.getTemplateChargingStationConfiguration();
473 this.supervisionUrl = this.getSupervisionURL();
474 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
475 // Build connectors if needed
476 const maxConnectors = this.getMaxNumberOfConnectors();
477 if (maxConnectors <= 0) {
478 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with ${maxConnectors} connectors
`);
480 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
481 if (templateMaxConnectors <= 0) {
482 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector configuration
`);
484 if (!this.stationInfo.Connectors[0]) {
485 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector Id
0 configuration
`);
488 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
489 logger.warn(`${this.logPrefix()}
Number of connectors exceeds the
number of connector configurations
in template ${this.stationTemplateFile}
, forcing random connector configurations affectation
`);
490 this.stationInfo.randomConnectors = true;
492 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
493 // FIXME: Handle shrinking the number of connectors
494 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
495 this.connectorsConfigurationHash = connectorsConfigHash;
496 // Add connector Id 0
497 let lastConnector = '0';
498 for (lastConnector in this.stationInfo.Connectors) {
499 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
500 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
501 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
502 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
503 this.connectors[lastConnector].chargingProfiles = [];
507 // Generate all connectors
508 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
509 for (let index = 1; index <= maxConnectors; index++) {
510 const randConnectorID = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
511 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorID]);
512 this.connectors[index].availability = AvailabilityType.OPERATIVE;
513 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
514 this.connectors[index].chargingProfiles = [];
519 // Avoid duplication of connectors related information
520 delete this.stationInfo.Connectors;
521 // Initialize transaction attributes on connectors
522 for (const connector in this.connectors) {
523 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
524 this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
527 switch (this.getOCPPVersion()) {
528 case OCPPVersion.VERSION_16:
529 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
530 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
533 this.handleUnsupportedVersion(this.getOCPPVersion());
537 this.initOCPPParameters();
538 this.stationInfo.powerDivider = this.getPowerDivider();
539 if (this.getEnableStatistics()) {
540 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId);
541 this.performanceObserver = new PerformanceObserver((list) => {
542 const entry = list.getEntries()[0];
543 this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
544 this.performanceObserver.disconnect();
549 private initOCPPParameters(): void {
550 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
551 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core}
,${SupportedFeatureProfiles.Local_Auth_List_Management}
,${SupportedFeatureProfiles.Smart_Charging}
`);
553 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
554 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
555 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
557 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
558 const connectorPhaseRotation = [];
559 for (const connector in this.connectors) {
561 if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) {
562 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
563 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) {
564 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
566 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) {
567 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
568 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) {
569 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
572 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
574 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
575 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
577 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
578 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
579 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
581 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
582 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
586 private async onOpen(): Promise<void> {
587 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}
`);
588 if (!this.isRegistered()) {
589 // Send BootNotification
590 let registrationRetryCount = 0;
592 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
593 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
594 if (!this.isRegistered()) {
595 registrationRetryCount++;
596 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
598 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
600 if (this.isRegistered()) {
601 await this.startMessageSequence();
602 this.hasStopped && (this.hasStopped = false);
603 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
604 this.flushMessageQueue();
607 logger.error(`${this.logPrefix()} Registration failure
: max retries
reached (${this.getRegistrationMaxRetries()}
) or retry
disabled (${this.getRegistrationMaxRetries()}
)`);
609 this.autoReconnectRetryCount = 0;
610 this.hasSocketRestarted = false;
613 private async onClose(closeEvent: any): Promise<void> {
614 switch (closeEvent) {
615 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
616 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
617 logger.info(`${this.logPrefix()} Socket normally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
618 this.autoReconnectRetryCount = 0;
620 default: // Abnormal close
621 logger.error(`${this.logPrefix()} Socket abnormally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
622 await this.reconnect(closeEvent);
627 private async onMessage(messageEvent: MessageEvent): Promise<void> {
628 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
629 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
630 let rejectCallback: (error: OCPPError) => void;
631 let requestPayload: Record<string, unknown>;
635 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
636 // Check the Type of message
637 switch (messageType) {
639 case MessageType.CALL_MESSAGE:
640 if (this.getEnableStatistics()) {
641 this.performanceStatistics.addMessage(commandName, messageType);
644 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
647 case MessageType.CALL_RESULT_MESSAGE:
649 if (Utils.isIterable(this.requests[messageId])) {
650 [responseCallback, , requestPayload] = this.requests[messageId];
652 throw new Error(`Response request
for message id ${messageId}
is not iterable
`);
654 if (!responseCallback) {
656 throw new Error(`Response request
for unknown message id ${messageId}
`);
658 delete this.requests[messageId];
659 responseCallback(commandName, requestPayload);
662 case MessageType.CALL_ERROR_MESSAGE:
663 if (!this.requests[messageId]) {
665 throw new Error(`Error request
for unknown message id ${messageId}
`);
667 if (Utils.isIterable(this.requests[messageId])) {
668 [, rejectCallback] = this.requests[messageId];
670 throw new Error(`Error request
for message id ${messageId}
is not iterable
`);
672 delete this.requests[messageId];
673 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
677 errMsg = `${this.logPrefix()} Wrong message
type ${messageType}
`;
678 logger.error(errMsg);
679 throw new Error(errMsg);
683 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
685 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
689 private onPing(): void {
690 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
693 private onPong(): void {
694 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
697 private async onError(errorEvent: any): Promise<void> {
698 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
699 // switch (errorEvent.code) {
700 // case 'ECONNREFUSED':
701 // await this._reconnect(errorEvent);
706 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
707 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
710 private getAuthorizationFile(): string | undefined {
711 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
714 private getAuthorizedTags(): string[] {
715 let authorizedTags: string[] = [];
716 const authorizationFile = this.getAuthorizationFile();
717 if (authorizationFile) {
719 // Load authorization file
720 const fileDescriptor = fs.openSync(authorizationFile, 'r');
721 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
722 fs.closeSync(fileDescriptor);
724 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
727 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
729 return authorizedTags;
732 private getUseConnectorId0(): boolean | undefined {
733 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
736 private getNumberOfRunningTransactions(): number {
738 for (const connector in this.connectors) {
739 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
747 private getConnectionTimeout(): number | undefined {
748 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
749 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
751 return Constants.DEFAULT_CONNECTION_TIMEOUT;
754 // -1 for unlimited, 0 for disabling
755 private getAutoReconnectMaxRetries(): number | undefined {
756 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
757 return this.stationInfo.autoReconnectMaxRetries;
759 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
760 return Configuration.getAutoReconnectMaxRetries();
766 private getRegistrationMaxRetries(): number | undefined {
767 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
768 return this.stationInfo.registrationMaxRetries;
773 private getPowerDivider(): number {
774 let powerDivider = this.getNumberOfConnectors();
775 if (this.stationInfo.powerSharedByConnectors) {
776 powerDivider = this.getNumberOfRunningTransactions();
781 private getTemplateMaxNumberOfConnectors(): number {
782 return Object.keys(this.stationInfo.Connectors).length;
785 private getMaxNumberOfConnectors(): number {
786 let maxConnectors = 0;
787 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
788 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
789 // Distribute evenly the number of connectors
790 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
791 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
792 maxConnectors = this.stationInfo.numberOfConnectors as number;
794 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
796 return maxConnectors;
799 private getNumberOfConnectors(): number {
800 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
803 private async startMessageSequence(): Promise<void> {
804 // Start WebSocket ping
805 this.startWebSocketPing();
807 this.startHeartbeat();
808 // Initialize connectors status
809 for (const connector in this.connectors) {
810 if (Utils.convertToInt(connector) === 0) {
812 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
813 // Send status in template at startup
814 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
815 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
816 } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
817 // Send status in template after reset
818 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
819 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
820 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
821 // Send previous status at template reload
822 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
824 // Send default status
825 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
826 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
830 this.startAutomaticTransactionGenerator();
831 if (this.getEnableStatistics()) {
832 this.performanceStatistics.start();
836 private startAutomaticTransactionGenerator() {
837 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
838 if (!this.automaticTransactionGeneration) {
839 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
841 if (this.automaticTransactionGeneration.timeToStop) {
842 // The ATG might sleep
843 void this.automaticTransactionGeneration.start();
848 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
849 // Stop WebSocket ping
850 this.stopWebSocketPing();
852 this.stopHeartbeat();
854 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
855 this.automaticTransactionGeneration &&
856 !this.automaticTransactionGeneration.timeToStop) {
857 await this.automaticTransactionGeneration.stop(reason);
859 for (const connector in this.connectors) {
860 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
861 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
862 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
863 this.getTransactionIdTag(transactionId), reason);
869 private startWebSocketPing(): void {
870 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
871 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
873 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
874 this.webSocketPingSetInterval = setInterval(() => {
875 if (this.isWebSocketOpen()) {
876 this.wsConnection.ping((): void => { });
878 }, webSocketPingInterval * 1000);
879 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
880 } else if (this.webSocketPingSetInterval) {
881 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
883 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}
, not starting the WebSocket ping
`);
887 private stopWebSocketPing(): void {
888 if (this.webSocketPingSetInterval) {
889 clearInterval(this.webSocketPingSetInterval);
893 private getSupervisionURL(): string {
894 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
896 if (!Utils.isEmptyArray(supervisionUrls)) {
897 if (Configuration.getDistributeStationsToTenantsEqually()) {
898 indexUrl = this.index % supervisionUrls.length;
901 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
903 return supervisionUrls[indexUrl];
905 return supervisionUrls as string;
908 private getHeartbeatInterval(): number | undefined {
909 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
910 if (HeartbeatInterval) {
911 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
913 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
914 if (HeartBeatInterval) {
915 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
919 private stopHeartbeat(): void {
920 if (this.heartbeatSetInterval) {
921 clearInterval(this.heartbeatSetInterval);
925 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
926 options ?? {} as WebSocket.ClientOptions;
927 options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
928 if (this.isWebSocketOpen() && forceCloseOpened) {
929 this.wsConnection.close();
932 switch (this.getOCPPVersion()) {
933 case OCPPVersion.VERSION_16:
934 protocol = 'ocpp' + OCPPVersion.VERSION_16;
937 this.handleUnsupportedVersion(this.getOCPPVersion());
940 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
941 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
944 private stopMeterValues(connectorId: number) {
945 if (this.getConnector(connectorId)?.transactionSetInterval) {
946 clearInterval(this.getConnector(connectorId).transactionSetInterval);
950 private startAuthorizationFileMonitoring(): void {
951 const authorizationFile = this.getAuthorizationFile();
952 if (authorizationFile) {
954 fs.watch(authorizationFile).on('change', () => {
956 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
957 // Initialize authorizedTags
958 this.authorizedTags = this.getAuthorizedTags();
960 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
964 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
967 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
971 private startStationTemplateFileMonitoring(): void {
973 // eslint-disable-next-line @typescript-eslint/no-misused-promises
974 fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => {
976 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
980 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
981 this.automaticTransactionGeneration) {
982 await this.automaticTransactionGeneration.stop();
985 this.startAutomaticTransactionGenerator();
986 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
988 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
992 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
996 private getReconnectExponentialDelay(): boolean | undefined {
997 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1000 private async reconnect(error: any): Promise<void> {
1002 this.stopHeartbeat();
1003 // Stop the ATG if needed
1004 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1005 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1006 this.automaticTransactionGeneration &&
1007 !this.automaticTransactionGeneration.timeToStop) {
1008 await this.automaticTransactionGeneration.stop();
1010 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1011 this.autoReconnectRetryCount++;
1012 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1013 logger.error(`${this.logPrefix()} Socket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectDelay - 100}ms
`);
1014 await Utils.sleep(reconnectDelay);
1015 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1016 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
1017 this.hasSocketRestarted = true;
1018 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1019 logger.error(`${this.logPrefix()} Socket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1023 private initTransactionAttributesOnConnector(connectorId: number): void {
1024 this.getConnector(connectorId).transactionStarted = false;
1025 this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
1026 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;