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