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