bceba844bf39cd51b38a5562a201de5e8ebdbd73
[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 bufferMessage(message: string): void {
841 this.messageBuffer.add(message);
842 }
843
844 private flushMessageBuffer() {
845 if (this.messageBuffer.size > 0) {
846 this.messageBuffer.forEach((message) => {
847 // TODO: evaluate the need to track performance
848 this.wsConnection.send(message);
849 this.messageBuffer.delete(message);
850 });
851 }
852 }
853
854 private getSupervisionUrlOcppConfiguration(): boolean {
855 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
856 }
857
858 private getSupervisionUrlOcppKey(): string {
859 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
860 }
861
862 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
863 // In case of multiple instances: add instance index to charging station id
864 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
865 const idSuffix = stationTemplate.nameSuffix ?? '';
866 const idStr = '000000000' + this.index.toString();
867 return stationTemplate.fixedName
868 ? stationTemplate.baseName
869 : stationTemplate.baseName +
870 '-' +
871 instanceIndex.toString() +
872 idStr.substring(idStr.length - 4) +
873 idSuffix;
874 }
875
876 private getRandomSerialNumberSuffix(params?: {
877 randomBytesLength?: number;
878 upperCase?: boolean;
879 }): string {
880 const randomSerialNumberSuffix = crypto
881 .randomBytes(params?.randomBytesLength ?? 16)
882 .toString('hex');
883 if (params?.upperCase) {
884 return randomSerialNumberSuffix.toUpperCase();
885 }
886 return randomSerialNumberSuffix;
887 }
888
889 private getTemplateFromFile(): ChargingStationTemplate | null {
890 let template: ChargingStationTemplate = null;
891 try {
892 const measureId = `${FileType.ChargingStationTemplate} read`;
893 const beginId = PerformanceStatistics.beginMeasure(measureId);
894 template = JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate;
895 PerformanceStatistics.endMeasure(measureId, beginId);
896 } catch (error) {
897 FileUtils.handleFileException(
898 this.logPrefix(),
899 FileType.ChargingStationTemplate,
900 this.templateFile,
901 error as NodeJS.ErrnoException
902 );
903 }
904 return template;
905 }
906
907 private createSerialNumber(
908 stationInfo: ChargingStationInfo,
909 existingStationInfo?: ChargingStationInfo,
910 params: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean } = {
911 randomSerialNumberUpperCase: true,
912 randomSerialNumber: true,
913 }
914 ): void {
915 params = params ?? {};
916 params.randomSerialNumberUpperCase = params?.randomSerialNumberUpperCase ?? true;
917 params.randomSerialNumber = params?.randomSerialNumber ?? true;
918 if (existingStationInfo) {
919 existingStationInfo?.chargePointSerialNumber &&
920 (stationInfo.chargePointSerialNumber = existingStationInfo.chargePointSerialNumber);
921 existingStationInfo?.chargeBoxSerialNumber &&
922 (stationInfo.chargeBoxSerialNumber = existingStationInfo.chargeBoxSerialNumber);
923 } else {
924 const serialNumberSuffix = params?.randomSerialNumber
925 ? this.getRandomSerialNumberSuffix({ upperCase: params.randomSerialNumberUpperCase })
926 : '';
927 stationInfo.chargePointSerialNumber =
928 stationInfo?.chargePointSerialNumberPrefix &&
929 stationInfo.chargePointSerialNumberPrefix + serialNumberSuffix;
930 stationInfo.chargeBoxSerialNumber =
931 stationInfo?.chargeBoxSerialNumberPrefix &&
932 stationInfo.chargeBoxSerialNumberPrefix + serialNumberSuffix;
933 }
934 }
935
936 private getStationInfoFromTemplate(): ChargingStationInfo {
937 const stationInfo: ChargingStationInfo =
938 this.getTemplateFromFile() ?? ({} as ChargingStationInfo);
939 stationInfo.hash = crypto
940 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
941 .update(JSON.stringify(stationInfo))
942 .digest('hex');
943 const chargingStationId = this.getChargingStationId(stationInfo);
944 // Deprecation template keys section
945 this.warnDeprecatedTemplateKey(
946 stationInfo,
947 'supervisionUrl',
948 chargingStationId,
949 "Use 'supervisionUrls' instead"
950 );
951 this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls');
952 stationInfo.wsOptions = stationInfo?.wsOptions ?? {};
953 if (!Utils.isEmptyArray(stationInfo.power)) {
954 stationInfo.power = stationInfo.power as number[];
955 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length);
956 stationInfo.maximumPower =
957 stationInfo.powerUnit === PowerUnits.KILO_WATT
958 ? stationInfo.power[powerArrayRandomIndex] * 1000
959 : stationInfo.power[powerArrayRandomIndex];
960 } else {
961 stationInfo.power = stationInfo.power as number;
962 stationInfo.maximumPower =
963 stationInfo.powerUnit === PowerUnits.KILO_WATT
964 ? stationInfo.power * 1000
965 : stationInfo.power;
966 }
967 delete stationInfo.power;
968 delete stationInfo.powerUnit;
969 stationInfo.chargingStationId = chargingStationId;
970 stationInfo.resetTime = stationInfo.resetTime
971 ? stationInfo.resetTime * 1000
972 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
973 return stationInfo;
974 }
975
976 private getStationInfoFromFile(): ChargingStationInfo | null {
977 return this.getConfigurationFromFile()?.stationInfo ?? null;
978 }
979
980 private getStationInfo(): ChargingStationInfo {
981 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
982 this.hashId = this.getHashId(stationInfoFromTemplate);
983 this.configurationFile = path.join(
984 path.resolve(__dirname, '../'),
985 'assets',
986 'configurations',
987 this.hashId + '.json'
988 );
989 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
990 if (stationInfoFromFile?.hash === stationInfoFromTemplate.hash) {
991 return stationInfoFromFile;
992 }
993 this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile);
994 return stationInfoFromTemplate;
995 }
996
997 private saveStationInfo(): void {
998 this.saveConfiguration(Section.stationInfo);
999 }
1000
1001 private getOcppVersion(): OCPPVersion {
1002 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
1003 }
1004
1005 private getOcppPersistentConfiguration(): boolean {
1006 return this.stationInfo.ocppPersistentConfiguration ?? true;
1007 }
1008
1009 private handleUnsupportedVersion(version: OCPPVersion) {
1010 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
1011 this.templateFile
1012 }`;
1013 logger.error(errMsg);
1014 throw new Error(errMsg);
1015 }
1016
1017 private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest {
1018 return {
1019 chargePointModel: stationInfo.chargePointModel,
1020 chargePointVendor: stationInfo.chargePointVendor,
1021 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && {
1022 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
1023 }),
1024 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && {
1025 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
1026 }),
1027 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1028 firmwareVersion: stationInfo.firmwareVersion,
1029 }),
1030 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1031 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
1032 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
1033 meterSerialNumber: stationInfo.meterSerialNumber,
1034 }),
1035 ...(!Utils.isUndefined(stationInfo.meterType) && {
1036 meterType: stationInfo.meterType,
1037 }),
1038 };
1039 }
1040
1041 private getHashId(stationInfo: ChargingStationInfo): string {
1042 const hashBootNotificationRequest = {
1043 chargePointModel: stationInfo.chargePointModel,
1044 chargePointVendor: stationInfo.chargePointVendor,
1045 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && {
1046 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix,
1047 }),
1048 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && {
1049 chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix,
1050 }),
1051 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1052 firmwareVersion: stationInfo.firmwareVersion,
1053 }),
1054 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1055 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
1056 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
1057 meterSerialNumber: stationInfo.meterSerialNumber,
1058 }),
1059 ...(!Utils.isUndefined(stationInfo.meterType) && {
1060 meterType: stationInfo.meterType,
1061 }),
1062 };
1063 return crypto
1064 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1065 .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId)
1066 .digest('hex');
1067 }
1068
1069 private initialize(): void {
1070 this.stationInfo = this.getStationInfo();
1071 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
1072 this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo);
1073 this.ocppConfiguration = this.getOcppConfiguration();
1074 delete this.stationInfo.Configuration;
1075 // Build connectors if needed
1076 const maxConnectors = this.getMaxNumberOfConnectors();
1077 if (maxConnectors <= 0) {
1078 logger.warn(
1079 `${this.logPrefix()} Charging station template ${
1080 this.templateFile
1081 } with ${maxConnectors} connectors`
1082 );
1083 }
1084 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
1085 if (templateMaxConnectors <= 0) {
1086 logger.warn(
1087 `${this.logPrefix()} Charging station template ${
1088 this.templateFile
1089 } with no connector configuration`
1090 );
1091 }
1092 if (!this.stationInfo.Connectors[0]) {
1093 logger.warn(
1094 `${this.logPrefix()} Charging station template ${
1095 this.templateFile
1096 } with no connector Id 0 configuration`
1097 );
1098 }
1099 // Sanity check
1100 if (
1101 maxConnectors >
1102 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
1103 !this.stationInfo.randomConnectors
1104 ) {
1105 logger.warn(
1106 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
1107 this.templateFile
1108 }, forcing random connector configurations affectation`
1109 );
1110 this.stationInfo.randomConnectors = true;
1111 }
1112 const connectorsConfigHash = crypto
1113 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1114 .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
1115 .digest('hex');
1116 const connectorsConfigChanged =
1117 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1118 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1119 connectorsConfigChanged && this.connectors.clear();
1120 this.connectorsConfigurationHash = connectorsConfigHash;
1121 // Add connector Id 0
1122 let lastConnector = '0';
1123 for (lastConnector in this.stationInfo.Connectors) {
1124 const lastConnectorId = Utils.convertToInt(lastConnector);
1125 if (
1126 lastConnectorId === 0 &&
1127 this.getUseConnectorId0() &&
1128 this.stationInfo.Connectors[lastConnector]
1129 ) {
1130 this.connectors.set(
1131 lastConnectorId,
1132 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])
1133 );
1134 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1135 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1136 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1137 }
1138 }
1139 }
1140 // Generate all connectors
1141 if (
1142 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
1143 ) {
1144 for (let index = 1; index <= maxConnectors; index++) {
1145 const randConnectorId = this.stationInfo.randomConnectors
1146 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1147 : index;
1148 this.connectors.set(
1149 index,
1150 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])
1151 );
1152 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1153 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1154 this.getConnectorStatus(index).chargingProfiles = [];
1155 }
1156 }
1157 }
1158 }
1159 // The connectors attribute need to be initialized
1160 this.stationInfo.maximumAmperage = this.getMaximumAmperage();
1161 this.saveStationInfo();
1162 // Avoid duplication of connectors related information in RAM
1163 delete this.stationInfo.Connectors;
1164 // Initialize transaction attributes on connectors
1165 for (const connectorId of this.connectors.keys()) {
1166 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1167 this.initializeConnectorStatus(connectorId);
1168 }
1169 }
1170 this.wsConfiguredConnectionUrl = new URL(
1171 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
1172 );
1173 // OCPP configuration
1174 this.initializeOcppConfiguration();
1175 switch (this.getOcppVersion()) {
1176 case OCPPVersion.VERSION_16:
1177 this.ocppIncomingRequestService =
1178 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
1179 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
1180 this,
1181 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
1182 );
1183 break;
1184 default:
1185 this.handleUnsupportedVersion(this.getOcppVersion());
1186 break;
1187 }
1188 if (this.stationInfo.autoRegister) {
1189 this.bootNotificationResponse = {
1190 currentTime: new Date().toISOString(),
1191 interval: this.getHeartbeatInterval() / 1000,
1192 status: RegistrationStatus.ACCEPTED,
1193 };
1194 }
1195 this.stationInfo.powerDivider = this.getPowerDivider();
1196 if (this.getEnableStatistics()) {
1197 this.performanceStatistics = PerformanceStatistics.getInstance(
1198 this.hashId,
1199 this.stationInfo.chargingStationId,
1200 this.wsConnectionUrl
1201 );
1202 }
1203 }
1204
1205 private initializeOcppConfiguration(): void {
1206 if (
1207 this.getSupervisionUrlOcppConfiguration() &&
1208 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1209 ) {
1210 this.addConfigurationKey(
1211 this.getSupervisionUrlOcppKey(),
1212 this.getConfiguredSupervisionUrl().href,
1213 { reboot: true }
1214 );
1215 } else if (
1216 !this.getSupervisionUrlOcppConfiguration() &&
1217 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1218 ) {
1219 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
1220 }
1221 if (
1222 this.stationInfo.amperageLimitationOcppKey &&
1223 !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1224 ) {
1225 this.addConfigurationKey(
1226 this.stationInfo.amperageLimitationOcppKey,
1227 (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString()
1228 );
1229 }
1230 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
1231 this.addConfigurationKey(
1232 StandardParametersKey.SupportedFeatureProfiles,
1233 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
1234 );
1235 }
1236 this.addConfigurationKey(
1237 StandardParametersKey.NumberOfConnectors,
1238 this.getNumberOfConnectors().toString(),
1239 { readonly: true },
1240 { overwrite: true }
1241 );
1242 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
1243 this.addConfigurationKey(
1244 StandardParametersKey.MeterValuesSampledData,
1245 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1246 );
1247 }
1248 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
1249 const connectorPhaseRotation = [];
1250 for (const connectorId of this.connectors.keys()) {
1251 // AC/DC
1252 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1253 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1254 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1255 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1256 // AC
1257 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1258 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1259 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1260 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1261 }
1262 }
1263 this.addConfigurationKey(
1264 StandardParametersKey.ConnectorPhaseRotation,
1265 connectorPhaseRotation.toString()
1266 );
1267 }
1268 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
1269 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
1270 }
1271 if (
1272 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
1273 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(
1274 SupportedFeatureProfiles.Local_Auth_List_Management
1275 )
1276 ) {
1277 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
1278 }
1279 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1280 this.addConfigurationKey(
1281 StandardParametersKey.ConnectionTimeOut,
1282 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1283 );
1284 }
1285 this.saveOcppConfiguration();
1286 }
1287
1288 private getConfigurationFromFile(): ChargingStationConfiguration | null {
1289 let configuration: ChargingStationConfiguration = null;
1290 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
1291 try {
1292 const measureId = `${FileType.ChargingStationConfiguration} read`;
1293 const beginId = PerformanceStatistics.beginMeasure(
1294 `${FileType.ChargingStationConfiguration} read`
1295 );
1296 configuration = JSON.parse(
1297 fs.readFileSync(this.configurationFile, 'utf8')
1298 ) as ChargingStationConfiguration;
1299 PerformanceStatistics.endMeasure(measureId, beginId);
1300 } catch (error) {
1301 FileUtils.handleFileException(
1302 this.logPrefix(),
1303 FileType.ChargingStationConfiguration,
1304 this.configurationFile,
1305 error as NodeJS.ErrnoException
1306 );
1307 }
1308 }
1309 return configuration;
1310 }
1311
1312 private saveConfiguration(section?: Section): void {
1313 if (this.configurationFile) {
1314 try {
1315 const configurationData: ChargingStationConfiguration =
1316 this.getConfigurationFromFile() ?? {};
1317 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1318 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
1319 }
1320 switch (section) {
1321 case Section.ocppConfiguration:
1322 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1323 break;
1324 case Section.stationInfo:
1325 configurationData.stationInfo = this.stationInfo;
1326 break;
1327 default:
1328 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1329 configurationData.stationInfo = this.stationInfo;
1330 break;
1331 }
1332 const measureId = `${FileType.ChargingStationConfiguration} write`;
1333 const beginId = PerformanceStatistics.beginMeasure(measureId);
1334 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1335 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1336 fs.closeSync(fileDescriptor);
1337 PerformanceStatistics.endMeasure(measureId, beginId);
1338 } catch (error) {
1339 FileUtils.handleFileException(
1340 this.logPrefix(),
1341 FileType.ChargingStationConfiguration,
1342 this.configurationFile,
1343 error as NodeJS.ErrnoException
1344 );
1345 }
1346 } else {
1347 logger.error(
1348 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
1349 );
1350 }
1351 }
1352
1353 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration {
1354 return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration);
1355 }
1356
1357 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1358 let configuration: ChargingStationConfiguration = null;
1359 if (this.getOcppPersistentConfiguration()) {
1360 const configurationFromFile = this.getConfigurationFromFile();
1361 configuration = configurationFromFile?.configurationKey && configurationFromFile;
1362 }
1363 configuration && delete configuration.stationInfo;
1364 return configuration;
1365 }
1366
1367 private getOcppConfiguration(): ChargingStationOcppConfiguration {
1368 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1369 if (!ocppConfiguration) {
1370 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1371 }
1372 return ocppConfiguration;
1373 }
1374
1375 private saveOcppConfiguration(): void {
1376 if (this.getOcppPersistentConfiguration()) {
1377 this.saveConfiguration(Section.ocppConfiguration);
1378 }
1379 }
1380
1381 private async onOpen(): Promise<void> {
1382 logger.info(
1383 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1384 );
1385 if (!this.isInAcceptedState()) {
1386 // Send BootNotification
1387 let registrationRetryCount = 0;
1388 do {
1389 this.bootNotificationResponse = await this.ocppRequestService.sendMessageHandler<
1390 BootNotificationRequest,
1391 BootNotificationResponse
1392 >(
1393 RequestCommand.BOOT_NOTIFICATION,
1394 {
1395 chargePointModel: this.bootNotificationRequest.chargePointModel,
1396 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1397 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1398 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1399 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1400 iccid: this.bootNotificationRequest.iccid,
1401 imsi: this.bootNotificationRequest.imsi,
1402 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1403 meterType: this.bootNotificationRequest.meterType,
1404 },
1405 { skipBufferingOnError: true }
1406 );
1407 if (!this.isInAcceptedState()) {
1408 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1409 await Utils.sleep(
1410 this.bootNotificationResponse?.interval
1411 ? this.bootNotificationResponse.interval * 1000
1412 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1413 );
1414 }
1415 } while (
1416 !this.isInAcceptedState() &&
1417 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1418 this.getRegistrationMaxRetries() === -1)
1419 );
1420 }
1421 if (this.isInAcceptedState()) {
1422 await this.startMessageSequence();
1423 this.stopped && (this.stopped = false);
1424 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
1425 this.flushMessageBuffer();
1426 }
1427 } else {
1428 logger.error(
1429 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1430 );
1431 }
1432 this.autoReconnectRetryCount = 0;
1433 this.wsConnectionRestarted = false;
1434 }
1435
1436 private async onClose(code: number, reason: string): Promise<void> {
1437 switch (code) {
1438 // Normal close
1439 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1440 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1441 logger.info(
1442 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1443 code
1444 )}' and reason '${reason}'`
1445 );
1446 this.autoReconnectRetryCount = 0;
1447 break;
1448 // Abnormal close
1449 default:
1450 logger.error(
1451 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1452 code
1453 )}' and reason '${reason}'`
1454 );
1455 await this.reconnect(code);
1456 break;
1457 }
1458 }
1459
1460 private async onMessage(data: Data): Promise<void> {
1461 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [
1462 0,
1463 '',
1464 '' as IncomingRequestCommand,
1465 {},
1466 {},
1467 ];
1468 let responseCallback: (
1469 payload: JsonType | string,
1470 requestPayload: JsonType | OCPPError
1471 ) => void;
1472 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1473 let requestCommandName: RequestCommand | IncomingRequestCommand;
1474 let requestPayload: JsonType | OCPPError;
1475 let cachedRequest: CachedRequest;
1476 let errMsg: string;
1477 try {
1478 const request = JSON.parse(data.toString()) as IncomingRequest;
1479 if (Utils.isIterable(request)) {
1480 // Parse the message
1481 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
1482 } else {
1483 throw new OCPPError(
1484 ErrorType.PROTOCOL_ERROR,
1485 'Incoming request is not iterable',
1486 commandName
1487 );
1488 }
1489 // Check the Type of message
1490 switch (messageType) {
1491 // Incoming Message
1492 case MessageType.CALL_MESSAGE:
1493 if (this.getEnableStatistics()) {
1494 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1495 }
1496 // Process the call
1497 await this.ocppIncomingRequestService.handleRequest(
1498 messageId,
1499 commandName,
1500 commandPayload
1501 );
1502 break;
1503 // Outcome Message
1504 case MessageType.CALL_RESULT_MESSAGE:
1505 // Respond
1506 cachedRequest = this.requests.get(messageId);
1507 if (Utils.isIterable(cachedRequest)) {
1508 [responseCallback, , , requestPayload] = cachedRequest;
1509 } else {
1510 throw new OCPPError(
1511 ErrorType.PROTOCOL_ERROR,
1512 `Cached request for message id ${messageId} response is not iterable`,
1513 commandName
1514 );
1515 }
1516 if (!responseCallback) {
1517 // Error
1518 throw new OCPPError(
1519 ErrorType.INTERNAL_ERROR,
1520 `Response for unknown message id ${messageId}`,
1521 commandName
1522 );
1523 }
1524 responseCallback(commandName, requestPayload);
1525 break;
1526 // Error Message
1527 case MessageType.CALL_ERROR_MESSAGE:
1528 cachedRequest = this.requests.get(messageId);
1529 if (Utils.isIterable(cachedRequest)) {
1530 [, rejectCallback, requestCommandName] = cachedRequest;
1531 } else {
1532 throw new OCPPError(
1533 ErrorType.PROTOCOL_ERROR,
1534 `Cached request for message id ${messageId} error response is not iterable`
1535 );
1536 }
1537 if (!rejectCallback) {
1538 // Error
1539 throw new OCPPError(
1540 ErrorType.INTERNAL_ERROR,
1541 `Error response for unknown message id ${messageId}`,
1542 requestCommandName
1543 );
1544 }
1545 rejectCallback(
1546 new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails)
1547 );
1548 break;
1549 // Error
1550 default:
1551 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1552 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1553 logger.error(errMsg);
1554 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1555 }
1556 } catch (error) {
1557 // Log
1558 logger.error(
1559 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1560 this.logPrefix(),
1561 data.toString(),
1562 this.requests.get(messageId),
1563 error
1564 );
1565 // Send error
1566 messageType === MessageType.CALL_MESSAGE &&
1567 (await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName));
1568 }
1569 }
1570
1571 private onPing(): void {
1572 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1573 }
1574
1575 private onPong(): void {
1576 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1577 }
1578
1579 private onError(error: WSError): void {
1580 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
1581 }
1582
1583 private getAuthorizationFile(): string | undefined {
1584 return (
1585 this.stationInfo.authorizationFile &&
1586 path.join(
1587 path.resolve(__dirname, '../'),
1588 'assets',
1589 path.basename(this.stationInfo.authorizationFile)
1590 )
1591 );
1592 }
1593
1594 private getAuthorizedTags(): string[] {
1595 let authorizedTags: string[] = [];
1596 const authorizationFile = this.getAuthorizationFile();
1597 if (authorizationFile) {
1598 try {
1599 // Load authorization file
1600 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
1601 } catch (error) {
1602 FileUtils.handleFileException(
1603 this.logPrefix(),
1604 FileType.Authorization,
1605 authorizationFile,
1606 error as NodeJS.ErrnoException
1607 );
1608 }
1609 } else {
1610 logger.info(
1611 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
1612 );
1613 }
1614 return authorizedTags;
1615 }
1616
1617 private getUseConnectorId0(): boolean | undefined {
1618 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1619 ? this.stationInfo.useConnectorId0
1620 : true;
1621 }
1622
1623 private getNumberOfRunningTransactions(): number {
1624 let trxCount = 0;
1625 for (const connectorId of this.connectors.keys()) {
1626 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1627 trxCount++;
1628 }
1629 }
1630 return trxCount;
1631 }
1632
1633 // 0 for disabling
1634 private getConnectionTimeout(): number | undefined {
1635 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1636 return (
1637 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1638 Constants.DEFAULT_CONNECTION_TIMEOUT
1639 );
1640 }
1641 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1642 }
1643
1644 // -1 for unlimited, 0 for disabling
1645 private getAutoReconnectMaxRetries(): number | undefined {
1646 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1647 return this.stationInfo.autoReconnectMaxRetries;
1648 }
1649 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1650 return Configuration.getAutoReconnectMaxRetries();
1651 }
1652 return -1;
1653 }
1654
1655 // 0 for disabling
1656 private getRegistrationMaxRetries(): number | undefined {
1657 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1658 return this.stationInfo.registrationMaxRetries;
1659 }
1660 return -1;
1661 }
1662
1663 private getPowerDivider(): number {
1664 let powerDivider = this.getNumberOfConnectors();
1665 if (this.stationInfo.powerSharedByConnectors) {
1666 powerDivider = this.getNumberOfRunningTransactions();
1667 }
1668 return powerDivider;
1669 }
1670
1671 private getTemplateMaxNumberOfConnectors(): number {
1672 return Object.keys(this.stationInfo.Connectors).length;
1673 }
1674
1675 private getMaxNumberOfConnectors(): number {
1676 let maxConnectors: number;
1677 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1678 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
1679 // Distribute evenly the number of connectors
1680 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1681 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1682 maxConnectors = this.stationInfo.numberOfConnectors as number;
1683 } else {
1684 maxConnectors = this.stationInfo.Connectors[0]
1685 ? this.getTemplateMaxNumberOfConnectors() - 1
1686 : this.getTemplateMaxNumberOfConnectors();
1687 }
1688 return maxConnectors;
1689 }
1690
1691 private getMaximumAmperage(): number | undefined {
1692 const maximumPower = (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower;
1693 switch (this.getCurrentOutType()) {
1694 case CurrentType.AC:
1695 return ACElectricUtils.amperagePerPhaseFromPower(
1696 this.getNumberOfPhases(),
1697 maximumPower / this.getNumberOfConnectors(),
1698 this.getVoltageOut()
1699 );
1700 case CurrentType.DC:
1701 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut());
1702 }
1703 }
1704
1705 private getAmperageLimitationUnitDivider(): number {
1706 let unitDivider = 1;
1707 switch (this.stationInfo.amperageLimitationUnit) {
1708 case AmpereUnits.DECI_AMPERE:
1709 unitDivider = 10;
1710 break;
1711 case AmpereUnits.CENTI_AMPERE:
1712 unitDivider = 100;
1713 break;
1714 case AmpereUnits.MILLI_AMPERE:
1715 unitDivider = 1000;
1716 break;
1717 }
1718 return unitDivider;
1719 }
1720
1721 private getAmperageLimitation(): number | undefined {
1722 if (
1723 this.stationInfo.amperageLimitationOcppKey &&
1724 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1725 ) {
1726 return (
1727 Utils.convertToInt(
1728 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value
1729 ) / this.getAmperageLimitationUnitDivider()
1730 );
1731 }
1732 }
1733
1734 private async startMessageSequence(): Promise<void> {
1735 if (this.stationInfo.autoRegister) {
1736 await this.ocppRequestService.sendMessageHandler<
1737 BootNotificationRequest,
1738 BootNotificationResponse
1739 >(
1740 RequestCommand.BOOT_NOTIFICATION,
1741 {
1742 chargePointModel: this.bootNotificationRequest.chargePointModel,
1743 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1744 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1745 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1746 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1747 iccid: this.bootNotificationRequest.iccid,
1748 imsi: this.bootNotificationRequest.imsi,
1749 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1750 meterType: this.bootNotificationRequest.meterType,
1751 },
1752 { skipBufferingOnError: true }
1753 );
1754 }
1755 // Start WebSocket ping
1756 this.startWebSocketPing();
1757 // Start heartbeat
1758 this.startHeartbeat();
1759 // Initialize connectors status
1760 for (const connectorId of this.connectors.keys()) {
1761 if (connectorId === 0) {
1762 continue;
1763 } else if (
1764 !this.stopped &&
1765 !this.getConnectorStatus(connectorId)?.status &&
1766 this.getConnectorStatus(connectorId)?.bootStatus
1767 ) {
1768 // Send status in template at startup
1769 await this.ocppRequestService.sendMessageHandler<
1770 StatusNotificationRequest,
1771 StatusNotificationResponse
1772 >(RequestCommand.STATUS_NOTIFICATION, {
1773 connectorId,
1774 status: this.getConnectorStatus(connectorId).bootStatus,
1775 errorCode: ChargePointErrorCode.NO_ERROR,
1776 });
1777 this.getConnectorStatus(connectorId).status =
1778 this.getConnectorStatus(connectorId).bootStatus;
1779 } else if (
1780 this.stopped &&
1781 this.getConnectorStatus(connectorId)?.status &&
1782 this.getConnectorStatus(connectorId)?.bootStatus
1783 ) {
1784 // Send status in template after reset
1785 await this.ocppRequestService.sendMessageHandler<
1786 StatusNotificationRequest,
1787 StatusNotificationResponse
1788 >(RequestCommand.STATUS_NOTIFICATION, {
1789 connectorId,
1790 status: this.getConnectorStatus(connectorId).bootStatus,
1791 errorCode: ChargePointErrorCode.NO_ERROR,
1792 });
1793 this.getConnectorStatus(connectorId).status =
1794 this.getConnectorStatus(connectorId).bootStatus;
1795 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1796 // Send previous status at template reload
1797 await this.ocppRequestService.sendMessageHandler<
1798 StatusNotificationRequest,
1799 StatusNotificationResponse
1800 >(RequestCommand.STATUS_NOTIFICATION, {
1801 connectorId,
1802 status: this.getConnectorStatus(connectorId).status,
1803 errorCode: ChargePointErrorCode.NO_ERROR,
1804 });
1805 } else {
1806 // Send default status
1807 await this.ocppRequestService.sendMessageHandler<
1808 StatusNotificationRequest,
1809 StatusNotificationResponse
1810 >(RequestCommand.STATUS_NOTIFICATION, {
1811 connectorId,
1812 status: ChargePointStatus.AVAILABLE,
1813 errorCode: ChargePointErrorCode.NO_ERROR,
1814 });
1815 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1816 }
1817 }
1818 // Start the ATG
1819 this.startAutomaticTransactionGenerator();
1820 }
1821
1822 private startAutomaticTransactionGenerator() {
1823 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
1824 if (!this.automaticTransactionGenerator) {
1825 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
1826 }
1827 if (!this.automaticTransactionGenerator.started) {
1828 this.automaticTransactionGenerator.start();
1829 }
1830 }
1831 }
1832
1833 private async stopMessageSequence(
1834 reason: StopTransactionReason = StopTransactionReason.NONE
1835 ): Promise<void> {
1836 // Stop WebSocket ping
1837 this.stopWebSocketPing();
1838 // Stop heartbeat
1839 this.stopHeartbeat();
1840 // Stop the ATG
1841 if (
1842 this.stationInfo.AutomaticTransactionGenerator.enable &&
1843 this.automaticTransactionGenerator?.started
1844 ) {
1845 this.automaticTransactionGenerator.stop();
1846 } else {
1847 for (const connectorId of this.connectors.keys()) {
1848 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1849 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1850 if (
1851 this.getBeginEndMeterValues() &&
1852 this.getOcppStrictCompliance() &&
1853 !this.getOutOfOrderEndMeterValues()
1854 ) {
1855 // FIXME: Implement OCPP version agnostic helpers
1856 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1857 this,
1858 connectorId,
1859 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1860 );
1861 await this.ocppRequestService.sendMessageHandler<
1862 MeterValuesRequest,
1863 MeterValuesResponse
1864 >(RequestCommand.METER_VALUES, {
1865 connectorId,
1866 transactionId,
1867 meterValue: transactionEndMeterValue,
1868 });
1869 }
1870 await this.ocppRequestService.sendMessageHandler<
1871 StopTransactionRequest,
1872 StopTransactionResponse
1873 >(RequestCommand.STOP_TRANSACTION, {
1874 transactionId,
1875 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1876 idTag: this.getTransactionIdTag(transactionId),
1877 reason,
1878 });
1879 }
1880 }
1881 }
1882 }
1883
1884 private startWebSocketPing(): void {
1885 const webSocketPingInterval: number = this.getConfigurationKey(
1886 StandardParametersKey.WebSocketPingInterval
1887 )
1888 ? Utils.convertToInt(
1889 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1890 )
1891 : 0;
1892 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1893 this.webSocketPingSetInterval = setInterval(() => {
1894 if (this.isWebSocketConnectionOpened()) {
1895 this.wsConnection.ping((): void => {
1896 /* This is intentional */
1897 });
1898 }
1899 }, webSocketPingInterval * 1000);
1900 logger.info(
1901 this.logPrefix() +
1902 ' WebSocket ping started every ' +
1903 Utils.formatDurationSeconds(webSocketPingInterval)
1904 );
1905 } else if (this.webSocketPingSetInterval) {
1906 logger.info(
1907 this.logPrefix() +
1908 ' WebSocket ping every ' +
1909 Utils.formatDurationSeconds(webSocketPingInterval) +
1910 ' already started'
1911 );
1912 } else {
1913 logger.error(
1914 `${this.logPrefix()} WebSocket ping interval set to ${
1915 webSocketPingInterval
1916 ? Utils.formatDurationSeconds(webSocketPingInterval)
1917 : webSocketPingInterval
1918 }, not starting the WebSocket ping`
1919 );
1920 }
1921 }
1922
1923 private stopWebSocketPing(): void {
1924 if (this.webSocketPingSetInterval) {
1925 clearInterval(this.webSocketPingSetInterval);
1926 }
1927 }
1928
1929 private warnDeprecatedTemplateKey(
1930 template: ChargingStationTemplate,
1931 key: string,
1932 chargingStationId: string,
1933 logMsgToAppend = ''
1934 ): void {
1935 if (!Utils.isUndefined(template[key])) {
1936 const logPrefixStr = ` ${chargingStationId} |`;
1937 logger.warn(
1938 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1939 this.templateFile
1940 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1941 );
1942 }
1943 }
1944
1945 private convertDeprecatedTemplateKey(
1946 template: ChargingStationTemplate,
1947 deprecatedKey: string,
1948 key: string
1949 ): void {
1950 if (!Utils.isUndefined(template[deprecatedKey])) {
1951 template[key] = template[deprecatedKey] as unknown;
1952 delete template[deprecatedKey];
1953 }
1954 }
1955
1956 private getConfiguredSupervisionUrl(): URL {
1957 const supervisionUrls = Utils.cloneObject<string | string[]>(
1958 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1959 );
1960 if (!Utils.isEmptyArray(supervisionUrls)) {
1961 let urlIndex = 0;
1962 switch (Configuration.getSupervisionUrlDistribution()) {
1963 case SupervisionUrlDistribution.ROUND_ROBIN:
1964 urlIndex = (this.index - 1) % supervisionUrls.length;
1965 break;
1966 case SupervisionUrlDistribution.RANDOM:
1967 // Get a random url
1968 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1969 break;
1970 case SupervisionUrlDistribution.SEQUENTIAL:
1971 if (this.index <= supervisionUrls.length) {
1972 urlIndex = this.index - 1;
1973 } else {
1974 logger.warn(
1975 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1976 );
1977 }
1978 break;
1979 default:
1980 logger.error(
1981 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1982 SupervisionUrlDistribution.ROUND_ROBIN
1983 }`
1984 );
1985 urlIndex = (this.index - 1) % supervisionUrls.length;
1986 break;
1987 }
1988 return new URL(supervisionUrls[urlIndex]);
1989 }
1990 return new URL(supervisionUrls as string);
1991 }
1992
1993 private getHeartbeatInterval(): number | undefined {
1994 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1995 if (HeartbeatInterval) {
1996 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1997 }
1998 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1999 if (HeartBeatInterval) {
2000 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
2001 }
2002 !this.stationInfo.autoRegister &&
2003 logger.warn(
2004 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2005 Constants.DEFAULT_HEARTBEAT_INTERVAL
2006 }`
2007 );
2008 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
2009 }
2010
2011 private stopHeartbeat(): void {
2012 if (this.heartbeatSetInterval) {
2013 clearInterval(this.heartbeatSetInterval);
2014 }
2015 }
2016
2017 private openWSConnection(
2018 options: WsOptions = this.stationInfo.wsOptions,
2019 forceCloseOpened = false
2020 ): void {
2021 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
2022 if (
2023 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
2024 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
2025 ) {
2026 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2027 }
2028 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
2029 this.wsConnection.close();
2030 }
2031 let protocol: string;
2032 switch (this.getOcppVersion()) {
2033 case OCPPVersion.VERSION_16:
2034 protocol = 'ocpp' + OCPPVersion.VERSION_16;
2035 break;
2036 default:
2037 this.handleUnsupportedVersion(this.getOcppVersion());
2038 break;
2039 }
2040 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
2041 logger.info(
2042 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
2043 );
2044 }
2045
2046 private stopMeterValues(connectorId: number) {
2047 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
2048 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
2049 }
2050 }
2051
2052 private getReconnectExponentialDelay(): boolean | undefined {
2053 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
2054 ? this.stationInfo.reconnectExponentialDelay
2055 : false;
2056 }
2057
2058 private async reconnect(code: number): Promise<void> {
2059 // Stop WebSocket ping
2060 this.stopWebSocketPing();
2061 // Stop heartbeat
2062 this.stopHeartbeat();
2063 // Stop the ATG if needed
2064 if (
2065 this.stationInfo.AutomaticTransactionGenerator.enable &&
2066 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
2067 this.automaticTransactionGenerator?.started
2068 ) {
2069 this.automaticTransactionGenerator.stop();
2070 }
2071 if (
2072 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
2073 this.getAutoReconnectMaxRetries() === -1
2074 ) {
2075 this.autoReconnectRetryCount++;
2076 const reconnectDelay = this.getReconnectExponentialDelay()
2077 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
2078 : this.getConnectionTimeout() * 1000;
2079 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
2080 logger.error(
2081 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2082 reconnectDelay,
2083 2
2084 )}ms, timeout ${reconnectTimeout}ms`
2085 );
2086 await Utils.sleep(reconnectDelay);
2087 logger.error(
2088 this.logPrefix() +
2089 ' WebSocket: reconnecting try #' +
2090 this.autoReconnectRetryCount.toString()
2091 );
2092 this.openWSConnection(
2093 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
2094 true
2095 );
2096 this.wsConnectionRestarted = true;
2097 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2098 logger.error(
2099 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2100 this.autoReconnectRetryCount
2101 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2102 );
2103 }
2104 }
2105
2106 private initializeConnectorStatus(connectorId: number): void {
2107 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2108 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2109 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
2110 this.getConnectorStatus(connectorId).transactionStarted = false;
2111 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2112 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
2113 }
2114 }