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