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