2b0b071137ceccbb5825001e1118d6f72b2aa75f
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils';
4 import {
5 AvailabilityType,
6 BootNotificationRequest,
7 CachedRequest,
8 HeartbeatRequest,
9 IncomingRequest,
10 IncomingRequestCommand,
11 MeterValuesRequest,
12 RequestCommand,
13 StatusNotificationRequest,
14 } from '../types/ocpp/Requests';
15 import {
16 BootNotificationResponse,
17 ErrorResponse,
18 HeartbeatResponse,
19 MeterValuesResponse,
20 RegistrationStatus,
21 Response,
22 StatusNotificationResponse,
23 } from '../types/ocpp/Responses';
24 import { ChargingProfile, ChargingRateUnitType } from '../types/ocpp/ChargingProfile';
25 import ChargingStationConfiguration, { Section } from '../types/ChargingStationConfiguration';
26 import ChargingStationTemplate, {
27 CurrentType,
28 PowerUnits,
29 Voltage,
30 WsOptions,
31 } from '../types/ChargingStationTemplate';
32 import {
33 ConnectorPhaseRotation,
34 StandardParametersKey,
35 SupportedFeatureProfiles,
36 VendorDefaultParametersKey,
37 } from '../types/ocpp/Configuration';
38 import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
39 import {
40 StopTransactionReason,
41 StopTransactionRequest,
42 StopTransactionResponse,
43 } from '../types/ocpp/Transaction';
44 import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
45 import WebSocket, { Data, OPEN, RawData } from 'ws';
46
47 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
48 import BaseError from '../exception/BaseError';
49 import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
50 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
51 import { ChargingStationConfigurationUtils } from './ChargingStationConfigurationUtils';
52 import ChargingStationInfo from '../types/ChargingStationInfo';
53 import ChargingStationOcppConfiguration from '../types/ChargingStationOcppConfiguration';
54 import { ChargingStationUtils } from './ChargingStationUtils';
55 import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
56 import Configuration from '../utils/Configuration';
57 import { ConnectorStatus } from '../types/ConnectorStatus';
58 import Constants from '../utils/Constants';
59 import { ErrorType } from '../types/ocpp/ErrorType';
60 import { FileType } from '../types/FileType';
61 import FileUtils from '../utils/FileUtils';
62 import { JsonType } from '../types/JsonType';
63 import { MessageType } from '../types/ocpp/MessageType';
64 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
65 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
66 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
67 import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
68 import OCPPError from '../exception/OCPPError';
69 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
70 import OCPPRequestService from './ocpp/OCPPRequestService';
71 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
72 import PerformanceStatistics from '../performance/PerformanceStatistics';
73 import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
74 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
75 import { URL } from 'url';
76 import Utils from '../utils/Utils';
77 import crypto from 'crypto';
78 import fs from 'fs';
79 import logger from '../utils/Logger';
80 import { parentPort } from 'worker_threads';
81 import path from 'path';
82
83 export default class ChargingStation {
84 public hashId!: string;
85 public readonly templateFile: string;
86 public authorizedTags: string[];
87 public stationInfo!: ChargingStationInfo;
88 public readonly connectors: Map<number, ConnectorStatus>;
89 public ocppConfiguration!: ChargingStationOcppConfiguration;
90 public wsConnection!: WebSocket;
91 public readonly requests: Map<string, CachedRequest>;
92 public performanceStatistics!: PerformanceStatistics;
93 public heartbeatSetInterval!: NodeJS.Timeout;
94 public ocppRequestService!: OCPPRequestService;
95 public bootNotificationResponse!: BootNotificationResponse | null;
96 private readonly index: number;
97 private configurationFile!: string;
98 private bootNotificationRequest!: BootNotificationRequest;
99 private connectorsConfigurationHash!: string;
100 private ocppIncomingRequestService!: OCPPIncomingRequestService;
101 private readonly messageBuffer: Set<string>;
102 private wsConfiguredConnectionUrl!: URL;
103 private wsConnectionRestarted: boolean;
104 private stopped: boolean;
105 private autoReconnectRetryCount: number;
106 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
107 private webSocketPingSetInterval!: NodeJS.Timeout;
108
109 constructor(index: number, templateFile: string) {
110 this.index = index;
111 this.templateFile = templateFile;
112 this.stopped = false;
113 this.wsConnectionRestarted = false;
114 this.autoReconnectRetryCount = 0;
115 this.connectors = new Map<number, ConnectorStatus>();
116 this.requests = new Map<string, CachedRequest>();
117 this.messageBuffer = new Set<string>();
118 this.initialize();
119 this.authorizedTags = this.getAuthorizedTags();
120 }
121
122 private get wsConnectionUrl(): URL {
123 return this.getSupervisionUrlOcppConfiguration()
124 ? new URL(
125 ChargingStationConfigurationUtils.getConfigurationKey(
126 this,
127 this.getSupervisionUrlOcppKey()
128 ).value +
129 '/' +
130 this.stationInfo.chargingStationId
131 )
132 : this.wsConfiguredConnectionUrl;
133 }
134
135 public logPrefix(): string {
136 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
137 }
138
139 public getBootNotificationRequest(): BootNotificationRequest {
140 return this.bootNotificationRequest;
141 }
142
143 public getRandomIdTag(): string {
144 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
145 return this.authorizedTags[index];
146 }
147
148 public hasAuthorizedTags(): boolean {
149 return !Utils.isEmptyArray(this.authorizedTags);
150 }
151
152 public getEnableStatistics(): boolean | undefined {
153 return !Utils.isUndefined(this.stationInfo.enableStatistics)
154 ? this.stationInfo.enableStatistics
155 : true;
156 }
157
158 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
159 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
160 }
161
162 public getNumberOfPhases(): number | undefined {
163 switch (this.getCurrentOutType()) {
164 case CurrentType.AC:
165 return !Utils.isUndefined(this.stationInfo.numberOfPhases)
166 ? this.stationInfo.numberOfPhases
167 : 3;
168 case CurrentType.DC:
169 return 0;
170 }
171 }
172
173 public isWebSocketConnectionOpened(): boolean {
174 return this?.wsConnection?.readyState === OPEN;
175 }
176
177 public getRegistrationStatus(): RegistrationStatus {
178 return this?.bootNotificationResponse?.status;
179 }
180
181 public isInUnknownState(): boolean {
182 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
183 }
184
185 public isInPendingState(): boolean {
186 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
187 }
188
189 public isInAcceptedState(): boolean {
190 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
191 }
192
193 public isInRejectedState(): boolean {
194 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
195 }
196
197 public isRegistered(): boolean {
198 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
199 }
200
201 public isChargingStationAvailable(): boolean {
202 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
203 }
204
205 public isConnectorAvailable(id: number): boolean {
206 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
207 }
208
209 public getNumberOfConnectors(): number {
210 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
211 }
212
213 public getConnectorStatus(id: number): ConnectorStatus {
214 return this.connectors.get(id);
215 }
216
217 public getCurrentOutType(): CurrentType | undefined {
218 return this.stationInfo.currentOutType ?? CurrentType.AC;
219 }
220
221 public getOcppStrictCompliance(): boolean {
222 return this.stationInfo.ocppStrictCompliance ?? false;
223 }
224
225 public getVoltageOut(): number | undefined {
226 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
227 this.templateFile
228 }, cannot define default voltage out`;
229 let defaultVoltageOut: number;
230 switch (this.getCurrentOutType()) {
231 case CurrentType.AC:
232 defaultVoltageOut = Voltage.VOLTAGE_230;
233 break;
234 case CurrentType.DC:
235 defaultVoltageOut = Voltage.VOLTAGE_400;
236 break;
237 default:
238 logger.error(errMsg);
239 throw new Error(errMsg);
240 }
241 return !Utils.isUndefined(this.stationInfo.voltageOut)
242 ? this.stationInfo.voltageOut
243 : defaultVoltageOut;
244 }
245
246 public getConnectorMaximumAvailablePower(connectorId: number): number {
247 let connectorAmperageLimitationPowerLimit: number;
248 if (
249 !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
250 this.getAmperageLimitation() < this.stationInfo.maximumAmperage
251 ) {
252 connectorAmperageLimitationPowerLimit =
253 (this.getCurrentOutType() === CurrentType.AC
254 ? ACElectricUtils.powerTotal(
255 this.getNumberOfPhases(),
256 this.getVoltageOut(),
257 this.getAmperageLimitation() * this.getNumberOfConnectors()
258 )
259 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) /
260 this.stationInfo.powerDivider;
261 }
262 const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider;
263 const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId);
264 return Math.min(
265 isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
266 isNaN(connectorAmperageLimitationPowerLimit)
267 ? Infinity
268 : connectorAmperageLimitationPowerLimit,
269 isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit
270 );
271 }
272
273 public getTransactionIdTag(transactionId: number): string | undefined {
274 for (const connectorId of this.connectors.keys()) {
275 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
276 return this.getConnectorStatus(connectorId).transactionIdTag;
277 }
278 }
279 }
280
281 public getOutOfOrderEndMeterValues(): boolean {
282 return this.stationInfo.outOfOrderEndMeterValues ?? false;
283 }
284
285 public getBeginEndMeterValues(): boolean {
286 return this.stationInfo.beginEndMeterValues ?? false;
287 }
288
289 public getMeteringPerTransaction(): boolean {
290 return this.stationInfo.meteringPerTransaction ?? true;
291 }
292
293 public getTransactionDataMeterValues(): boolean {
294 return this.stationInfo.transactionDataMeterValues ?? false;
295 }
296
297 public getMainVoltageMeterValues(): boolean {
298 return this.stationInfo.mainVoltageMeterValues ?? true;
299 }
300
301 public getPhaseLineToLineVoltageMeterValues(): boolean {
302 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
303 }
304
305 public getCustomValueLimitationMeterValues(): boolean {
306 return this.stationInfo.customValueLimitationMeterValues ?? true;
307 }
308
309 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
310 for (const connectorId of this.connectors.keys()) {
311 if (
312 connectorId > 0 &&
313 this.getConnectorStatus(connectorId)?.transactionId === transactionId
314 ) {
315 return connectorId;
316 }
317 }
318 }
319
320 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
321 const transactionConnectorStatus = this.getConnectorStatus(
322 this.getConnectorIdByTransactionId(transactionId)
323 );
324 if (this.getMeteringPerTransaction()) {
325 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
326 }
327 return transactionConnectorStatus?.energyActiveImportRegisterValue;
328 }
329
330 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
331 const connectorStatus = this.getConnectorStatus(connectorId);
332 if (this.getMeteringPerTransaction()) {
333 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
334 }
335 return connectorStatus?.energyActiveImportRegisterValue;
336 }
337
338 public getAuthorizeRemoteTxRequests(): boolean {
339 const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey(
340 this,
341 StandardParametersKey.AuthorizeRemoteTxRequests
342 );
343 return authorizeRemoteTxRequests
344 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
345 : false;
346 }
347
348 public getLocalAuthListEnabled(): boolean {
349 const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey(
350 this,
351 StandardParametersKey.LocalAuthListEnabled
352 );
353 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
354 }
355
356 public getSampledValueTemplate(
357 connectorId: number,
358 measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
359 phase?: MeterValuePhase
360 ): SampledValueTemplate | undefined {
361 const onPhaseStr = phase ? `on phase ${phase} ` : '';
362 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
363 logger.warn(
364 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
365 );
366 return;
367 }
368 if (
369 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
370 !ChargingStationConfigurationUtils.getConfigurationKey(
371 this,
372 StandardParametersKey.MeterValuesSampledData
373 )?.value.includes(measurand)
374 ) {
375 logger.debug(
376 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
377 StandardParametersKey.MeterValuesSampledData
378 }' OCPP parameter`
379 );
380 return;
381 }
382 const sampledValueTemplates: SampledValueTemplate[] =
383 this.getConnectorStatus(connectorId).MeterValues;
384 for (
385 let index = 0;
386 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
387 index++
388 ) {
389 if (
390 !Constants.SUPPORTED_MEASURANDS.includes(
391 sampledValueTemplates[index]?.measurand ??
392 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
393 )
394 ) {
395 logger.warn(
396 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
397 );
398 } else if (
399 phase &&
400 sampledValueTemplates[index]?.phase === phase &&
401 sampledValueTemplates[index]?.measurand === measurand &&
402 ChargingStationConfigurationUtils.getConfigurationKey(
403 this,
404 StandardParametersKey.MeterValuesSampledData
405 )?.value.includes(measurand)
406 ) {
407 return sampledValueTemplates[index];
408 } else if (
409 !phase &&
410 !sampledValueTemplates[index].phase &&
411 sampledValueTemplates[index]?.measurand === measurand &&
412 ChargingStationConfigurationUtils.getConfigurationKey(
413 this,
414 StandardParametersKey.MeterValuesSampledData
415 )?.value.includes(measurand)
416 ) {
417 return sampledValueTemplates[index];
418 } else if (
419 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
420 (!sampledValueTemplates[index].measurand ||
421 sampledValueTemplates[index].measurand === measurand)
422 ) {
423 return sampledValueTemplates[index];
424 }
425 }
426 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
427 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
428 logger.error(errorMsg);
429 throw new Error(errorMsg);
430 }
431 logger.debug(
432 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
433 );
434 }
435
436 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
437 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
438 }
439
440 public startHeartbeat(): void {
441 if (
442 this.getHeartbeatInterval() &&
443 this.getHeartbeatInterval() > 0 &&
444 !this.heartbeatSetInterval
445 ) {
446 // eslint-disable-next-line @typescript-eslint/no-misused-promises
447 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
448 await this.ocppRequestService.requestHandler<HeartbeatRequest, HeartbeatResponse>(
449 this,
450 RequestCommand.HEARTBEAT
451 );
452 }, this.getHeartbeatInterval());
453 logger.info(
454 this.logPrefix() +
455 ' Heartbeat started every ' +
456 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
457 );
458 } else if (this.heartbeatSetInterval) {
459 logger.info(
460 this.logPrefix() +
461 ' Heartbeat already started every ' +
462 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
463 );
464 } else {
465 logger.error(
466 `${this.logPrefix()} Heartbeat interval set to ${
467 this.getHeartbeatInterval()
468 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
469 : this.getHeartbeatInterval()
470 }, not starting the heartbeat`
471 );
472 }
473 }
474
475 public restartHeartbeat(): void {
476 // Stop heartbeat
477 this.stopHeartbeat();
478 // Start heartbeat
479 this.startHeartbeat();
480 }
481
482 public restartWebSocketPing(): void {
483 // Stop WebSocket ping
484 this.stopWebSocketPing();
485 // Start WebSocket ping
486 this.startWebSocketPing();
487 }
488
489 public startMeterValues(connectorId: number, interval: number): void {
490 if (connectorId === 0) {
491 logger.error(
492 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
493 );
494 return;
495 }
496 if (!this.getConnectorStatus(connectorId)) {
497 logger.error(
498 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
499 );
500 return;
501 }
502 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
503 logger.error(
504 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
505 );
506 return;
507 } else if (
508 this.getConnectorStatus(connectorId)?.transactionStarted &&
509 !this.getConnectorStatus(connectorId)?.transactionId
510 ) {
511 logger.error(
512 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
513 );
514 return;
515 }
516 if (interval > 0) {
517 // eslint-disable-next-line @typescript-eslint/no-misused-promises
518 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
519 // eslint-disable-next-line @typescript-eslint/no-misused-promises
520 async (): Promise<void> => {
521 // FIXME: Implement OCPP version agnostic helpers
522 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
523 this,
524 connectorId,
525 this.getConnectorStatus(connectorId).transactionId,
526 interval
527 );
528 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
529 this,
530 RequestCommand.METER_VALUES,
531 {
532 connectorId,
533 transactionId: this.getConnectorStatus(connectorId).transactionId,
534 meterValue: [meterValue],
535 }
536 );
537 },
538 interval
539 );
540 } else {
541 logger.error(
542 `${this.logPrefix()} Charging station ${
543 StandardParametersKey.MeterValueSampleInterval
544 } configuration set to ${
545 interval ? Utils.formatDurationMilliSeconds(interval) : interval
546 }, not sending MeterValues`
547 );
548 }
549 }
550
551 public start(): void {
552 if (this.getEnableStatistics()) {
553 this.performanceStatistics.start();
554 }
555 this.openWSConnection();
556 // Handle WebSocket message
557 this.wsConnection.on(
558 'message',
559 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
560 );
561 // Handle WebSocket error
562 this.wsConnection.on(
563 'error',
564 this.onError.bind(this) as (this: WebSocket, error: Error) => void
565 );
566 // Handle WebSocket close
567 this.wsConnection.on(
568 'close',
569 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
570 );
571 // Handle WebSocket open
572 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
573 // Handle WebSocket ping
574 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
575 // Handle WebSocket pong
576 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
577 // Monitor authorization file
578 FileUtils.watchJsonFile<string[]>(
579 this.logPrefix(),
580 FileType.Authorization,
581 this.getAuthorizationFile(),
582 this.authorizedTags
583 );
584 // Monitor charging station template file
585 FileUtils.watchJsonFile(
586 this.logPrefix(),
587 FileType.ChargingStationTemplate,
588 this.templateFile,
589 null,
590 (event, filename): void => {
591 if (filename && event === 'change') {
592 try {
593 logger.debug(
594 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
595 this.templateFile
596 } file have changed, reload`
597 );
598 // Initialize
599 this.initialize();
600 // Restart the ATG
601 if (
602 !this.stationInfo.AutomaticTransactionGenerator.enable &&
603 this.automaticTransactionGenerator
604 ) {
605 this.automaticTransactionGenerator.stop();
606 }
607 this.startAutomaticTransactionGenerator();
608 if (this.getEnableStatistics()) {
609 this.performanceStatistics.restart();
610 } else {
611 this.performanceStatistics.stop();
612 }
613 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
614 } catch (error) {
615 logger.error(
616 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
617 error
618 );
619 }
620 }
621 }
622 );
623 parentPort.postMessage({
624 id: ChargingStationWorkerMessageEvents.STARTED,
625 data: { id: this.stationInfo.chargingStationId },
626 });
627 }
628
629 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
630 // Stop message sequence
631 await this.stopMessageSequence(reason);
632 for (const connectorId of this.connectors.keys()) {
633 if (connectorId > 0) {
634 await this.ocppRequestService.requestHandler<
635 StatusNotificationRequest,
636 StatusNotificationResponse
637 >(this, RequestCommand.STATUS_NOTIFICATION, {
638 connectorId,
639 status: ChargePointStatus.UNAVAILABLE,
640 errorCode: ChargePointErrorCode.NO_ERROR,
641 });
642 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
643 }
644 }
645 if (this.isWebSocketConnectionOpened()) {
646 this.wsConnection.close();
647 }
648 if (this.getEnableStatistics()) {
649 this.performanceStatistics.stop();
650 }
651 this.bootNotificationResponse = null;
652 parentPort.postMessage({
653 id: ChargingStationWorkerMessageEvents.STOPPED,
654 data: { id: this.stationInfo.chargingStationId },
655 });
656 this.stopped = true;
657 }
658
659 public async reset(reason?: StopTransactionReason): Promise<void> {
660 await this.stop(reason);
661 await Utils.sleep(this.stationInfo.resetTime);
662 this.stationInfo = this.getStationInfo();
663 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
664 this.start();
665 }
666
667 public saveOcppConfiguration(): void {
668 if (this.getOcppPersistentConfiguration()) {
669 this.saveConfiguration(Section.ocppConfiguration);
670 }
671 }
672
673 public getChargingProfilePowerLimit(connectorId: number): number | undefined {
674 let limit: number, matchingChargingProfile: ChargingProfile;
675 let chargingProfiles: ChargingProfile[] = [];
676 // Get charging profiles for connector and sort by stack level
677 chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort(
678 (a, b) => b.stackLevel - a.stackLevel
679 );
680 // Get profiles on connector 0
681 if (this.getConnectorStatus(0).chargingProfiles) {
682 chargingProfiles.push(
683 ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel)
684 );
685 }
686 if (!Utils.isEmptyArray(chargingProfiles)) {
687 const result = ChargingStationUtils.getLimitFromChargingProfiles(
688 chargingProfiles,
689 Utils.logPrefix()
690 );
691 if (!Utils.isNullOrUndefined(result)) {
692 limit = result.limit;
693 matchingChargingProfile = result.matchingChargingProfile;
694 switch (this.getCurrentOutType()) {
695 case CurrentType.AC:
696 limit =
697 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
698 ChargingRateUnitType.WATT
699 ? limit
700 : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit);
701 break;
702 case CurrentType.DC:
703 limit =
704 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
705 ChargingRateUnitType.WATT
706 ? limit
707 : DCElectricUtils.power(this.getVoltageOut(), limit);
708 }
709
710 const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider;
711 if (limit > connectorMaximumPower) {
712 logger.error(
713 `${this.logPrefix()} Charging profile id ${
714 matchingChargingProfile.chargingProfileId
715 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
716 this.getConnectorStatus(connectorId).chargingProfiles
717 );
718 limit = connectorMaximumPower;
719 }
720 }
721 }
722 return limit;
723 }
724
725 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
726 if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) {
727 logger.error(
728 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
729 );
730 this.getConnectorStatus(connectorId).chargingProfiles = [];
731 }
732 if (!Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
733 logger.error(
734 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
735 );
736 this.getConnectorStatus(connectorId).chargingProfiles = [];
737 }
738 let cpReplaced = false;
739 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
740 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
741 (chargingProfile: ChargingProfile, index: number) => {
742 if (
743 chargingProfile.chargingProfileId === cp.chargingProfileId ||
744 (chargingProfile.stackLevel === cp.stackLevel &&
745 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
746 ) {
747 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
748 cpReplaced = true;
749 }
750 }
751 );
752 }
753 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
754 }
755
756 public resetConnectorStatus(connectorId: number): void {
757 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
758 this.getConnectorStatus(connectorId).idTagAuthorized = false;
759 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
760 this.getConnectorStatus(connectorId).transactionStarted = false;
761 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
762 delete this.getConnectorStatus(connectorId).authorizeIdTag;
763 delete this.getConnectorStatus(connectorId).transactionId;
764 delete this.getConnectorStatus(connectorId).transactionIdTag;
765 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
766 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
767 this.stopMeterValues(connectorId);
768 }
769
770 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) {
771 return ChargingStationConfigurationUtils.getConfigurationKey(
772 this,
773 StandardParametersKey.SupportedFeatureProfiles
774 )?.value.includes(featureProfile);
775 }
776
777 public bufferMessage(message: string): void {
778 this.messageBuffer.add(message);
779 }
780
781 private flushMessageBuffer() {
782 if (this.messageBuffer.size > 0) {
783 this.messageBuffer.forEach((message) => {
784 // TODO: evaluate the need to track performance
785 this.wsConnection.send(message);
786 this.messageBuffer.delete(message);
787 });
788 }
789 }
790
791 private getSupervisionUrlOcppConfiguration(): boolean {
792 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
793 }
794
795 private getSupervisionUrlOcppKey(): string {
796 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
797 }
798
799 private getTemplateFromFile(): ChargingStationTemplate | null {
800 let template: ChargingStationTemplate = null;
801 try {
802 const measureId = `${FileType.ChargingStationTemplate} read`;
803 const beginId = PerformanceStatistics.beginMeasure(measureId);
804 template =
805 (JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate) ??
806 ({} as ChargingStationTemplate);
807 PerformanceStatistics.endMeasure(measureId, beginId);
808 template.templateHash = crypto
809 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
810 .update(JSON.stringify(template))
811 .digest('hex');
812 } catch (error) {
813 FileUtils.handleFileException(
814 this.logPrefix(),
815 FileType.ChargingStationTemplate,
816 this.templateFile,
817 error as NodeJS.ErrnoException
818 );
819 }
820 return template;
821 }
822
823 private getStationInfoFromTemplate(): ChargingStationInfo {
824 const stationInfo: ChargingStationInfo = this.getTemplateFromFile();
825 if (Utils.isNullOrUndefined(stationInfo)) {
826 const logMsg = 'Failed to read charging station template file';
827 logger.error(`${this.logPrefix()} ${logMsg}`);
828 throw new BaseError(logMsg);
829 }
830 if (Utils.isEmptyObject(stationInfo)) {
831 logger.warn(
832 `${this.logPrefix()} Empty charging station information from template file ${
833 this.templateFile
834 }`
835 );
836 }
837 const chargingStationId = ChargingStationUtils.getChargingStationId(this.index, stationInfo);
838 // Deprecation template keys section
839 ChargingStationUtils.warnDeprecatedTemplateKey(
840 stationInfo,
841 'supervisionUrl',
842 this.templateFile,
843 this.logPrefix(),
844 "Use 'supervisionUrls' instead"
845 );
846 ChargingStationUtils.convertDeprecatedTemplateKey(
847 stationInfo,
848 'supervisionUrl',
849 'supervisionUrls'
850 );
851 stationInfo.wsOptions = stationInfo?.wsOptions ?? {};
852 if (!Utils.isEmptyArray(stationInfo.power)) {
853 stationInfo.power = stationInfo.power as number[];
854 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length);
855 stationInfo.maximumPower =
856 stationInfo.powerUnit === PowerUnits.KILO_WATT
857 ? stationInfo.power[powerArrayRandomIndex] * 1000
858 : stationInfo.power[powerArrayRandomIndex];
859 } else {
860 stationInfo.power = stationInfo.power as number;
861 stationInfo.maximumPower =
862 stationInfo.powerUnit === PowerUnits.KILO_WATT
863 ? stationInfo.power * 1000
864 : stationInfo.power;
865 }
866 delete stationInfo.power;
867 delete stationInfo.powerUnit;
868 stationInfo.chargingStationId = chargingStationId;
869 stationInfo.resetTime = stationInfo.resetTime
870 ? stationInfo.resetTime * 1000
871 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
872 return stationInfo;
873 }
874
875 private getStationInfoFromFile(): ChargingStationInfo {
876 let stationInfo = this.getConfigurationFromFile()?.stationInfo ?? ({} as ChargingStationInfo);
877 stationInfo = ChargingStationUtils.createStationInfoHash(stationInfo);
878 return stationInfo;
879 }
880
881 private getStationInfo(): ChargingStationInfo {
882 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
883 this.hashId = ChargingStationUtils.getHashId(stationInfoFromTemplate);
884 this.configurationFile = path.join(
885 path.resolve(__dirname, '../'),
886 'assets',
887 'configurations',
888 this.hashId + '.json'
889 );
890 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
891 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
892 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
893 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
894 return this.stationInfo;
895 }
896 return stationInfoFromFile;
897 }
898 ChargingStationUtils.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile);
899 return stationInfoFromTemplate;
900 }
901
902 private saveStationInfo(): void {
903 this.saveConfiguration(Section.stationInfo);
904 }
905
906 private getOcppVersion(): OCPPVersion {
907 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
908 }
909
910 private getOcppPersistentConfiguration(): boolean {
911 return this.stationInfo.ocppPersistentConfiguration ?? true;
912 }
913
914 private handleUnsupportedVersion(version: OCPPVersion) {
915 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
916 this.templateFile
917 }`;
918 logger.error(errMsg);
919 throw new Error(errMsg);
920 }
921
922 private initialize(): void {
923 this.stationInfo = this.getStationInfo();
924 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
925 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
926 this.stationInfo
927 );
928 this.ocppConfiguration = this.getOcppConfiguration();
929 this.stationInfo?.Configuration && delete this.stationInfo.Configuration;
930 this.wsConfiguredConnectionUrl = new URL(
931 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
932 );
933 // Build connectors if needed
934 const maxConnectors = this.getMaxNumberOfConnectors();
935 this.checkMaxConnectors(maxConnectors);
936 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
937 this.checkTemplateMaxConnectors(templateMaxConnectors);
938 if (
939 maxConnectors >
940 (this.stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
941 !this.stationInfo.randomConnectors
942 ) {
943 logger.warn(
944 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
945 this.templateFile
946 }, forcing random connector configurations affectation`
947 );
948 this.stationInfo.randomConnectors = true;
949 }
950 this.initializeConnectors(this.stationInfo, maxConnectors, templateMaxConnectors);
951 this.stationInfo.maximumAmperage = this.getMaximumAmperage();
952 this.stationInfo = ChargingStationUtils.createStationInfoHash(this.stationInfo);
953 this.saveStationInfo();
954 // Avoid duplication of connectors related information in RAM
955 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
956 // OCPP configuration
957 this.initializeOcppConfiguration();
958 if (this.getEnableStatistics()) {
959 this.performanceStatistics = PerformanceStatistics.getInstance(
960 this.hashId,
961 this.stationInfo.chargingStationId,
962 this.wsConnectionUrl
963 );
964 }
965 switch (this.getOcppVersion()) {
966 case OCPPVersion.VERSION_16:
967 this.ocppIncomingRequestService =
968 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
969 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
970 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
971 );
972 break;
973 default:
974 this.handleUnsupportedVersion(this.getOcppVersion());
975 break;
976 }
977 if (this.stationInfo.autoRegister) {
978 this.bootNotificationResponse = {
979 currentTime: new Date().toISOString(),
980 interval: this.getHeartbeatInterval() / 1000,
981 status: RegistrationStatus.ACCEPTED,
982 };
983 }
984 this.stationInfo.powerDivider = this.getPowerDivider();
985 }
986
987 private initializeOcppConfiguration(): void {
988 if (
989 !ChargingStationConfigurationUtils.getConfigurationKey(
990 this,
991 StandardParametersKey.HeartbeatInterval
992 )
993 ) {
994 ChargingStationConfigurationUtils.addConfigurationKey(
995 this,
996 StandardParametersKey.HeartbeatInterval,
997 '0'
998 );
999 }
1000 if (
1001 !ChargingStationConfigurationUtils.getConfigurationKey(
1002 this,
1003 StandardParametersKey.HeartBeatInterval
1004 )
1005 ) {
1006 ChargingStationConfigurationUtils.addConfigurationKey(
1007 this,
1008 StandardParametersKey.HeartBeatInterval,
1009 '0',
1010 { visible: false }
1011 );
1012 }
1013 if (
1014 this.getSupervisionUrlOcppConfiguration() &&
1015 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1016 ) {
1017 ChargingStationConfigurationUtils.addConfigurationKey(
1018 this,
1019 this.getSupervisionUrlOcppKey(),
1020 this.getConfiguredSupervisionUrl().href,
1021 { reboot: true }
1022 );
1023 } else if (
1024 !this.getSupervisionUrlOcppConfiguration() &&
1025 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1026 ) {
1027 ChargingStationConfigurationUtils.deleteConfigurationKey(
1028 this,
1029 this.getSupervisionUrlOcppKey(),
1030 { save: false }
1031 );
1032 }
1033 if (
1034 this.stationInfo.amperageLimitationOcppKey &&
1035 !ChargingStationConfigurationUtils.getConfigurationKey(
1036 this,
1037 this.stationInfo.amperageLimitationOcppKey
1038 )
1039 ) {
1040 ChargingStationConfigurationUtils.addConfigurationKey(
1041 this,
1042 this.stationInfo.amperageLimitationOcppKey,
1043 (
1044 this.stationInfo.maximumAmperage *
1045 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1046 ).toString()
1047 );
1048 }
1049 if (
1050 !ChargingStationConfigurationUtils.getConfigurationKey(
1051 this,
1052 StandardParametersKey.SupportedFeatureProfiles
1053 )
1054 ) {
1055 ChargingStationConfigurationUtils.addConfigurationKey(
1056 this,
1057 StandardParametersKey.SupportedFeatureProfiles,
1058 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1059 );
1060 }
1061 ChargingStationConfigurationUtils.addConfigurationKey(
1062 this,
1063 StandardParametersKey.NumberOfConnectors,
1064 this.getNumberOfConnectors().toString(),
1065 { readonly: true },
1066 { overwrite: true }
1067 );
1068 if (
1069 !ChargingStationConfigurationUtils.getConfigurationKey(
1070 this,
1071 StandardParametersKey.MeterValuesSampledData
1072 )
1073 ) {
1074 ChargingStationConfigurationUtils.addConfigurationKey(
1075 this,
1076 StandardParametersKey.MeterValuesSampledData,
1077 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1078 );
1079 }
1080 if (
1081 !ChargingStationConfigurationUtils.getConfigurationKey(
1082 this,
1083 StandardParametersKey.ConnectorPhaseRotation
1084 )
1085 ) {
1086 const connectorPhaseRotation = [];
1087 for (const connectorId of this.connectors.keys()) {
1088 // AC/DC
1089 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1090 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1091 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1092 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1093 // AC
1094 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1095 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1096 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1097 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1098 }
1099 }
1100 ChargingStationConfigurationUtils.addConfigurationKey(
1101 this,
1102 StandardParametersKey.ConnectorPhaseRotation,
1103 connectorPhaseRotation.toString()
1104 );
1105 }
1106 if (
1107 !ChargingStationConfigurationUtils.getConfigurationKey(
1108 this,
1109 StandardParametersKey.AuthorizeRemoteTxRequests
1110 )
1111 ) {
1112 ChargingStationConfigurationUtils.addConfigurationKey(
1113 this,
1114 StandardParametersKey.AuthorizeRemoteTxRequests,
1115 'true'
1116 );
1117 }
1118 if (
1119 !ChargingStationConfigurationUtils.getConfigurationKey(
1120 this,
1121 StandardParametersKey.LocalAuthListEnabled
1122 ) &&
1123 ChargingStationConfigurationUtils.getConfigurationKey(
1124 this,
1125 StandardParametersKey.SupportedFeatureProfiles
1126 )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
1127 ) {
1128 ChargingStationConfigurationUtils.addConfigurationKey(
1129 this,
1130 StandardParametersKey.LocalAuthListEnabled,
1131 'false'
1132 );
1133 }
1134 if (
1135 !ChargingStationConfigurationUtils.getConfigurationKey(
1136 this,
1137 StandardParametersKey.ConnectionTimeOut
1138 )
1139 ) {
1140 ChargingStationConfigurationUtils.addConfigurationKey(
1141 this,
1142 StandardParametersKey.ConnectionTimeOut,
1143 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1144 );
1145 }
1146 this.saveOcppConfiguration();
1147 }
1148
1149 private initializeConnectors(
1150 stationInfo: ChargingStationInfo,
1151 maxConnectors: number,
1152 templateMaxConnectors: number
1153 ): void {
1154 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1155 const logMsg = `${this.logPrefix()} No already defined connectors and charging station information from template ${
1156 this.templateFile
1157 } with no connectors configuration defined`;
1158 logger.error(logMsg);
1159 throw new BaseError(logMsg);
1160 }
1161 if (!stationInfo?.Connectors[0]) {
1162 logger.warn(
1163 `${this.logPrefix()} Charging station information from template ${
1164 this.templateFile
1165 } with no connector Id 0 configuration`
1166 );
1167 }
1168 if (stationInfo?.Connectors) {
1169 const connectorsConfigHash = crypto
1170 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1171 .update(JSON.stringify(stationInfo?.Connectors) + maxConnectors.toString())
1172 .digest('hex');
1173 const connectorsConfigChanged =
1174 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1175 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1176 connectorsConfigChanged && this.connectors.clear();
1177 this.connectorsConfigurationHash = connectorsConfigHash;
1178 // Add connector Id 0
1179 let lastConnector = '0';
1180 for (lastConnector in stationInfo?.Connectors) {
1181 const lastConnectorId = Utils.convertToInt(lastConnector);
1182 if (
1183 lastConnectorId === 0 &&
1184 this.getUseConnectorId0() &&
1185 stationInfo?.Connectors[lastConnector]
1186 ) {
1187 this.connectors.set(
1188 lastConnectorId,
1189 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector])
1190 );
1191 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1192 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1193 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1194 }
1195 }
1196 }
1197 // Generate all connectors
1198 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
1199 for (let index = 1; index <= maxConnectors; index++) {
1200 const randConnectorId = stationInfo.randomConnectors
1201 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1202 : index;
1203 this.connectors.set(
1204 index,
1205 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId])
1206 );
1207 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1208 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1209 this.getConnectorStatus(index).chargingProfiles = [];
1210 }
1211 }
1212 }
1213 }
1214 } else {
1215 logger.warn(
1216 `${this.logPrefix()} Charging station information from template ${
1217 this.templateFile
1218 } with no connectors configuration defined, using already defined connectors`
1219 );
1220 }
1221 // Initialize transaction attributes on connectors
1222 for (const connectorId of this.connectors.keys()) {
1223 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1224 this.initializeConnectorStatus(connectorId);
1225 }
1226 }
1227 }
1228
1229 private checkMaxConnectors(maxConnectors: number): void {
1230 if (maxConnectors <= 0) {
1231 logger.warn(
1232 `${this.logPrefix()} Charging station information from template ${
1233 this.templateFile
1234 } with ${maxConnectors} connectors`
1235 );
1236 }
1237 }
1238
1239 private checkTemplateMaxConnectors(templateMaxConnectors: number): void {
1240 if (templateMaxConnectors === 0) {
1241 logger.warn(
1242 `${this.logPrefix()} Charging station information from template ${
1243 this.templateFile
1244 } with empty connectors configuration`
1245 );
1246 } else if (templateMaxConnectors < 0) {
1247 logger.error(
1248 `${this.logPrefix()} Charging station information from template ${
1249 this.templateFile
1250 } with no connectors configuration defined`
1251 );
1252 }
1253 }
1254
1255 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1256 let configuration: ChargingStationConfiguration = null;
1257 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1258 try {
1259 const measureId = `${FileType.ChargingStationConfiguration} read`;
1260 const beginId = PerformanceStatistics.beginMeasure(measureId);
1261 configuration = JSON.parse(
1262 fs.readFileSync(this.configurationFile, 'utf8')
1263 ) as ChargingStationConfiguration;
1264 PerformanceStatistics.endMeasure(measureId, beginId);
1265 } catch (error) {
1266 FileUtils.handleFileException(
1267 this.logPrefix(),
1268 FileType.ChargingStationConfiguration,
1269 this.configurationFile,
1270 error as NodeJS.ErrnoException
1271 );
1272 }
1273 }
1274 return configuration;
1275 }
1276
1277 private saveConfiguration(section?: Section): void {
1278 if (this.configurationFile) {
1279 try {
1280 const configurationData: ChargingStationConfiguration =
1281 this.getConfigurationFromFile() ?? {};
1282 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1283 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1284 }
1285 switch (section) {
1286 case Section.ocppConfiguration:
1287 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1288 break;
1289 case Section.stationInfo:
1290 if (configurationData?.stationInfo?.infoHash === this.stationInfo?.infoHash) {
1291 logger.debug(
1292 `${this.logPrefix()} Not saving unchanged charging station information to configuration file ${
1293 this.configurationFile
1294 }`
1295 );
1296 return;
1297 }
1298 configurationData.stationInfo = this.stationInfo;
1299 break;
1300 default:
1301 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1302 if (configurationData?.stationInfo?.infoHash !== this.stationInfo?.infoHash) {
1303 configurationData.stationInfo = this.stationInfo;
1304 }
1305 break;
1306 }
1307 const measureId = `${FileType.ChargingStationConfiguration} write`;
1308 const beginId = PerformanceStatistics.beginMeasure(measureId);
1309 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1310 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1311 fs.closeSync(fileDescriptor);
1312 PerformanceStatistics.endMeasure(measureId, beginId);
1313 } catch (error) {
1314 FileUtils.handleFileException(
1315 this.logPrefix(),
1316 FileType.ChargingStationConfiguration,
1317 this.configurationFile,
1318 error as NodeJS.ErrnoException
1319 );
1320 }
1321 } else {
1322 logger.error(
1323 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1324 );
1325 }
1326 }
1327
1328 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration {
1329 return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration);
1330 }
1331
1332 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1333 let configuration: ChargingStationConfiguration = null;
1334 if (this.getOcppPersistentConfiguration()) {
1335 const configurationFromFile = this.getConfigurationFromFile();
1336 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1337 }
1338 configuration && delete configuration.stationInfo;
1339 return configuration;
1340 }
1341
1342 private getOcppConfiguration(): ChargingStationOcppConfiguration {
1343 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1344 if (!ocppConfiguration) {
1345 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1346 }
1347 return ocppConfiguration;
1348 }
1349
1350 private async onOpen(): Promise<void> {
1351 if (this.isWebSocketConnectionOpened()) {
1352 logger.info(
1353 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1354 );
1355 if (!this.isRegistered()) {
1356 // Send BootNotification
1357 let registrationRetryCount = 0;
1358 do {
1359 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
1360 BootNotificationRequest,
1361 BootNotificationResponse
1362 >(
1363 this,
1364 RequestCommand.BOOT_NOTIFICATION,
1365 {
1366 chargePointModel: this.bootNotificationRequest.chargePointModel,
1367 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1368 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1369 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1370 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1371 iccid: this.bootNotificationRequest.iccid,
1372 imsi: this.bootNotificationRequest.imsi,
1373 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1374 meterType: this.bootNotificationRequest.meterType,
1375 },
1376 { skipBufferingOnError: true }
1377 );
1378 if (!this.isRegistered()) {
1379 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1380 await Utils.sleep(
1381 this.bootNotificationResponse?.interval
1382 ? this.bootNotificationResponse.interval * 1000
1383 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1384 );
1385 }
1386 } while (
1387 !this.isRegistered() &&
1388 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1389 this.getRegistrationMaxRetries() === -1)
1390 );
1391 }
1392 if (this.isRegistered()) {
1393 if (this.isInAcceptedState()) {
1394 await this.startMessageSequence();
1395 this.wsConnectionRestarted && this.flushMessageBuffer();
1396 }
1397 } else {
1398 logger.error(
1399 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1400 );
1401 }
1402 this.stopped && (this.stopped = false);
1403 this.autoReconnectRetryCount = 0;
1404 this.wsConnectionRestarted = false;
1405 } else {
1406 logger.warn(
1407 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1408 );
1409 }
1410 }
1411
1412 private async onClose(code: number, reason: string): Promise<void> {
1413 switch (code) {
1414 // Normal close
1415 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1416 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1417 logger.info(
1418 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1419 code
1420 )}' and reason '${reason}'`
1421 );
1422 this.autoReconnectRetryCount = 0;
1423 break;
1424 // Abnormal close
1425 default:
1426 logger.error(
1427 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1428 code
1429 )}' and reason '${reason}'`
1430 );
1431 await this.reconnect(code);
1432 break;
1433 }
1434 }
1435
1436 private async onMessage(data: Data): Promise<void> {
1437 let messageType: number;
1438 let messageId: string;
1439 let commandName: IncomingRequestCommand;
1440 let commandPayload: JsonType;
1441 let errorType: ErrorType;
1442 let errorMessage: string;
1443 let errorDetails: JsonType;
1444 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
1445 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1446 let requestCommandName: RequestCommand | IncomingRequestCommand;
1447 let requestPayload: JsonType;
1448 let cachedRequest: CachedRequest;
1449 let errMsg: string;
1450 try {
1451 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
1452 if (Utils.isIterable(request)) {
1453 [messageType, messageId] = request;
1454 // Check the type of message
1455 switch (messageType) {
1456 // Incoming Message
1457 case MessageType.CALL_MESSAGE:
1458 [, , commandName, commandPayload] = request as IncomingRequest;
1459 if (this.getEnableStatistics()) {
1460 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1461 }
1462 logger.debug(
1463 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1464 request
1465 )}`
1466 );
1467 // Process the message
1468 await this.ocppIncomingRequestService.incomingRequestHandler(
1469 this,
1470 messageId,
1471 commandName,
1472 commandPayload
1473 );
1474 break;
1475 // Outcome Message
1476 case MessageType.CALL_RESULT_MESSAGE:
1477 [, , commandPayload] = request as Response;
1478 if (!this.requests.has(messageId)) {
1479 // Error
1480 throw new OCPPError(
1481 ErrorType.INTERNAL_ERROR,
1482 `Response for unknown message id ${messageId}`,
1483 null,
1484 commandPayload
1485 );
1486 }
1487 // Respond
1488 cachedRequest = this.requests.get(messageId);
1489 if (Utils.isIterable(cachedRequest)) {
1490 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1491 } else {
1492 throw new OCPPError(
1493 ErrorType.PROTOCOL_ERROR,
1494 `Cached request for message id ${messageId} response is not iterable`,
1495 null,
1496 cachedRequest as unknown as JsonType
1497 );
1498 }
1499 logger.debug(
1500 `${this.logPrefix()} << Command '${
1501 requestCommandName ?? ''
1502 }' received response payload: ${JSON.stringify(request)}`
1503 );
1504 responseCallback(commandPayload, requestPayload);
1505 break;
1506 // Error Message
1507 case MessageType.CALL_ERROR_MESSAGE:
1508 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1509 if (!this.requests.has(messageId)) {
1510 // Error
1511 throw new OCPPError(
1512 ErrorType.INTERNAL_ERROR,
1513 `Error response for unknown message id ${messageId}`,
1514 null,
1515 { errorType, errorMessage, errorDetails }
1516 );
1517 }
1518 cachedRequest = this.requests.get(messageId);
1519 if (Utils.isIterable(cachedRequest)) {
1520 [, errorCallback, requestCommandName] = cachedRequest;
1521 } else {
1522 throw new OCPPError(
1523 ErrorType.PROTOCOL_ERROR,
1524 `Cached request for message id ${messageId} error response is not iterable`,
1525 null,
1526 cachedRequest as unknown as JsonType
1527 );
1528 }
1529 logger.debug(
1530 `${this.logPrefix()} << Command '${
1531 requestCommandName ?? ''
1532 }' received error payload: ${JSON.stringify(request)}`
1533 );
1534 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1535 break;
1536 // Error
1537 default:
1538 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1539 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1540 logger.error(errMsg);
1541 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1542 }
1543 } else {
1544 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, {
1545 payload: request,
1546 });
1547 }
1548 } catch (error) {
1549 // Log
1550 logger.error(
1551 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1552 this.logPrefix(),
1553 data.toString(),
1554 this.requests.get(messageId),
1555 error
1556 );
1557 // Send error
1558 messageType === MessageType.CALL_MESSAGE &&
1559 (await this.ocppRequestService.sendError(
1560 this,
1561 messageId,
1562 error as OCPPError,
1563 commandName ?? requestCommandName ?? null
1564 ));
1565 }
1566 }
1567
1568 private onPing(): void {
1569 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1570 }
1571
1572 private onPong(): void {
1573 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1574 }
1575
1576 private onError(error: WSError): void {
1577 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
1578 }
1579
1580 private getAuthorizationFile(): string | undefined {
1581 return (
1582 this.stationInfo.authorizationFile &&
1583 path.join(
1584 path.resolve(__dirname, '../'),
1585 'assets',
1586 path.basename(this.stationInfo.authorizationFile)
1587 )
1588 );
1589 }
1590
1591 private getAuthorizedTags(): string[] {
1592 let authorizedTags: string[] = [];
1593 const authorizationFile = this.getAuthorizationFile();
1594 if (authorizationFile) {
1595 try {
1596 // Load authorization file
1597 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
1598 } catch (error) {
1599 FileUtils.handleFileException(
1600 this.logPrefix(),
1601 FileType.Authorization,
1602 authorizationFile,
1603 error as NodeJS.ErrnoException
1604 );
1605 }
1606 } else {
1607 logger.info(
1608 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1609 );
1610 }
1611 return authorizedTags;
1612 }
1613
1614 private getUseConnectorId0(): boolean | undefined {
1615 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1616 ? this.stationInfo.useConnectorId0
1617 : true;
1618 }
1619
1620 private getNumberOfRunningTransactions(): number {
1621 let trxCount = 0;
1622 for (const connectorId of this.connectors.keys()) {
1623 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1624 trxCount++;
1625 }
1626 }
1627 return trxCount;
1628 }
1629
1630 // 0 for disabling
1631 private getConnectionTimeout(): number | undefined {
1632 if (
1633 ChargingStationConfigurationUtils.getConfigurationKey(
1634 this,
1635 StandardParametersKey.ConnectionTimeOut
1636 )
1637 ) {
1638 return (
1639 parseInt(
1640 ChargingStationConfigurationUtils.getConfigurationKey(
1641 this,
1642 StandardParametersKey.ConnectionTimeOut
1643 ).value
1644 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
1645 );
1646 }
1647 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1648 }
1649
1650 // -1 for unlimited, 0 for disabling
1651 private getAutoReconnectMaxRetries(): number | undefined {
1652 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1653 return this.stationInfo.autoReconnectMaxRetries;
1654 }
1655 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1656 return Configuration.getAutoReconnectMaxRetries();
1657 }
1658 return -1;
1659 }
1660
1661 // 0 for disabling
1662 private getRegistrationMaxRetries(): number | undefined {
1663 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1664 return this.stationInfo.registrationMaxRetries;
1665 }
1666 return -1;
1667 }
1668
1669 private getPowerDivider(): number {
1670 let powerDivider = this.getNumberOfConnectors();
1671 if (this.stationInfo.powerSharedByConnectors) {
1672 powerDivider = this.getNumberOfRunningTransactions();
1673 }
1674 return powerDivider;
1675 }
1676
1677 private getTemplateMaxNumberOfConnectors(): number {
1678 if (!this.stationInfo?.Connectors) {
1679 return -1;
1680 }
1681 return Object.keys(this.stationInfo?.Connectors).length;
1682 }
1683
1684 private getMaxNumberOfConnectors(): number {
1685 let maxConnectors: number;
1686 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1687 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
1688 // Distribute evenly the number of connectors
1689 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1690 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1691 maxConnectors = this.stationInfo.numberOfConnectors as number;
1692 } else {
1693 maxConnectors = this.stationInfo?.Connectors[0]
1694 ? this.getTemplateMaxNumberOfConnectors() - 1
1695 : this.getTemplateMaxNumberOfConnectors();
1696 }
1697 return maxConnectors;
1698 }
1699
1700 private getMaximumPower(): number {
1701 return (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower;
1702 }
1703
1704 private getMaximumAmperage(): number | undefined {
1705 const maximumPower = this.getMaximumPower();
1706 switch (this.getCurrentOutType()) {
1707 case CurrentType.AC:
1708 return ACElectricUtils.amperagePerPhaseFromPower(
1709 this.getNumberOfPhases(),
1710 maximumPower / this.getNumberOfConnectors(),
1711 this.getVoltageOut()
1712 );
1713 case CurrentType.DC:
1714 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut());
1715 }
1716 }
1717
1718 private getAmperageLimitation(): number | undefined {
1719 if (
1720 this.stationInfo.amperageLimitationOcppKey &&
1721 ChargingStationConfigurationUtils.getConfigurationKey(
1722 this,
1723 this.stationInfo.amperageLimitationOcppKey
1724 )
1725 ) {
1726 return (
1727 Utils.convertToInt(
1728 ChargingStationConfigurationUtils.getConfigurationKey(
1729 this,
1730 this.stationInfo.amperageLimitationOcppKey
1731 ).value
1732 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1733 );
1734 }
1735 }
1736
1737 private async startMessageSequence(): Promise<void> {
1738 if (this.stationInfo.autoRegister) {
1739 await this.ocppRequestService.requestHandler<
1740 BootNotificationRequest,
1741 BootNotificationResponse
1742 >(
1743 this,
1744 RequestCommand.BOOT_NOTIFICATION,
1745 {
1746 chargePointModel: this.bootNotificationRequest.chargePointModel,
1747 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1748 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1749 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1750 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1751 iccid: this.bootNotificationRequest.iccid,
1752 imsi: this.bootNotificationRequest.imsi,
1753 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1754 meterType: this.bootNotificationRequest.meterType,
1755 },
1756 { skipBufferingOnError: true }
1757 );
1758 }
1759 // Start WebSocket ping
1760 this.startWebSocketPing();
1761 // Start heartbeat
1762 this.startHeartbeat();
1763 // Initialize connectors status
1764 for (const connectorId of this.connectors.keys()) {
1765 if (connectorId === 0) {
1766 continue;
1767 } else if (
1768 !this.stopped &&
1769 !this.getConnectorStatus(connectorId)?.status &&
1770 this.getConnectorStatus(connectorId)?.bootStatus
1771 ) {
1772 // Send status in template at startup
1773 await this.ocppRequestService.requestHandler<
1774 StatusNotificationRequest,
1775 StatusNotificationResponse
1776 >(this, RequestCommand.STATUS_NOTIFICATION, {
1777 connectorId,
1778 status: this.getConnectorStatus(connectorId).bootStatus,
1779 errorCode: ChargePointErrorCode.NO_ERROR,
1780 });
1781 this.getConnectorStatus(connectorId).status =
1782 this.getConnectorStatus(connectorId).bootStatus;
1783 } else if (
1784 this.stopped &&
1785 this.getConnectorStatus(connectorId)?.status &&
1786 this.getConnectorStatus(connectorId)?.bootStatus
1787 ) {
1788 // Send status in template after reset
1789 await this.ocppRequestService.requestHandler<
1790 StatusNotificationRequest,
1791 StatusNotificationResponse
1792 >(this, RequestCommand.STATUS_NOTIFICATION, {
1793 connectorId,
1794 status: this.getConnectorStatus(connectorId).bootStatus,
1795 errorCode: ChargePointErrorCode.NO_ERROR,
1796 });
1797 this.getConnectorStatus(connectorId).status =
1798 this.getConnectorStatus(connectorId).bootStatus;
1799 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1800 // Send previous status at template reload
1801 await this.ocppRequestService.requestHandler<
1802 StatusNotificationRequest,
1803 StatusNotificationResponse
1804 >(this, RequestCommand.STATUS_NOTIFICATION, {
1805 connectorId,
1806 status: this.getConnectorStatus(connectorId).status,
1807 errorCode: ChargePointErrorCode.NO_ERROR,
1808 });
1809 } else {
1810 // Send default status
1811 await this.ocppRequestService.requestHandler<
1812 StatusNotificationRequest,
1813 StatusNotificationResponse
1814 >(this, RequestCommand.STATUS_NOTIFICATION, {
1815 connectorId,
1816 status: ChargePointStatus.AVAILABLE,
1817 errorCode: ChargePointErrorCode.NO_ERROR,
1818 });
1819 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1820 }
1821 }
1822 // Start the ATG
1823 this.startAutomaticTransactionGenerator();
1824 }
1825
1826 private startAutomaticTransactionGenerator() {
1827 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
1828 if (!this.automaticTransactionGenerator) {
1829 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
1830 }
1831 if (!this.automaticTransactionGenerator.started) {
1832 this.automaticTransactionGenerator.start();
1833 }
1834 }
1835 }
1836
1837 private async stopMessageSequence(
1838 reason: StopTransactionReason = StopTransactionReason.NONE
1839 ): Promise<void> {
1840 // Stop WebSocket ping
1841 this.stopWebSocketPing();
1842 // Stop heartbeat
1843 this.stopHeartbeat();
1844 // Stop the ATG
1845 if (
1846 this.stationInfo.AutomaticTransactionGenerator.enable &&
1847 this.automaticTransactionGenerator?.started
1848 ) {
1849 this.automaticTransactionGenerator.stop();
1850 } else {
1851 for (const connectorId of this.connectors.keys()) {
1852 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1853 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1854 if (
1855 this.getBeginEndMeterValues() &&
1856 this.getOcppStrictCompliance() &&
1857 !this.getOutOfOrderEndMeterValues()
1858 ) {
1859 // FIXME: Implement OCPP version agnostic helpers
1860 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1861 this,
1862 connectorId,
1863 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1864 );
1865 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
1866 this,
1867 RequestCommand.METER_VALUES,
1868 {
1869 connectorId,
1870 transactionId,
1871 meterValue: transactionEndMeterValue,
1872 }
1873 );
1874 }
1875 await this.ocppRequestService.requestHandler<
1876 StopTransactionRequest,
1877 StopTransactionResponse
1878 >(this, RequestCommand.STOP_TRANSACTION, {
1879 transactionId,
1880 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1881 idTag: this.getTransactionIdTag(transactionId),
1882 reason,
1883 });
1884 }
1885 }
1886 }
1887 }
1888
1889 private startWebSocketPing(): void {
1890 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
1891 this,
1892 StandardParametersKey.WebSocketPingInterval
1893 )
1894 ? Utils.convertToInt(
1895 ChargingStationConfigurationUtils.getConfigurationKey(
1896 this,
1897 StandardParametersKey.WebSocketPingInterval
1898 ).value
1899 )
1900 : 0;
1901 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1902 this.webSocketPingSetInterval = setInterval(() => {
1903 if (this.isWebSocketConnectionOpened()) {
1904 this.wsConnection.ping((): void => {
1905 /* This is intentional */
1906 });
1907 }
1908 }, webSocketPingInterval * 1000);
1909 logger.info(
1910 this.logPrefix() +
1911 ' WebSocket ping started every ' +
1912 Utils.formatDurationSeconds(webSocketPingInterval)
1913 );
1914 } else if (this.webSocketPingSetInterval) {
1915 logger.info(
1916 this.logPrefix() +
1917 ' WebSocket ping every ' +
1918 Utils.formatDurationSeconds(webSocketPingInterval) +
1919 ' already started'
1920 );
1921 } else {
1922 logger.error(
1923 `${this.logPrefix()} WebSocket ping interval set to ${
1924 webSocketPingInterval
1925 ? Utils.formatDurationSeconds(webSocketPingInterval)
1926 : webSocketPingInterval
1927 }, not starting the WebSocket ping`
1928 );
1929 }
1930 }
1931
1932 private stopWebSocketPing(): void {
1933 if (this.webSocketPingSetInterval) {
1934 clearInterval(this.webSocketPingSetInterval);
1935 }
1936 }
1937
1938 private getConfiguredSupervisionUrl(): URL {
1939 const supervisionUrls = Utils.cloneObject<string | string[]>(
1940 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1941 );
1942 if (!Utils.isEmptyArray(supervisionUrls)) {
1943 let urlIndex = 0;
1944 switch (Configuration.getSupervisionUrlDistribution()) {
1945 case SupervisionUrlDistribution.ROUND_ROBIN:
1946 urlIndex = (this.index - 1) % supervisionUrls.length;
1947 break;
1948 case SupervisionUrlDistribution.RANDOM:
1949 // Get a random url
1950 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1951 break;
1952 case SupervisionUrlDistribution.SEQUENTIAL:
1953 if (this.index <= supervisionUrls.length) {
1954 urlIndex = this.index - 1;
1955 } else {
1956 logger.warn(
1957 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1958 );
1959 }
1960 break;
1961 default:
1962 logger.error(
1963 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1964 SupervisionUrlDistribution.ROUND_ROBIN
1965 }`
1966 );
1967 urlIndex = (this.index - 1) % supervisionUrls.length;
1968 break;
1969 }
1970 return new URL(supervisionUrls[urlIndex]);
1971 }
1972 return new URL(supervisionUrls as string);
1973 }
1974
1975 private getHeartbeatInterval(): number | undefined {
1976 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1977 this,
1978 StandardParametersKey.HeartbeatInterval
1979 );
1980 if (HeartbeatInterval) {
1981 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1982 }
1983 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1984 this,
1985 StandardParametersKey.HeartBeatInterval
1986 );
1987 if (HeartBeatInterval) {
1988 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1989 }
1990 !this.stationInfo.autoRegister &&
1991 logger.warn(
1992 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1993 Constants.DEFAULT_HEARTBEAT_INTERVAL
1994 }`
1995 );
1996 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1997 }
1998
1999 private stopHeartbeat(): void {
2000 if (this.heartbeatSetInterval) {
2001 clearInterval(this.heartbeatSetInterval);
2002 }
2003 }
2004
2005 private openWSConnection(
2006 options: WsOptions = this.stationInfo.wsOptions,
2007 forceCloseOpened = false
2008 ): void {
2009 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
2010 if (
2011 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
2012 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
2013 ) {
2014 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2015 }
2016 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
2017 this.wsConnection.close();
2018 }
2019 let protocol: string;
2020 switch (this.getOcppVersion()) {
2021 case OCPPVersion.VERSION_16:
2022 protocol = 'ocpp' + OCPPVersion.VERSION_16;
2023 break;
2024 default:
2025 this.handleUnsupportedVersion(this.getOcppVersion());
2026 break;
2027 }
2028 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
2029 logger.info(
2030 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
2031 );
2032 }
2033
2034 private stopMeterValues(connectorId: number) {
2035 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
2036 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
2037 }
2038 }
2039
2040 private getReconnectExponentialDelay(): boolean | undefined {
2041 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
2042 ? this.stationInfo.reconnectExponentialDelay
2043 : false;
2044 }
2045
2046 private async reconnect(code: number): Promise<void> {
2047 // Stop WebSocket ping
2048 this.stopWebSocketPing();
2049 // Stop heartbeat
2050 this.stopHeartbeat();
2051 // Stop the ATG if needed
2052 if (
2053 this.stationInfo.AutomaticTransactionGenerator.enable &&
2054 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
2055 this.automaticTransactionGenerator?.started
2056 ) {
2057 this.automaticTransactionGenerator.stop();
2058 }
2059 if (
2060 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
2061 this.getAutoReconnectMaxRetries() === -1
2062 ) {
2063 this.autoReconnectRetryCount++;
2064 const reconnectDelay = this.getReconnectExponentialDelay()
2065 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
2066 : this.getConnectionTimeout() * 1000;
2067 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
2068 logger.error(
2069 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2070 reconnectDelay,
2071 2
2072 )}ms, timeout ${reconnectTimeout}ms`
2073 );
2074 await Utils.sleep(reconnectDelay);
2075 logger.error(
2076 this.logPrefix() +
2077 ' WebSocket: reconnecting try #' +
2078 this.autoReconnectRetryCount.toString()
2079 );
2080 this.openWSConnection(
2081 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
2082 true
2083 );
2084 this.wsConnectionRestarted = true;
2085 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2086 logger.error(
2087 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2088 this.autoReconnectRetryCount
2089 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2090 );
2091 }
2092 }
2093
2094 private initializeConnectorStatus(connectorId: number): void {
2095 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2096 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2097 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2098 this.getConnectorStatus(connectorId).transactionStarted = false;
2099 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2100 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2101 }
2102 }