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