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