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