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