0c2123a6fb123d693fedb4ad7e7540c9f8a65ccc
[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 authorizedTagsCache: AuthorizedTagsCache;
89 public stationInfo!: ChargingStationInfo;
90 public stopped: boolean;
91 public readonly connectors: Map<number, ConnectorStatus>;
92 public ocppConfiguration!: ChargingStationOcppConfiguration;
93 public wsConnection!: WebSocket;
94 public readonly requests: Map<string, CachedRequest>;
95 public performanceStatistics!: PerformanceStatistics;
96 public heartbeatSetInterval!: NodeJS.Timeout;
97 public ocppRequestService!: OCPPRequestService;
98 public bootNotificationRequest!: BootNotificationRequest;
99 public bootNotificationResponse!: BootNotificationResponse | null;
100 public powerDivider!: number;
101 private readonly index: number;
102 private configurationFile!: string;
103 private configurationFileHash!: string;
104 private connectorsConfigurationHash!: string;
105 private ocppIncomingRequestService!: OCPPIncomingRequestService;
106 private readonly messageBuffer: Set<string>;
107 private configuredSupervisionUrl!: URL;
108 private wsConnectionRestarted: boolean;
109 private autoReconnectRetryCount: number;
110 private templateFileWatcher!: fs.FSWatcher;
111 private readonly sharedLRUCache: SharedLRUCache;
112 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
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.stopped = 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.stopped = true;
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(): void {
747 if (!this.automaticTransactionGenerator) {
748 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(
749 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
750 this
751 );
752 }
753 if (!this.automaticTransactionGenerator.started) {
754 this.automaticTransactionGenerator.start();
755 }
756 }
757
758 public stopAutomaticTransactionGenerator(): void {
759 if (this.automaticTransactionGenerator?.started) {
760 this.automaticTransactionGenerator.stop();
761 this.automaticTransactionGenerator = null;
762 }
763 }
764
765 private flushMessageBuffer(): void {
766 if (this.messageBuffer.size > 0) {
767 this.messageBuffer.forEach((message) => {
768 // TODO: evaluate the need to track performance
769 this.wsConnection.send(message);
770 this.messageBuffer.delete(message);
771 });
772 }
773 }
774
775 private getSupervisionUrlOcppConfiguration(): boolean {
776 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
777 }
778
779 private getSupervisionUrlOcppKey(): string {
780 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
781 }
782
783 private getTemplateFromFile(): ChargingStationTemplate | null {
784 let template: ChargingStationTemplate = null;
785 try {
786 if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) {
787 template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash);
788 } else {
789 const measureId = `${FileType.ChargingStationTemplate} read`;
790 const beginId = PerformanceStatistics.beginMeasure(measureId);
791 template = JSON.parse(
792 fs.readFileSync(this.templateFile, 'utf8')
793 ) as ChargingStationTemplate;
794 PerformanceStatistics.endMeasure(measureId, beginId);
795 template.templateHash = crypto
796 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
797 .update(JSON.stringify(template))
798 .digest('hex');
799 this.sharedLRUCache.setChargingStationTemplate(template);
800 }
801 } catch (error) {
802 FileUtils.handleFileException(
803 this.logPrefix(),
804 FileType.ChargingStationTemplate,
805 this.templateFile,
806 error as NodeJS.ErrnoException
807 );
808 }
809 return template;
810 }
811
812 private getStationInfoFromTemplate(): ChargingStationInfo {
813 const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile();
814 if (Utils.isNullOrUndefined(stationTemplate)) {
815 const errorMsg = 'Failed to read charging station template file';
816 logger.error(`${this.logPrefix()} ${errorMsg}`);
817 throw new BaseError(errorMsg);
818 }
819 if (Utils.isEmptyObject(stationTemplate)) {
820 const errorMsg = `Empty charging station information from template file ${this.templateFile}`;
821 logger.error(`${this.logPrefix()} ${errorMsg}`);
822 throw new BaseError(errorMsg);
823 }
824 // Deprecation template keys section
825 ChargingStationUtils.warnDeprecatedTemplateKey(
826 stationTemplate,
827 'supervisionUrl',
828 this.templateFile,
829 this.logPrefix(),
830 "Use 'supervisionUrls' instead"
831 );
832 ChargingStationUtils.convertDeprecatedTemplateKey(
833 stationTemplate,
834 'supervisionUrl',
835 'supervisionUrls'
836 );
837 const stationInfo: ChargingStationInfo =
838 ChargingStationUtils.stationTemplateToStationInfo(stationTemplate);
839 stationInfo.hashId = ChargingStationUtils.getHashId(this.index, stationTemplate);
840 stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId(
841 this.index,
842 stationTemplate
843 );
844 ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
845 if (!Utils.isEmptyArray(stationTemplate.power)) {
846 stationTemplate.power = stationTemplate.power as number[];
847 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
848 stationInfo.maximumPower =
849 stationTemplate.powerUnit === PowerUnits.KILO_WATT
850 ? stationTemplate.power[powerArrayRandomIndex] * 1000
851 : stationTemplate.power[powerArrayRandomIndex];
852 } else {
853 stationTemplate.power = stationTemplate.power as number;
854 stationInfo.maximumPower =
855 stationTemplate.powerUnit === PowerUnits.KILO_WATT
856 ? stationTemplate.power * 1000
857 : stationTemplate.power;
858 }
859 stationInfo.resetTime = stationTemplate.resetTime
860 ? stationTemplate.resetTime * 1000
861 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
862 const configuredMaxConnectors = ChargingStationUtils.getConfiguredNumberOfConnectors(
863 this.index,
864 stationTemplate
865 );
866 ChargingStationUtils.checkConfiguredMaxConnectors(
867 configuredMaxConnectors,
868 this.templateFile,
869 this.logPrefix()
870 );
871 const templateMaxConnectors =
872 ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate);
873 ChargingStationUtils.checkTemplateMaxConnectors(
874 templateMaxConnectors,
875 this.templateFile,
876 this.logPrefix()
877 );
878 if (
879 configuredMaxConnectors >
880 (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
881 !stationTemplate?.randomConnectors
882 ) {
883 logger.warn(
884 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
885 this.templateFile
886 }, forcing random connector configurations affectation`
887 );
888 stationInfo.randomConnectors = true;
889 }
890 // Build connectors if needed (FIXME: should be factored out)
891 this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors);
892 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
893 ChargingStationUtils.createStationInfoHash(stationInfo);
894 return stationInfo;
895 }
896
897 private getStationInfoFromFile(): ChargingStationInfo | null {
898 let stationInfo: ChargingStationInfo = null;
899 this.getStationInfoPersistentConfiguration() &&
900 (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
901 stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
902 return stationInfo;
903 }
904
905 private getStationInfo(): ChargingStationInfo {
906 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
907 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
908 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
909 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
910 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
911 return this.stationInfo;
912 }
913 return stationInfoFromFile;
914 }
915 stationInfoFromFile &&
916 ChargingStationUtils.propagateSerialNumber(
917 this.getTemplateFromFile(),
918 stationInfoFromFile,
919 stationInfoFromTemplate
920 );
921 return stationInfoFromTemplate;
922 }
923
924 private saveStationInfo(): void {
925 if (this.getStationInfoPersistentConfiguration()) {
926 this.saveConfiguration();
927 }
928 }
929
930 private getOcppVersion(): OCPPVersion {
931 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
932 }
933
934 private getOcppPersistentConfiguration(): boolean {
935 return this.stationInfo?.ocppPersistentConfiguration ?? true;
936 }
937
938 private getStationInfoPersistentConfiguration(): boolean {
939 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
940 }
941
942 private handleUnsupportedVersion(version: OCPPVersion) {
943 const errMsg = `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
944 logger.error(`${this.logPrefix()} ${errMsg}`);
945 throw new BaseError(errMsg);
946 }
947
948 private initialize(): void {
949 this.configurationFile = path.join(
950 path.dirname(this.templateFile.replace('station-templates', 'configurations')),
951 ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile()) + '.json'
952 );
953 this.stationInfo = this.getStationInfo();
954 this.saveStationInfo();
955 logger.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
956 // Avoid duplication of connectors related information in RAM
957 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
958 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
959 if (this.getEnableStatistics()) {
960 this.performanceStatistics = PerformanceStatistics.getInstance(
961 this.stationInfo.hashId,
962 this.stationInfo.chargingStationId,
963 this.configuredSupervisionUrl
964 );
965 }
966 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
967 this.stationInfo
968 );
969 this.powerDivider = this.getPowerDivider();
970 // OCPP configuration
971 this.ocppConfiguration = this.getOcppConfiguration();
972 this.initializeOcppConfiguration();
973 switch (this.getOcppVersion()) {
974 case OCPPVersion.VERSION_16:
975 this.ocppIncomingRequestService =
976 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
977 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
978 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
979 );
980 break;
981 default:
982 this.handleUnsupportedVersion(this.getOcppVersion());
983 break;
984 }
985 if (this.stationInfo?.autoRegister) {
986 this.bootNotificationResponse = {
987 currentTime: new Date().toISOString(),
988 interval: this.getHeartbeatInterval() / 1000,
989 status: RegistrationStatus.ACCEPTED,
990 };
991 }
992 }
993
994 private initializeOcppConfiguration(): void {
995 if (
996 !ChargingStationConfigurationUtils.getConfigurationKey(
997 this,
998 StandardParametersKey.HeartbeatInterval
999 )
1000 ) {
1001 ChargingStationConfigurationUtils.addConfigurationKey(
1002 this,
1003 StandardParametersKey.HeartbeatInterval,
1004 '0'
1005 );
1006 }
1007 if (
1008 !ChargingStationConfigurationUtils.getConfigurationKey(
1009 this,
1010 StandardParametersKey.HeartBeatInterval
1011 )
1012 ) {
1013 ChargingStationConfigurationUtils.addConfigurationKey(
1014 this,
1015 StandardParametersKey.HeartBeatInterval,
1016 '0',
1017 { visible: false }
1018 );
1019 }
1020 if (
1021 this.getSupervisionUrlOcppConfiguration() &&
1022 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1023 ) {
1024 ChargingStationConfigurationUtils.addConfigurationKey(
1025 this,
1026 this.getSupervisionUrlOcppKey(),
1027 this.configuredSupervisionUrl.href,
1028 { reboot: true }
1029 );
1030 } else if (
1031 !this.getSupervisionUrlOcppConfiguration() &&
1032 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1033 ) {
1034 ChargingStationConfigurationUtils.deleteConfigurationKey(
1035 this,
1036 this.getSupervisionUrlOcppKey(),
1037 { save: false }
1038 );
1039 }
1040 if (
1041 this.stationInfo.amperageLimitationOcppKey &&
1042 !ChargingStationConfigurationUtils.getConfigurationKey(
1043 this,
1044 this.stationInfo.amperageLimitationOcppKey
1045 )
1046 ) {
1047 ChargingStationConfigurationUtils.addConfigurationKey(
1048 this,
1049 this.stationInfo.amperageLimitationOcppKey,
1050 (
1051 this.stationInfo.maximumAmperage *
1052 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1053 ).toString()
1054 );
1055 }
1056 if (
1057 !ChargingStationConfigurationUtils.getConfigurationKey(
1058 this,
1059 StandardParametersKey.SupportedFeatureProfiles
1060 )
1061 ) {
1062 ChargingStationConfigurationUtils.addConfigurationKey(
1063 this,
1064 StandardParametersKey.SupportedFeatureProfiles,
1065 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1066 );
1067 }
1068 ChargingStationConfigurationUtils.addConfigurationKey(
1069 this,
1070 StandardParametersKey.NumberOfConnectors,
1071 this.getNumberOfConnectors().toString(),
1072 { readonly: true },
1073 { overwrite: true }
1074 );
1075 if (
1076 !ChargingStationConfigurationUtils.getConfigurationKey(
1077 this,
1078 StandardParametersKey.MeterValuesSampledData
1079 )
1080 ) {
1081 ChargingStationConfigurationUtils.addConfigurationKey(
1082 this,
1083 StandardParametersKey.MeterValuesSampledData,
1084 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1085 );
1086 }
1087 if (
1088 !ChargingStationConfigurationUtils.getConfigurationKey(
1089 this,
1090 StandardParametersKey.ConnectorPhaseRotation
1091 )
1092 ) {
1093 const connectorPhaseRotation = [];
1094 for (const connectorId of this.connectors.keys()) {
1095 // AC/DC
1096 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1097 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1098 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1099 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1100 // AC
1101 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1102 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1103 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1104 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1105 }
1106 }
1107 ChargingStationConfigurationUtils.addConfigurationKey(
1108 this,
1109 StandardParametersKey.ConnectorPhaseRotation,
1110 connectorPhaseRotation.toString()
1111 );
1112 }
1113 if (
1114 !ChargingStationConfigurationUtils.getConfigurationKey(
1115 this,
1116 StandardParametersKey.AuthorizeRemoteTxRequests
1117 )
1118 ) {
1119 ChargingStationConfigurationUtils.addConfigurationKey(
1120 this,
1121 StandardParametersKey.AuthorizeRemoteTxRequests,
1122 'true'
1123 );
1124 }
1125 if (
1126 !ChargingStationConfigurationUtils.getConfigurationKey(
1127 this,
1128 StandardParametersKey.LocalAuthListEnabled
1129 ) &&
1130 ChargingStationConfigurationUtils.getConfigurationKey(
1131 this,
1132 StandardParametersKey.SupportedFeatureProfiles
1133 )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
1134 ) {
1135 ChargingStationConfigurationUtils.addConfigurationKey(
1136 this,
1137 StandardParametersKey.LocalAuthListEnabled,
1138 'false'
1139 );
1140 }
1141 if (
1142 !ChargingStationConfigurationUtils.getConfigurationKey(
1143 this,
1144 StandardParametersKey.ConnectionTimeOut
1145 )
1146 ) {
1147 ChargingStationConfigurationUtils.addConfigurationKey(
1148 this,
1149 StandardParametersKey.ConnectionTimeOut,
1150 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1151 );
1152 }
1153 this.saveOcppConfiguration();
1154 }
1155
1156 private initializeConnectors(
1157 stationInfo: ChargingStationInfo,
1158 configuredMaxConnectors: number,
1159 templateMaxConnectors: number
1160 ): void {
1161 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1162 const logMsg = `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1163 logger.error(`${this.logPrefix()} ${logMsg}`);
1164 throw new BaseError(logMsg);
1165 }
1166 if (!stationInfo?.Connectors[0]) {
1167 logger.warn(
1168 `${this.logPrefix()} Charging station information from template ${
1169 this.templateFile
1170 } with no connector Id 0 configuration`
1171 );
1172 }
1173 if (stationInfo?.Connectors) {
1174 const connectorsConfigHash = crypto
1175 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1176 .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString())
1177 .digest('hex');
1178 const connectorsConfigChanged =
1179 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1180 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1181 connectorsConfigChanged && this.connectors.clear();
1182 this.connectorsConfigurationHash = connectorsConfigHash;
1183 // Add connector Id 0
1184 let lastConnector = '0';
1185 for (lastConnector in stationInfo?.Connectors) {
1186 const lastConnectorId = Utils.convertToInt(lastConnector);
1187 if (
1188 lastConnectorId === 0 &&
1189 this.getUseConnectorId0(stationInfo) &&
1190 stationInfo?.Connectors[lastConnector]
1191 ) {
1192 this.connectors.set(
1193 lastConnectorId,
1194 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector])
1195 );
1196 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1197 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1198 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1199 }
1200 }
1201 }
1202 // Generate all connectors
1203 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
1204 for (let index = 1; index <= configuredMaxConnectors; index++) {
1205 const randConnectorId = stationInfo?.randomConnectors
1206 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1207 : index;
1208 this.connectors.set(
1209 index,
1210 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId])
1211 );
1212 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1213 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1214 this.getConnectorStatus(index).chargingProfiles = [];
1215 }
1216 }
1217 }
1218 }
1219 } else {
1220 logger.warn(
1221 `${this.logPrefix()} Charging station information from template ${
1222 this.templateFile
1223 } with no connectors configuration defined, using already defined connectors`
1224 );
1225 }
1226 // Initialize transaction attributes on connectors
1227 for (const connectorId of this.connectors.keys()) {
1228 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1229 this.initializeConnectorStatus(connectorId);
1230 }
1231 }
1232 }
1233
1234 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1235 let configuration: ChargingStationConfiguration = null;
1236 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1237 try {
1238 if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
1239 configuration = this.sharedLRUCache.getChargingStationConfiguration(
1240 this.configurationFileHash
1241 );
1242 } else {
1243 const measureId = `${FileType.ChargingStationConfiguration} read`;
1244 const beginId = PerformanceStatistics.beginMeasure(measureId);
1245 configuration = JSON.parse(
1246 fs.readFileSync(this.configurationFile, 'utf8')
1247 ) as ChargingStationConfiguration;
1248 PerformanceStatistics.endMeasure(measureId, beginId);
1249 this.configurationFileHash = configuration.configurationHash;
1250 this.sharedLRUCache.setChargingStationConfiguration(configuration);
1251 }
1252 } catch (error) {
1253 FileUtils.handleFileException(
1254 this.logPrefix(),
1255 FileType.ChargingStationConfiguration,
1256 this.configurationFile,
1257 error as NodeJS.ErrnoException
1258 );
1259 }
1260 }
1261 return configuration;
1262 }
1263
1264 private saveConfiguration(): void {
1265 if (this.configurationFile) {
1266 try {
1267 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1268 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1269 }
1270 const configurationData: ChargingStationConfiguration =
1271 this.getConfigurationFromFile() ?? {};
1272 this.ocppConfiguration?.configurationKey &&
1273 (configurationData.configurationKey = this.ocppConfiguration.configurationKey);
1274 this.stationInfo && (configurationData.stationInfo = this.stationInfo);
1275 delete configurationData.configurationHash;
1276 const configurationHash = crypto
1277 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1278 .update(JSON.stringify(configurationData))
1279 .digest('hex');
1280 if (this.configurationFileHash !== configurationHash) {
1281 configurationData.configurationHash = configurationHash;
1282 const measureId = `${FileType.ChargingStationConfiguration} write`;
1283 const beginId = PerformanceStatistics.beginMeasure(measureId);
1284 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1285 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1286 fs.closeSync(fileDescriptor);
1287 PerformanceStatistics.endMeasure(measureId, beginId);
1288 this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
1289 this.configurationFileHash = configurationHash;
1290 this.sharedLRUCache.setChargingStationConfiguration(configurationData);
1291 } else {
1292 logger.debug(
1293 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1294 this.configurationFile
1295 }`
1296 );
1297 }
1298 } catch (error) {
1299 FileUtils.handleFileException(
1300 this.logPrefix(),
1301 FileType.ChargingStationConfiguration,
1302 this.configurationFile,
1303 error as NodeJS.ErrnoException
1304 );
1305 }
1306 } else {
1307 logger.error(
1308 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1309 );
1310 }
1311 }
1312
1313 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null {
1314 return this.getTemplateFromFile()?.Configuration ?? null;
1315 }
1316
1317 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1318 let configuration: ChargingStationConfiguration = null;
1319 if (this.getOcppPersistentConfiguration()) {
1320 const configurationFromFile = this.getConfigurationFromFile();
1321 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1322 }
1323 configuration && delete configuration.stationInfo;
1324 return configuration;
1325 }
1326
1327 private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
1328 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1329 if (!ocppConfiguration) {
1330 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1331 }
1332 return ocppConfiguration;
1333 }
1334
1335 private async onOpen(): Promise<void> {
1336 if (this.isWebSocketConnectionOpened()) {
1337 logger.info(
1338 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1339 );
1340 if (!this.isRegistered()) {
1341 // Send BootNotification
1342 let registrationRetryCount = 0;
1343 do {
1344 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
1345 BootNotificationRequest,
1346 BootNotificationResponse
1347 >(
1348 this,
1349 RequestCommand.BOOT_NOTIFICATION,
1350 {
1351 chargePointModel: this.bootNotificationRequest.chargePointModel,
1352 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1353 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1354 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1355 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1356 iccid: this.bootNotificationRequest.iccid,
1357 imsi: this.bootNotificationRequest.imsi,
1358 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1359 meterType: this.bootNotificationRequest.meterType,
1360 },
1361 { skipBufferingOnError: true }
1362 );
1363 if (!this.isRegistered()) {
1364 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1365 await Utils.sleep(
1366 this.bootNotificationResponse?.interval
1367 ? this.bootNotificationResponse.interval * 1000
1368 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1369 );
1370 }
1371 } while (
1372 !this.isRegistered() &&
1373 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1374 this.getRegistrationMaxRetries() === -1)
1375 );
1376 }
1377 if (this.isRegistered()) {
1378 if (this.isInAcceptedState()) {
1379 await this.startMessageSequence();
1380 this.wsConnectionRestarted && this.flushMessageBuffer();
1381 }
1382 } else {
1383 logger.error(
1384 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1385 );
1386 }
1387 this.stopped && (this.stopped = false);
1388 this.autoReconnectRetryCount = 0;
1389 this.wsConnectionRestarted = false;
1390 } else {
1391 logger.warn(
1392 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1393 );
1394 }
1395 }
1396
1397 private async onClose(code: number, reason: string): Promise<void> {
1398 switch (code) {
1399 // Normal close
1400 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1401 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1402 logger.info(
1403 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1404 code
1405 )}' and reason '${reason}'`
1406 );
1407 this.autoReconnectRetryCount = 0;
1408 break;
1409 // Abnormal close
1410 default:
1411 logger.error(
1412 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1413 code
1414 )}' and reason '${reason}'`
1415 );
1416 await this.reconnect(code);
1417 break;
1418 }
1419 }
1420
1421 private async onMessage(data: Data): Promise<void> {
1422 let messageType: number;
1423 let messageId: string;
1424 let commandName: IncomingRequestCommand;
1425 let commandPayload: JsonType;
1426 let errorType: ErrorType;
1427 let errorMessage: string;
1428 let errorDetails: JsonType;
1429 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
1430 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1431 let requestCommandName: RequestCommand | IncomingRequestCommand;
1432 let requestPayload: JsonType;
1433 let cachedRequest: CachedRequest;
1434 let errMsg: string;
1435 try {
1436 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
1437 if (Array.isArray(request) === true) {
1438 [messageType, messageId] = request;
1439 // Check the type of message
1440 switch (messageType) {
1441 // Incoming Message
1442 case MessageType.CALL_MESSAGE:
1443 [, , commandName, commandPayload] = request as IncomingRequest;
1444 if (this.getEnableStatistics()) {
1445 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1446 }
1447 logger.debug(
1448 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1449 request
1450 )}`
1451 );
1452 // Process the message
1453 await this.ocppIncomingRequestService.incomingRequestHandler(
1454 this,
1455 messageId,
1456 commandName,
1457 commandPayload
1458 );
1459 break;
1460 // Outcome Message
1461 case MessageType.CALL_RESULT_MESSAGE:
1462 [, , commandPayload] = request as Response;
1463 if (!this.requests.has(messageId)) {
1464 // Error
1465 throw new OCPPError(
1466 ErrorType.INTERNAL_ERROR,
1467 `Response for unknown message id ${messageId}`,
1468 null,
1469 commandPayload
1470 );
1471 }
1472 // Respond
1473 cachedRequest = this.requests.get(messageId);
1474 if (Array.isArray(cachedRequest) === true) {
1475 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1476 } else {
1477 throw new OCPPError(
1478 ErrorType.PROTOCOL_ERROR,
1479 `Cached request for message id ${messageId} response is not an array`,
1480 null,
1481 cachedRequest as unknown as JsonType
1482 );
1483 }
1484 logger.debug(
1485 `${this.logPrefix()} << Command '${
1486 requestCommandName ?? 'unknown'
1487 }' received response payload: ${JSON.stringify(request)}`
1488 );
1489 responseCallback(commandPayload, requestPayload);
1490 break;
1491 // Error Message
1492 case MessageType.CALL_ERROR_MESSAGE:
1493 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1494 if (!this.requests.has(messageId)) {
1495 // Error
1496 throw new OCPPError(
1497 ErrorType.INTERNAL_ERROR,
1498 `Error response for unknown message id ${messageId}`,
1499 null,
1500 { errorType, errorMessage, errorDetails }
1501 );
1502 }
1503 cachedRequest = this.requests.get(messageId);
1504 if (Array.isArray(cachedRequest) === true) {
1505 [, errorCallback, requestCommandName] = cachedRequest;
1506 } else {
1507 throw new OCPPError(
1508 ErrorType.PROTOCOL_ERROR,
1509 `Cached request for message id ${messageId} error response is not an array`,
1510 null,
1511 cachedRequest as unknown as JsonType
1512 );
1513 }
1514 logger.debug(
1515 `${this.logPrefix()} << Command '${
1516 requestCommandName ?? 'unknown'
1517 }' received error payload: ${JSON.stringify(request)}`
1518 );
1519 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
1520 break;
1521 // Error
1522 default:
1523 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1524 errMsg = `Wrong message type ${messageType}`;
1525 logger.error(`${this.logPrefix()} ${errMsg}`);
1526 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1527 }
1528 parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
1529 } else {
1530 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, {
1531 payload: request,
1532 });
1533 }
1534 } catch (error) {
1535 // Log
1536 logger.error(
1537 `${this.logPrefix()} Incoming OCPP command '${
1538 commandName ?? requestCommandName ?? null
1539 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1540 this.requests.get(messageId)
1541 )}' processing error:`,
1542 error
1543 );
1544 if (!(error instanceof OCPPError)) {
1545 logger.warn(
1546 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1547 commandName ?? requestCommandName ?? null
1548 }' message '${data.toString()}' handling is not an OCPPError:`,
1549 error
1550 );
1551 }
1552 // Send error
1553 messageType === MessageType.CALL_MESSAGE &&
1554 (await this.ocppRequestService.sendError(
1555 this,
1556 messageId,
1557 error as OCPPError,
1558 commandName ?? requestCommandName ?? null
1559 ));
1560 }
1561 }
1562
1563 private onPing(): void {
1564 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1565 }
1566
1567 private onPong(): void {
1568 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1569 }
1570
1571 private onError(error: WSError): void {
1572 this.closeWSConnection();
1573 logger.error(this.logPrefix() + ' WebSocket error:', error);
1574 }
1575
1576 private getEnergyActiveImportRegister(
1577 connectorStatus: ConnectorStatus,
1578 meterStop = false
1579 ): number {
1580 if (this.getMeteringPerTransaction()) {
1581 return (
1582 (meterStop === true
1583 ? Math.round(connectorStatus?.transactionEnergyActiveImportRegisterValue)
1584 : connectorStatus?.transactionEnergyActiveImportRegisterValue) ?? 0
1585 );
1586 }
1587 return (
1588 (meterStop === true
1589 ? Math.round(connectorStatus?.energyActiveImportRegisterValue)
1590 : connectorStatus?.energyActiveImportRegisterValue) ?? 0
1591 );
1592 }
1593
1594 private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean | undefined {
1595 const localStationInfo = stationInfo ?? this.stationInfo;
1596 return !Utils.isUndefined(localStationInfo.useConnectorId0)
1597 ? localStationInfo.useConnectorId0
1598 : true;
1599 }
1600
1601 private getNumberOfRunningTransactions(): number {
1602 let trxCount = 0;
1603 for (const connectorId of this.connectors.keys()) {
1604 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1605 trxCount++;
1606 }
1607 }
1608 return trxCount;
1609 }
1610
1611 // 0 for disabling
1612 private getConnectionTimeout(): number | undefined {
1613 if (
1614 ChargingStationConfigurationUtils.getConfigurationKey(
1615 this,
1616 StandardParametersKey.ConnectionTimeOut
1617 )
1618 ) {
1619 return (
1620 parseInt(
1621 ChargingStationConfigurationUtils.getConfigurationKey(
1622 this,
1623 StandardParametersKey.ConnectionTimeOut
1624 ).value
1625 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
1626 );
1627 }
1628 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1629 }
1630
1631 // -1 for unlimited, 0 for disabling
1632 private getAutoReconnectMaxRetries(): number | undefined {
1633 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1634 return this.stationInfo.autoReconnectMaxRetries;
1635 }
1636 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1637 return Configuration.getAutoReconnectMaxRetries();
1638 }
1639 return -1;
1640 }
1641
1642 // 0 for disabling
1643 private getRegistrationMaxRetries(): number | undefined {
1644 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1645 return this.stationInfo.registrationMaxRetries;
1646 }
1647 return -1;
1648 }
1649
1650 private getPowerDivider(): number {
1651 let powerDivider = this.getNumberOfConnectors();
1652 if (this.stationInfo?.powerSharedByConnectors) {
1653 powerDivider = this.getNumberOfRunningTransactions();
1654 }
1655 return powerDivider;
1656 }
1657
1658 private getMaximumPower(stationInfo?: ChargingStationInfo): number {
1659 const localStationInfo = stationInfo ?? this.stationInfo;
1660 return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower;
1661 }
1662
1663 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
1664 const maximumPower = this.getMaximumPower(stationInfo);
1665 switch (this.getCurrentOutType(stationInfo)) {
1666 case CurrentType.AC:
1667 return ACElectricUtils.amperagePerPhaseFromPower(
1668 this.getNumberOfPhases(stationInfo),
1669 maximumPower / this.getNumberOfConnectors(),
1670 this.getVoltageOut(stationInfo)
1671 );
1672 case CurrentType.DC:
1673 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
1674 }
1675 }
1676
1677 private getAmperageLimitation(): number | undefined {
1678 if (
1679 this.stationInfo.amperageLimitationOcppKey &&
1680 ChargingStationConfigurationUtils.getConfigurationKey(
1681 this,
1682 this.stationInfo.amperageLimitationOcppKey
1683 )
1684 ) {
1685 return (
1686 Utils.convertToInt(
1687 ChargingStationConfigurationUtils.getConfigurationKey(
1688 this,
1689 this.stationInfo.amperageLimitationOcppKey
1690 ).value
1691 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
1692 );
1693 }
1694 }
1695
1696 private async startMessageSequence(): Promise<void> {
1697 if (this.stationInfo?.autoRegister) {
1698 await this.ocppRequestService.requestHandler<
1699 BootNotificationRequest,
1700 BootNotificationResponse
1701 >(
1702 this,
1703 RequestCommand.BOOT_NOTIFICATION,
1704 {
1705 chargePointModel: this.bootNotificationRequest.chargePointModel,
1706 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1707 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1708 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1709 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1710 iccid: this.bootNotificationRequest.iccid,
1711 imsi: this.bootNotificationRequest.imsi,
1712 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1713 meterType: this.bootNotificationRequest.meterType,
1714 },
1715 { skipBufferingOnError: true }
1716 );
1717 }
1718 // Start WebSocket ping
1719 this.startWebSocketPing();
1720 // Start heartbeat
1721 this.startHeartbeat();
1722 // Initialize connectors status
1723 for (const connectorId of this.connectors.keys()) {
1724 if (connectorId === 0) {
1725 continue;
1726 } else if (
1727 !this.stopped &&
1728 !this.getConnectorStatus(connectorId)?.status &&
1729 this.getConnectorStatus(connectorId)?.bootStatus
1730 ) {
1731 // Send status in template at startup
1732 await this.ocppRequestService.requestHandler<
1733 StatusNotificationRequest,
1734 StatusNotificationResponse
1735 >(this, RequestCommand.STATUS_NOTIFICATION, {
1736 connectorId,
1737 status: this.getConnectorStatus(connectorId).bootStatus,
1738 errorCode: ChargePointErrorCode.NO_ERROR,
1739 });
1740 this.getConnectorStatus(connectorId).status =
1741 this.getConnectorStatus(connectorId).bootStatus;
1742 } else if (
1743 this.stopped &&
1744 this.getConnectorStatus(connectorId)?.status &&
1745 this.getConnectorStatus(connectorId)?.bootStatus
1746 ) {
1747 // Send status in template after reset
1748 await this.ocppRequestService.requestHandler<
1749 StatusNotificationRequest,
1750 StatusNotificationResponse
1751 >(this, RequestCommand.STATUS_NOTIFICATION, {
1752 connectorId,
1753 status: this.getConnectorStatus(connectorId).bootStatus,
1754 errorCode: ChargePointErrorCode.NO_ERROR,
1755 });
1756 this.getConnectorStatus(connectorId).status =
1757 this.getConnectorStatus(connectorId).bootStatus;
1758 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1759 // Send previous status at template reload
1760 await this.ocppRequestService.requestHandler<
1761 StatusNotificationRequest,
1762 StatusNotificationResponse
1763 >(this, RequestCommand.STATUS_NOTIFICATION, {
1764 connectorId,
1765 status: this.getConnectorStatus(connectorId).status,
1766 errorCode: ChargePointErrorCode.NO_ERROR,
1767 });
1768 } else {
1769 // Send default status
1770 await this.ocppRequestService.requestHandler<
1771 StatusNotificationRequest,
1772 StatusNotificationResponse
1773 >(this, RequestCommand.STATUS_NOTIFICATION, {
1774 connectorId,
1775 status: ChargePointStatus.AVAILABLE,
1776 errorCode: ChargePointErrorCode.NO_ERROR,
1777 });
1778 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1779 }
1780 }
1781 // Start the ATG
1782 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable) {
1783 this.startAutomaticTransactionGenerator();
1784 }
1785 }
1786
1787 private async stopMessageSequence(
1788 reason: StopTransactionReason = StopTransactionReason.NONE
1789 ): Promise<void> {
1790 // Stop WebSocket ping
1791 this.stopWebSocketPing();
1792 // Stop heartbeat
1793 this.stopHeartbeat();
1794 // Stop ongoing transactions
1795 if (this.getNumberOfRunningTransactions() > 0) {
1796 if (this.automaticTransactionGenerator?.started) {
1797 this.stopAutomaticTransactionGenerator();
1798 } else {
1799 for (const connectorId of this.connectors.keys()) {
1800 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1801 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1802 if (
1803 this.getBeginEndMeterValues() &&
1804 this.getOcppStrictCompliance() &&
1805 !this.getOutOfOrderEndMeterValues()
1806 ) {
1807 // FIXME: Implement OCPP version agnostic helpers
1808 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1809 this,
1810 connectorId,
1811 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1812 );
1813 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
1814 this,
1815 RequestCommand.METER_VALUES,
1816 {
1817 connectorId,
1818 transactionId,
1819 meterValue: [transactionEndMeterValue],
1820 }
1821 );
1822 }
1823 await this.ocppRequestService.requestHandler<
1824 StopTransactionRequest,
1825 StopTransactionResponse
1826 >(this, RequestCommand.STOP_TRANSACTION, {
1827 transactionId,
1828 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true),
1829 idTag: this.getTransactionIdTag(transactionId),
1830 reason,
1831 });
1832 }
1833 }
1834 }
1835 }
1836 }
1837
1838 private startWebSocketPing(): void {
1839 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
1840 this,
1841 StandardParametersKey.WebSocketPingInterval
1842 )
1843 ? Utils.convertToInt(
1844 ChargingStationConfigurationUtils.getConfigurationKey(
1845 this,
1846 StandardParametersKey.WebSocketPingInterval
1847 ).value
1848 )
1849 : 0;
1850 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1851 this.webSocketPingSetInterval = setInterval(() => {
1852 if (this.isWebSocketConnectionOpened()) {
1853 this.wsConnection.ping((): void => {
1854 /* This is intentional */
1855 });
1856 }
1857 }, webSocketPingInterval * 1000);
1858 logger.info(
1859 this.logPrefix() +
1860 ' WebSocket ping started every ' +
1861 Utils.formatDurationSeconds(webSocketPingInterval)
1862 );
1863 } else if (this.webSocketPingSetInterval) {
1864 logger.info(
1865 this.logPrefix() +
1866 ' WebSocket ping every ' +
1867 Utils.formatDurationSeconds(webSocketPingInterval) +
1868 ' already started'
1869 );
1870 } else {
1871 logger.error(
1872 `${this.logPrefix()} WebSocket ping interval set to ${
1873 webSocketPingInterval
1874 ? Utils.formatDurationSeconds(webSocketPingInterval)
1875 : webSocketPingInterval
1876 }, not starting the WebSocket ping`
1877 );
1878 }
1879 }
1880
1881 private stopWebSocketPing(): void {
1882 if (this.webSocketPingSetInterval) {
1883 clearInterval(this.webSocketPingSetInterval);
1884 }
1885 }
1886
1887 private getConfiguredSupervisionUrl(): URL {
1888 const supervisionUrls = Utils.cloneObject<string | string[]>(
1889 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1890 );
1891 if (!Utils.isEmptyArray(supervisionUrls)) {
1892 let urlIndex = 0;
1893 switch (Configuration.getSupervisionUrlDistribution()) {
1894 case SupervisionUrlDistribution.ROUND_ROBIN:
1895 urlIndex = (this.index - 1) % supervisionUrls.length;
1896 break;
1897 case SupervisionUrlDistribution.RANDOM:
1898 // Get a random url
1899 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1900 break;
1901 case SupervisionUrlDistribution.SEQUENTIAL:
1902 if (this.index <= supervisionUrls.length) {
1903 urlIndex = this.index - 1;
1904 } else {
1905 logger.warn(
1906 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1907 );
1908 }
1909 break;
1910 default:
1911 logger.error(
1912 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1913 SupervisionUrlDistribution.ROUND_ROBIN
1914 }`
1915 );
1916 urlIndex = (this.index - 1) % supervisionUrls.length;
1917 break;
1918 }
1919 return new URL(supervisionUrls[urlIndex]);
1920 }
1921 return new URL(supervisionUrls as string);
1922 }
1923
1924 private getHeartbeatInterval(): number | undefined {
1925 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1926 this,
1927 StandardParametersKey.HeartbeatInterval
1928 );
1929 if (HeartbeatInterval) {
1930 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1931 }
1932 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1933 this,
1934 StandardParametersKey.HeartBeatInterval
1935 );
1936 if (HeartBeatInterval) {
1937 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1938 }
1939 !this.stationInfo?.autoRegister &&
1940 logger.warn(
1941 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1942 Constants.DEFAULT_HEARTBEAT_INTERVAL
1943 }`
1944 );
1945 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1946 }
1947
1948 private stopHeartbeat(): void {
1949 if (this.heartbeatSetInterval) {
1950 clearInterval(this.heartbeatSetInterval);
1951 }
1952 }
1953
1954 private terminateWSConnection(): void {
1955 if (this.isWebSocketConnectionOpened()) {
1956 this.wsConnection.terminate();
1957 this.wsConnection = null;
1958 }
1959 }
1960
1961 private stopMeterValues(connectorId: number) {
1962 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1963 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1964 }
1965 }
1966
1967 private getReconnectExponentialDelay(): boolean | undefined {
1968 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1969 ? this.stationInfo.reconnectExponentialDelay
1970 : false;
1971 }
1972
1973 private async reconnect(code: number): Promise<void> {
1974 // Stop WebSocket ping
1975 this.stopWebSocketPing();
1976 // Stop heartbeat
1977 this.stopHeartbeat();
1978 // Stop the ATG if needed
1979 if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure) {
1980 this.stopAutomaticTransactionGenerator();
1981 }
1982 if (
1983 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1984 this.getAutoReconnectMaxRetries() === -1
1985 ) {
1986 this.autoReconnectRetryCount++;
1987 const reconnectDelay = this.getReconnectExponentialDelay()
1988 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1989 : this.getConnectionTimeout() * 1000;
1990 const reconnectDelayWithdraw = 1000;
1991 const reconnectTimeout =
1992 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
1993 ? reconnectDelay - reconnectDelayWithdraw
1994 : 0;
1995 logger.error(
1996 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1997 reconnectDelay,
1998 2
1999 )}ms, timeout ${reconnectTimeout}ms`
2000 );
2001 await Utils.sleep(reconnectDelay);
2002 logger.error(
2003 this.logPrefix() +
2004 ' WebSocket: reconnecting try #' +
2005 this.autoReconnectRetryCount.toString()
2006 );
2007 this.openWSConnection(
2008 { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout },
2009 { closeOpened: true }
2010 );
2011 this.wsConnectionRestarted = true;
2012 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2013 logger.error(
2014 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2015 this.autoReconnectRetryCount
2016 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2017 );
2018 }
2019 }
2020
2021 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null {
2022 return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null;
2023 }
2024
2025 private initializeConnectorStatus(connectorId: number): void {
2026 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2027 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2028 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2029 this.getConnectorStatus(connectorId).transactionStarted = false;
2030 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2031 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2032 }
2033 }