1 import { BootNotificationResponse
, RegistrationStatus
} from
'../types/ocpp/Responses';
2 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
3 import ChargingStationTemplate
, { CurrentType
, PowerUnits
, Voltage
} 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 getMayAuthorizeAtRemoteStart(): boolean | undefined {
95 return this.stationInfo
.mayAuthorizeAtRemoteStart
?? true;
98 public getNumberOfPhases(): number | undefined {
99 switch (this.getCurrentOutType()) {
101 return !Utils
.isUndefined(this.stationInfo
.numberOfPhases
) ? this.stationInfo
.numberOfPhases
: 3;
107 public isWebSocketOpen(): boolean {
108 return this.wsConnection
?.readyState
=== WebSocket
.OPEN
;
111 public isRegistered(): boolean {
112 return this.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
115 public isChargingStationAvailable(): boolean {
116 return this.getConnector(0).availability
=== AvailabilityType
.OPERATIVE
;
119 public isConnectorAvailable(id
: number): boolean {
120 return this.getConnector(id
).availability
=== AvailabilityType
.OPERATIVE
;
123 public getConnector(id
: number): Connector
{
124 return this.connectors
[id
];
127 public getCurrentOutType(): CurrentType
| undefined {
128 return this.stationInfo
.currentOutType
?? CurrentType
.AC
;
131 public getVoltageOut(): number | undefined {
132 const errMsg
= `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`;
133 let defaultVoltageOut
: number;
134 switch (this.getCurrentOutType()) {
136 defaultVoltageOut
= Voltage
.VOLTAGE_230
;
139 defaultVoltageOut
= Voltage
.VOLTAGE_400
;
142 logger
.error(errMsg
);
145 return !Utils
.isUndefined(this.stationInfo
.voltageOut
) ? this.stationInfo
.voltageOut
: defaultVoltageOut
;
148 public getTransactionIdTag(transactionId
: number): string | undefined {
149 for (const connector
in this.connectors
) {
150 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
151 return this.getConnector(Utils
.convertToInt(connector
)).transactionIdTag
;
156 public getOutOfOrderEndMeterValues(): boolean {
157 return this.stationInfo
.outOfOrderEndMeterValues
?? false;
160 public getBeginEndMeterValues(): boolean {
161 return this.stationInfo
.beginEndMeterValues
?? false;
164 public getMeteringPerTransaction(): boolean {
165 return this.stationInfo
.meteringPerTransaction
?? true;
168 public getTransactionDataMeterValues(): boolean {
169 return this.stationInfo
.transactionDataMeterValues
?? false;
172 public getMainVoltageMeterValues(): boolean {
173 return this.stationInfo
.mainVoltageMeterValues
?? true;
176 public getPhaseLineToLineVoltageMeterValues(): boolean {
177 return this.stationInfo
.phaseLineToLineVoltageMeterValues
?? false;
180 public getEnergyActiveImportRegisterByTransactionId(transactionId
: number): number | undefined {
181 if (this.getMeteringPerTransaction()) {
182 for (const connector
in this.connectors
) {
183 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
184 return this.getConnector(Utils
.convertToInt(connector
)).transactionEnergyActiveImportRegisterValue
;
188 for (const connector
in this.connectors
) {
189 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
190 return this.getConnector(Utils
.convertToInt(connector
)).energyActiveImportRegisterValue
;
195 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number | undefined {
196 if (this.getMeteringPerTransaction()) {
197 return this.getConnector(connectorId
).transactionEnergyActiveImportRegisterValue
;
199 return this.getConnector(connectorId
).energyActiveImportRegisterValue
;
202 public getAuthorizeRemoteTxRequests(): boolean {
203 const authorizeRemoteTxRequests
= this.getConfigurationKey(StandardParametersKey
.AuthorizeRemoteTxRequests
);
204 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
207 public getLocalAuthListEnabled(): boolean {
208 const localAuthListEnabled
= this.getConfigurationKey(StandardParametersKey
.LocalAuthListEnabled
);
209 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
212 public restartWebSocketPing(): void {
213 // Stop WebSocket ping
214 this.stopWebSocketPing();
215 // Start WebSocket ping
216 this.startWebSocketPing();
219 public getSampledValueTemplate(connectorId
: number, measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
220 phase
?: MeterValuePhase
): SampledValueTemplate
| undefined {
221 if (!Constants
.SUPPORTED_MEASURANDS
.includes(measurand
)) {
222 logger
.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
225 if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) {
226 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`);
229 const sampledValueTemplates
: SampledValueTemplate
[] = this.getConnector(connectorId
).MeterValues
;
230 for (let index
= 0; !Utils
.isEmptyArray(sampledValueTemplates
) && index
< sampledValueTemplates
.length
; index
++) {
231 if (phase
&& sampledValueTemplates
[index
]?.phase
=== phase
&& sampledValueTemplates
[index
]?.measurand
=== measurand
232 && this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(measurand
)) {
233 return sampledValueTemplates
[index
];
234 } else if (!phase
&& !sampledValueTemplates
[index
].phase
&& sampledValueTemplates
[index
]?.measurand
=== measurand
235 && this.getConfigurationKey(StandardParametersKey
.MeterValuesSampledData
).value
.includes(measurand
)) {
236 return sampledValueTemplates
[index
];
237 } else if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
238 && (!sampledValueTemplates
[index
].measurand
|| sampledValueTemplates
[index
].measurand
=== measurand
)) {
239 return sampledValueTemplates
[index
];
242 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
243 logger
.error(`${this.logPrefix()} Missing MeterValues for default measurand ${measurand} in template on connectorId ${connectorId}`);
245 logger
.debug(`${this.logPrefix()} No MeterValues for measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}
`);
248 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
249 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
252 public startHeartbeat(): void {
253 if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) {
254 // eslint-disable-next-line @typescript-eslint/no-misused-promises
255 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
256 await this.ocppRequestService.sendHeartbeat();
257 }, this.getHeartbeatInterval());
258 logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
259 } else if (this.heartbeatSetInterval) {
260 logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()));
262 logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}
, not starting the heartbeat
`);
266 public restartHeartbeat(): void {
268 this.stopHeartbeat();
270 this.startHeartbeat();
273 public startMeterValues(connectorId: number, interval: number): void {
274 if (connectorId === 0) {
275 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}
`);
278 if (!this.getConnector(connectorId)) {
279 logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}
`);
282 if (!this.getConnector(connectorId)?.transactionStarted) {
283 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId}
with no transaction started
`);
285 } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) {
286 logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId}
with no transaction id
`);
290 // eslint-disable-next-line @typescript-eslint/no-misused-promises
291 this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => {
292 if (this.getEnableStatistics()) {
293 const sendMeterValues = performance.timerify(this.ocppRequestService.sendMeterValues);
294 this.performanceObserver.observe({
295 entryTypes: ['function'],
297 await sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
299 await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval, this.ocppRequestService);
303 logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}
, not sending MeterValues
`);
307 public start(): void {
308 this.openWSConnection();
309 // Monitor authorization file
310 this.startAuthorizationFileMonitoring();
311 // Monitor station template file
312 this.startStationTemplateFileMonitoring();
313 // Handle Socket incoming messages
314 this.wsConnection.on('message', this.onMessage.bind(this));
315 // Handle Socket error
316 this.wsConnection.on('error', this.onError.bind(this));
317 // Handle Socket close
318 this.wsConnection.on('close', this.onClose.bind(this));
319 // Handle Socket opening connection
320 this.wsConnection.on('open', this.onOpen.bind(this));
321 // Handle Socket ping
322 this.wsConnection.on('ping', this.onPing.bind(this));
323 // Handle Socket pong
324 this.wsConnection.on('pong', this.onPong.bind(this));
327 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
328 // Stop message sequence
329 await this.stopMessageSequence(reason);
330 for (const connector in this.connectors) {
331 if (Utils.convertToInt(connector) > 0) {
332 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
333 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE;
336 if (this.isWebSocketOpen()) {
337 this.wsConnection.close();
339 this.bootNotificationResponse = null;
340 this.hasStopped = true;
343 public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined {
344 const configurationKey: ConfigurationKey | undefined = this.configuration.configurationKey.find((configElement) => {
345 if (caseInsensitive) {
346 return configElement.key.toLowerCase() === key.toLowerCase();
348 return configElement.key === key;
350 return configurationKey;
353 public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void {
354 const keyFound = this.getConfigurationKey(key);
356 this.configuration.configurationKey.push({
364 logger.error(`${this.logPrefix()} Trying to add an already existing configuration key
: %j
`, keyFound);
368 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
369 const keyFound = this.getConfigurationKey(key);
371 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
372 this.configuration.configurationKey[keyIndex].value = value;
374 logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key
: %j
`, { key, value });
378 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
379 let cpReplaced = false;
380 if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) {
381 this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => {
382 if (chargingProfile.chargingProfileId === cp.chargingProfileId
383 || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) {
384 this.getConnector(connectorId).chargingProfiles[index] = cp;
389 !cpReplaced && this.getConnector(connectorId).chargingProfiles?.push(cp);
392 public resetTransactionOnConnector(connectorId: number): void {
393 this.getConnector(connectorId).authorized = false;
394 this.getConnector(connectorId).transactionStarted = false;
395 delete this.getConnector(connectorId).authorizeIdTag;
396 delete this.getConnector(connectorId).transactionId;
397 delete this.getConnector(connectorId).transactionIdTag;
398 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;
399 delete this.getConnector(connectorId).transactionBeginMeterValue;
400 this.stopMeterValues(connectorId);
403 public addToMessageQueue(message: string): void {
405 // Handle dups in message queue
406 for (const bufferedMessage of this.messageQueue) {
407 // Message already in the queue
408 if (message === bufferedMessage) {
415 this.messageQueue.push(message);
419 private flushMessageQueue() {
420 if (!Utils.isEmptyArray(this.messageQueue)) {
421 this.messageQueue.forEach((message, index) => {
422 this.messageQueue.splice(index, 1);
423 this.wsConnection.send(message);
428 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
429 // In case of multiple instances: add instance index to charging station id
430 let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
431 instanceIndex = instanceIndex > 0 ? instanceIndex : '';
432 const idSuffix = stationTemplate.nameSuffix ?? '';
433 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix;
436 private buildStationInfo(): ChargingStationInfo {
437 let stationTemplateFromFile: ChargingStationTemplate;
439 // Load template file
440 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
441 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
442 fs.closeSync(fileDescriptor);
444 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
446 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
447 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
448 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
449 const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length);
450 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
451 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
452 : stationTemplateFromFile.power[powerArrayRandomIndex];
454 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
455 stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
456 ? stationTemplateFromFile.power * 1000
457 : stationTemplateFromFile.power;
459 delete stationInfo.power;
460 delete stationInfo.powerUnit;
461 stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile);
462 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
466 private getOCPPVersion(): OCPPVersion {
467 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
470 private handleUnsupportedVersion(version: OCPPVersion) {
471 const errMsg = `${this.logPrefix()} Unsupported protocol version
'${version}' configured
in template file ${this.stationTemplateFile}
`;
472 logger.error(errMsg);
473 throw new Error(errMsg);
476 private initialize(): void {
477 this.stationInfo = this.buildStationInfo();
478 this.bootNotificationRequest = {
479 chargePointModel: this.stationInfo.chargePointModel,
480 chargePointVendor: this.stationInfo.chargePointVendor,
481 ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix },
482 ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
484 this.configuration = this.getTemplateChargingStationConfiguration();
485 this.supervisionUrl = this.getSupervisionURL();
486 this.wsConnectionUrl = this.supervisionUrl + '/' + this.stationInfo.chargingStationId;
487 // Build connectors if needed
488 const maxConnectors = this.getMaxNumberOfConnectors();
489 if (maxConnectors <= 0) {
490 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with ${maxConnectors} connectors
`);
492 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
493 if (templateMaxConnectors <= 0) {
494 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector configuration
`);
496 if (!this.stationInfo.Connectors[0]) {
497 logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile}
with no connector Id
0 configuration
`);
500 if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) {
501 logger.warn(`${this.logPrefix()}
Number of connectors exceeds the
number of connector configurations
in template ${this.stationTemplateFile}
, forcing random connector configurations affectation
`);
502 this.stationInfo.randomConnectors = true;
504 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
505 // FIXME: Handle shrinking the number of connectors
506 if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) {
507 this.connectorsConfigurationHash = connectorsConfigHash;
508 // Add connector Id 0
509 let lastConnector = '0';
510 for (lastConnector in this.stationInfo.Connectors) {
511 if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) {
512 this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]);
513 this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE;
514 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
515 this.connectors[lastConnector].chargingProfiles = [];
519 // Generate all connectors
520 if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
521 for (let index = 1; index <= maxConnectors; index++) {
522 const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
523 this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]);
524 this.connectors[index].availability = AvailabilityType.OPERATIVE;
525 if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) {
526 this.connectors[index].chargingProfiles = [];
531 // Avoid duplication of connectors related information
532 delete this.stationInfo.Connectors;
533 // Initialize transaction attributes on connectors
534 for (const connector in this.connectors) {
535 if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
536 this.initTransactionAttributesOnConnector(Utils.convertToInt(connector));
539 switch (this.getOCPPVersion()) {
540 case OCPPVersion.VERSION_16:
541 this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this);
542 this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this));
545 this.handleUnsupportedVersion(this.getOCPPVersion());
549 this.initOCPPParameters();
550 this.stationInfo.powerDivider = this.getPowerDivider();
551 if (this.getEnableStatistics()) {
552 this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId);
553 this.performanceObserver = new PerformanceObserver((list) => {
554 const entry = list.getEntries()[0];
555 this.performanceStatistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
556 this.performanceObserver.disconnect();
561 private initOCPPParameters(): void {
562 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
563 this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core}
,${SupportedFeatureProfiles.Local_Auth_List_Management}
,${SupportedFeatureProfiles.Smart_Charging}
`);
565 this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true);
566 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
567 this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
569 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
570 const connectorPhaseRotation = [];
571 for (const connector in this.connectors) {
573 if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) {
574 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
575 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) {
576 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
578 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) {
579 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.NotApplicable}
`);
580 } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) {
581 connectorPhaseRotation.push(`${connector}
.${ConnectorPhaseRotation.RST}
`);
584 this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString());
586 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
587 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
589 if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled)
590 && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) {
591 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
593 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
594 this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString());
598 private async onOpen(): Promise<void> {
599 logger.info(`${this.logPrefix()} Is connected to server through ${this.wsConnectionUrl}
`);
600 if (!this.isRegistered()) {
601 // Send BootNotification
602 let registrationRetryCount = 0;
604 this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel,
605 this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion);
606 if (!this.isRegistered()) {
607 registrationRetryCount++;
608 await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL);
610 } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1));
612 if (this.isRegistered()) {
613 await this.startMessageSequence();
614 this.hasStopped && (this.hasStopped = false);
615 if (this.hasSocketRestarted && this.isWebSocketOpen()) {
616 this.flushMessageQueue();
619 logger.error(`${this.logPrefix()} Registration failure
: max retries
reached (${this.getRegistrationMaxRetries()}
) or retry
disabled (${this.getRegistrationMaxRetries()}
)`);
621 this.autoReconnectRetryCount = 0;
622 this.hasSocketRestarted = false;
625 private async onClose(closeEvent: any): Promise<void> {
626 switch (closeEvent) {
627 case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close
628 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
629 logger.info(`${this.logPrefix()} Socket normally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
630 this.autoReconnectRetryCount = 0;
632 default: // Abnormal close
633 logger.error(`${this.logPrefix()} Socket abnormally closed
with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`);
634 await this.reconnect(closeEvent);
639 private async onMessage(messageEvent: MessageEvent): Promise<void> {
640 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}];
641 let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void;
642 let rejectCallback: (error: OCPPError) => void;
643 let requestPayload: Record<string, unknown>;
647 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest;
648 // Check the Type of message
649 switch (messageType) {
651 case MessageType.CALL_MESSAGE:
652 if (this.getEnableStatistics()) {
653 this.performanceStatistics.addMessage(commandName, messageType);
656 await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload);
659 case MessageType.CALL_RESULT_MESSAGE:
661 if (Utils.isIterable(this.requests[messageId])) {
662 [responseCallback, , requestPayload] = this.requests[messageId];
664 throw new Error(`Response request
for message id ${messageId}
is not iterable
`);
666 if (!responseCallback) {
668 throw new Error(`Response request
for unknown message id ${messageId}
`);
670 delete this.requests[messageId];
671 responseCallback(commandName, requestPayload);
674 case MessageType.CALL_ERROR_MESSAGE:
675 if (!this.requests[messageId]) {
677 throw new Error(`Error request
for unknown message id ${messageId}
`);
679 if (Utils.isIterable(this.requests[messageId])) {
680 [, rejectCallback] = this.requests[messageId];
682 throw new Error(`Error request
for message id ${messageId}
is not iterable
`);
684 delete this.requests[messageId];
685 rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails));
689 errMsg = `${this.logPrefix()} Wrong message
type ${messageType}
`;
690 logger.error(errMsg);
691 throw new Error(errMsg);
695 logger.error('%s Incoming message %j processing error %j on request content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]);
697 messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
701 private onPing(): void {
702 logger.debug(this.logPrefix() + ' Has received a WS ping (rfc6455) from the server');
705 private onPong(): void {
706 logger.debug(this.logPrefix() + ' Has received a WS pong (rfc6455) from the server');
709 private async onError(errorEvent: any): Promise<void> {
710 logger.error(this.logPrefix() + ' Socket error: %j', errorEvent);
711 // switch (errorEvent.code) {
712 // case 'ECONNREFUSED':
713 // await this._reconnect(errorEvent);
718 private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
719 return this.stationInfo.Configuration ? this.stationInfo.Configuration : {} as ChargingStationConfiguration;
722 private getAuthorizationFile(): string | undefined {
723 return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile));
726 private getAuthorizedTags(): string[] {
727 let authorizedTags: string[] = [];
728 const authorizationFile = this.getAuthorizationFile();
729 if (authorizationFile) {
731 // Load authorization file
732 const fileDescriptor = fs.openSync(authorizationFile, 'r');
733 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
734 fs.closeSync(fileDescriptor);
736 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
739 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile);
741 return authorizedTags;
744 private getUseConnectorId0(): boolean | undefined {
745 return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true;
748 private getNumberOfRunningTransactions(): number {
750 for (const connector in this.connectors) {
751 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
759 private getConnectionTimeout(): number | undefined {
760 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
761 return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT;
763 return Constants.DEFAULT_CONNECTION_TIMEOUT;
766 // -1 for unlimited, 0 for disabling
767 private getAutoReconnectMaxRetries(): number | undefined {
768 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
769 return this.stationInfo.autoReconnectMaxRetries;
771 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
772 return Configuration.getAutoReconnectMaxRetries();
778 private getRegistrationMaxRetries(): number | undefined {
779 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
780 return this.stationInfo.registrationMaxRetries;
785 private getPowerDivider(): number {
786 let powerDivider = this.getNumberOfConnectors();
787 if (this.stationInfo.powerSharedByConnectors) {
788 powerDivider = this.getNumberOfRunningTransactions();
793 private getTemplateMaxNumberOfConnectors(): number {
794 return Object.keys(this.stationInfo.Connectors).length;
797 private getMaxNumberOfConnectors(): number {
798 let maxConnectors = 0;
799 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
800 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
801 // Distribute evenly the number of connectors
802 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
803 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
804 maxConnectors = this.stationInfo.numberOfConnectors as number;
806 maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors();
808 return maxConnectors;
811 private getNumberOfConnectors(): number {
812 return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length;
815 private async startMessageSequence(): Promise<void> {
816 // Start WebSocket ping
817 this.startWebSocketPing();
819 this.startHeartbeat();
820 // Initialize connectors status
821 for (const connector in this.connectors) {
822 if (Utils.convertToInt(connector) === 0) {
824 } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) {
825 // Send status in template at startup
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))?.bootStatus) {
829 // Send status in template after reset
830 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
831 this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus;
832 } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) {
833 // Send previous status at template reload
834 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
836 // Send default status
837 await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
838 this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE;
842 this.startAutomaticTransactionGenerator();
843 if (this.getEnableStatistics()) {
844 this.performanceStatistics.start();
848 private startAutomaticTransactionGenerator() {
849 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
850 if (!this.automaticTransactionGeneration) {
851 this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
853 if (this.automaticTransactionGeneration.timeToStop) {
854 // The ATG might sleep
855 void this.automaticTransactionGeneration.start();
860 private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
861 // Stop WebSocket ping
862 this.stopWebSocketPing();
864 this.stopHeartbeat();
866 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
867 this.automaticTransactionGeneration &&
868 !this.automaticTransactionGeneration.timeToStop) {
869 await this.automaticTransactionGeneration.stop(reason);
871 for (const connector in this.connectors) {
872 if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
873 const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId;
874 await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId),
875 this.getTransactionIdTag(transactionId), reason);
881 private startWebSocketPing(): void {
882 const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval)
883 ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value)
885 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
886 this.webSocketPingSetInterval = setInterval(() => {
887 if (this.isWebSocketOpen()) {
888 this.wsConnection.ping((): void => { });
890 }, webSocketPingInterval * 1000);
891 logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
892 } else if (this.webSocketPingSetInterval) {
893 logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
895 logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}
, not starting the WebSocket ping
`);
899 private stopWebSocketPing(): void {
900 if (this.webSocketPingSetInterval) {
901 clearInterval(this.webSocketPingSetInterval);
905 private getSupervisionURL(): string {
906 const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs());
908 if (!Utils.isEmptyArray(supervisionUrls)) {
909 if (Configuration.getDistributeStationsToTenantsEqually()) {
910 indexUrl = this.index % supervisionUrls.length;
913 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
915 return supervisionUrls[indexUrl];
917 return supervisionUrls as string;
920 private getHeartbeatInterval(): number | undefined {
921 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
922 if (HeartbeatInterval) {
923 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
925 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
926 if (HeartBeatInterval) {
927 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
931 private stopHeartbeat(): void {
932 if (this.heartbeatSetInterval) {
933 clearInterval(this.heartbeatSetInterval);
937 private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void {
938 options ?? {} as WebSocket.ClientOptions;
939 options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
940 if (this.isWebSocketOpen() && forceCloseOpened) {
941 this.wsConnection.close();
944 switch (this.getOCPPVersion()) {
945 case OCPPVersion.VERSION_16:
946 protocol = 'ocpp' + OCPPVersion.VERSION_16;
949 this.handleUnsupportedVersion(this.getOCPPVersion());
952 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
953 logger.info(this.logPrefix() + ' Will communicate through URL ' + this.supervisionUrl);
956 private stopMeterValues(connectorId: number) {
957 if (this.getConnector(connectorId)?.transactionSetInterval) {
958 clearInterval(this.getConnector(connectorId).transactionSetInterval);
962 private startAuthorizationFileMonitoring(): void {
963 const authorizationFile = this.getAuthorizationFile();
964 if (authorizationFile) {
966 fs.watch(authorizationFile).on('change', () => {
968 logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload');
969 // Initialize authorizedTags
970 this.authorizedTags = this.getAuthorizedTags();
972 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
976 FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error);
979 logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes');
983 private startStationTemplateFileMonitoring(): void {
985 // eslint-disable-next-line @typescript-eslint/no-misused-promises
986 fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => {
988 logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload');
992 if (!this.stationInfo.AutomaticTransactionGenerator.enable &&
993 this.automaticTransactionGeneration) {
994 await this.automaticTransactionGeneration.stop();
997 this.startAutomaticTransactionGenerator();
998 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1000 logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error);
1004 FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
1008 private getReconnectExponentialDelay(): boolean | undefined {
1009 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false;
1012 private async reconnect(error: any): Promise<void> {
1014 this.stopHeartbeat();
1015 // Stop the ATG if needed
1016 if (this.stationInfo.AutomaticTransactionGenerator.enable &&
1017 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1018 this.automaticTransactionGeneration &&
1019 !this.automaticTransactionGeneration.timeToStop) {
1020 await this.automaticTransactionGeneration.stop();
1022 if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
1023 this.autoReconnectRetryCount++;
1024 const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
1025 logger.error(`${this.logPrefix()} Socket
: connection retry
in ${Utils.roundTo(reconnectDelay, 2)}ms
, timeout ${reconnectDelay - 100}ms
`);
1026 await Utils.sleep(reconnectDelay);
1027 logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString());
1028 this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
1029 this.hasSocketRestarted = true;
1030 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1031 logger.error(`${this.logPrefix()} Socket reconnect failure
: max retries
reached (${this.autoReconnectRetryCount}
) or retry
disabled (${this.getAutoReconnectMaxRetries()}
)`);
1035 private initTransactionAttributesOnConnector(connectorId: number): void {
1036 this.getConnector(connectorId).authorized = false;
1037 this.getConnector(connectorId).transactionStarted = false;
1038 this.getConnector(connectorId).energyActiveImportRegisterValue = 0;
1039 this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0;