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