Fix truncated boot notification payload
[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
JB
962 if (Utils.isNullOrUndefined(stationInfo)) {
963 const logMsg = 'Fail to read charging station template file';
964 logger.error(`${this.logPrefix()} ${logMsg}`);
965 throw new BaseError(logMsg);
966 }
967 if (Utils.isEmptyObject(stationInfo)) {
968 logger.warn(this.logPrefix(), 'Empty charging station template file');
969 }
7a3a2ebb 970 const chargingStationId = this.getChargingStationId(stationInfo);
2dcfe98e 971 // Deprecation template keys section
e7aeea18 972 this.warnDeprecatedTemplateKey(
7a3a2ebb 973 stationInfo,
e7aeea18
JB
974 'supervisionUrl',
975 chargingStationId,
976 "Use 'supervisionUrls' instead"
977 );
7a3a2ebb
JB
978 this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls');
979 stationInfo.wsOptions = stationInfo?.wsOptions ?? {};
980 if (!Utils.isEmptyArray(stationInfo.power)) {
981 stationInfo.power = stationInfo.power as number[];
982 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length);
cc6e8ab5 983 stationInfo.maximumPower =
7a3a2ebb
JB
984 stationInfo.powerUnit === PowerUnits.KILO_WATT
985 ? stationInfo.power[powerArrayRandomIndex] * 1000
986 : stationInfo.power[powerArrayRandomIndex];
5ad8570f 987 } else {
7a3a2ebb 988 stationInfo.power = stationInfo.power as number;
cc6e8ab5 989 stationInfo.maximumPower =
7a3a2ebb
JB
990 stationInfo.powerUnit === PowerUnits.KILO_WATT
991 ? stationInfo.power * 1000
992 : stationInfo.power;
5ad8570f 993 }
fd0c36fa
JB
994 delete stationInfo.power;
995 delete stationInfo.powerUnit;
2dcfe98e 996 stationInfo.chargingStationId = chargingStationId;
7a3a2ebb
JB
997 stationInfo.resetTime = stationInfo.resetTime
998 ? stationInfo.resetTime * 1000
e7aeea18 999 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
9ac86a7e 1000 return stationInfo;
5ad8570f
JB
1001 }
1002
01efc60a 1003 private createStationInfoHash(stationInfo: ChargingStationInfo): ChargingStationInfo {
94ec7e96 1004 const previousInfoHash = stationInfo?.infoHash ?? '';
01efc60a
JB
1005 delete stationInfo.infoHash;
1006 const currentInfoHash = crypto
f765beaa
JB
1007 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1008 .update(JSON.stringify(stationInfo))
1009 .digest('hex');
01efc60a 1010 if (
94ec7e96 1011 (!Utils.isEmptyObject(stationInfo) && Utils.isEmptyString(previousInfoHash)) ||
01efc60a
JB
1012 (!Utils.isEmptyString(previousInfoHash) && currentInfoHash !== previousInfoHash)
1013 ) {
1014 stationInfo.infoHash = currentInfoHash;
94ec7e96 1015 } else if (!Utils.isEmptyObject(stationInfo)) {
01efc60a
JB
1016 stationInfo.infoHash = previousInfoHash;
1017 }
1018 return stationInfo;
1019 }
1020
1021 private getStationInfoFromFile(): ChargingStationInfo {
1022 let stationInfo = this.getConfigurationFromFile()?.stationInfo ?? ({} as ChargingStationInfo);
1023 stationInfo = this.createStationInfoHash(stationInfo);
f765beaa 1024 return stationInfo;
2484ac1e
JB
1025 }
1026
1027 private getStationInfo(): ChargingStationInfo {
1028 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
7a3a2ebb 1029 this.hashId = this.getHashId(stationInfoFromTemplate);
2484ac1e
JB
1030 this.configurationFile = path.join(
1031 path.resolve(__dirname, '../'),
1032 'assets',
1033 'configurations',
1034 this.hashId + '.json'
1035 );
1036 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
aca53a1a 1037 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
f765beaa 1038 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
01efc60a
JB
1039 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
1040 return this.stationInfo;
1041 }
2484ac1e 1042 return stationInfoFromFile;
f765beaa 1043 }
01efc60a
JB
1044 this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile);
1045 return stationInfoFromTemplate;
2484ac1e
JB
1046 }
1047
1048 private saveStationInfo(): void {
1049 this.saveConfiguration(Section.stationInfo);
1050 }
1051
1f5df42a 1052 private getOcppVersion(): OCPPVersion {
c0560973
JB
1053 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
1054 }
1055
e8e865ea
JB
1056 private getOcppPersistentConfiguration(): boolean {
1057 return this.stationInfo.ocppPersistentConfiguration ?? true;
1058 }
1059
c0560973 1060 private handleUnsupportedVersion(version: OCPPVersion) {
e7aeea18 1061 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
2484ac1e 1062 this.templateFile
e7aeea18 1063 }`;
9f2e3130 1064 logger.error(errMsg);
c0560973
JB
1065 throw new Error(errMsg);
1066 }
1067
2484ac1e
JB
1068 private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest {
1069 return {
1070 chargePointModel: stationInfo.chargePointModel,
1071 chargePointVendor: stationInfo.chargePointVendor,
1072 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && {
1073 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber,
e7aeea18 1074 }),
2484ac1e
JB
1075 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && {
1076 chargePointSerialNumber: stationInfo.chargePointSerialNumber,
43bb4cd9 1077 }),
2484ac1e
JB
1078 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1079 firmwareVersion: stationInfo.firmwareVersion,
e7aeea18 1080 }),
2484ac1e
JB
1081 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1082 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
1083 ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && {
1084 meterSerialNumber: stationInfo.meterSerialNumber,
3f94cab5 1085 }),
2484ac1e
JB
1086 ...(!Utils.isUndefined(stationInfo.meterType) && {
1087 meterType: stationInfo.meterType,
3f94cab5 1088 }),
2e6f5966 1089 };
2484ac1e
JB
1090 }
1091
7a3a2ebb
JB
1092 private getHashId(stationInfo: ChargingStationInfo): string {
1093 const hashBootNotificationRequest = {
1094 chargePointModel: stationInfo.chargePointModel,
1095 chargePointVendor: stationInfo.chargePointVendor,
1096 ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && {
1097 chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix,
1098 }),
1099 ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && {
1100 chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix,
1101 }),
1102 ...(!Utils.isUndefined(stationInfo.firmwareVersion) && {
1103 firmwareVersion: stationInfo.firmwareVersion,
1104 }),
1105 ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }),
1106 ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }),
0b7c34ba
JB
1107 ...(!Utils.isUndefined(stationInfo.meterSerialNumberPrefix) && {
1108 meterSerialNumber: stationInfo.meterSerialNumberPrefix,
7a3a2ebb
JB
1109 }),
1110 ...(!Utils.isUndefined(stationInfo.meterType) && {
1111 meterType: stationInfo.meterType,
1112 }),
1113 };
2484ac1e 1114 return crypto
3f94cab5 1115 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
7a3a2ebb 1116 .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId)
3f94cab5 1117 .digest('hex');
2484ac1e
JB
1118 }
1119
1120 private initialize(): void {
1121 this.stationInfo = this.getStationInfo();
3f94cab5 1122 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
2484ac1e
JB
1123 this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo);
1124 this.ocppConfiguration = this.getOcppConfiguration();
01efc60a 1125 this.stationInfo?.Configuration && delete this.stationInfo.Configuration;
0642c3d2
JB
1126 this.wsConfiguredConnectionUrl = new URL(
1127 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
1128 );
0a60c33c 1129 // Build connectors if needed
c0560973 1130 const maxConnectors = this.getMaxNumberOfConnectors();
6ecb15e4 1131 if (maxConnectors <= 0) {
e7aeea18
JB
1132 logger.warn(
1133 `${this.logPrefix()} Charging station template ${
2484ac1e 1134 this.templateFile
e7aeea18
JB
1135 } with ${maxConnectors} connectors`
1136 );
7abfea5f 1137 }
c0560973 1138 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
94ec7e96 1139 if (templateMaxConnectors === 0) {
e7aeea18
JB
1140 logger.warn(
1141 `${this.logPrefix()} Charging station template ${
2484ac1e 1142 this.templateFile
94ec7e96
JB
1143 } with empty connectors configuration`
1144 );
1145 } else if (templateMaxConnectors < 0) {
1146 logger.error(
1147 `${this.logPrefix()} Charging station template ${
1148 this.templateFile
1149 } with no connectors configuration defined`
e7aeea18 1150 );
593cf3f9 1151 }
94ec7e96 1152 if (!this.stationInfo?.Connectors[0]) {
e7aeea18
JB
1153 logger.warn(
1154 `${this.logPrefix()} Charging station template ${
2484ac1e 1155 this.templateFile
e7aeea18
JB
1156 } with no connector Id 0 configuration`
1157 );
7abfea5f
JB
1158 }
1159 // Sanity check
e7aeea18
JB
1160 if (
1161 maxConnectors >
94ec7e96 1162 (this.stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
e7aeea18
JB
1163 !this.stationInfo.randomConnectors
1164 ) {
1165 logger.warn(
1166 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
2484ac1e 1167 this.templateFile
e7aeea18
JB
1168 }, forcing random connector configurations affectation`
1169 );
ad2f27c3 1170 this.stationInfo.randomConnectors = true;
6ecb15e4 1171 }
e7aeea18 1172 const connectorsConfigHash = crypto
3f94cab5 1173 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
94ec7e96 1174 .update(JSON.stringify(this.stationInfo?.Connectors) + maxConnectors.toString())
e7aeea18
JB
1175 .digest('hex');
1176 const connectorsConfigChanged =
1177 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
54544ef1 1178 if (this.connectors?.size === 0 || connectorsConfigChanged) {
e7aeea18 1179 connectorsConfigChanged && this.connectors.clear();
ad2f27c3 1180 this.connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 1181 // Add connector Id 0
6af9012e 1182 let lastConnector = '0';
94ec7e96 1183 for (lastConnector in this.stationInfo?.Connectors) {
734d790d 1184 const lastConnectorId = Utils.convertToInt(lastConnector);
e7aeea18
JB
1185 if (
1186 lastConnectorId === 0 &&
1187 this.getUseConnectorId0() &&
94ec7e96 1188 this.stationInfo?.Connectors[lastConnector]
e7aeea18
JB
1189 ) {
1190 this.connectors.set(
1191 lastConnectorId,
94ec7e96 1192 Utils.cloneObject<ConnectorStatus>(this.stationInfo?.Connectors[lastConnector])
e7aeea18 1193 );
734d790d
JB
1194 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1195 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1196 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
418106c8 1197 }
0a60c33c
JB
1198 }
1199 }
0a60c33c 1200 // Generate all connectors
e7aeea18 1201 if (
94ec7e96 1202 (this.stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
e7aeea18 1203 ) {
7abfea5f 1204 for (let index = 1; index <= maxConnectors; index++) {
e7aeea18
JB
1205 const randConnectorId = this.stationInfo.randomConnectors
1206 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1207 : index;
1208 this.connectors.set(
1209 index,
94ec7e96 1210 Utils.cloneObject<ConnectorStatus>(this.stationInfo?.Connectors[randConnectorId])
e7aeea18 1211 );
734d790d
JB
1212 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1213 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1214 this.getConnectorStatus(index).chargingProfiles = [];
418106c8 1215 }
7abfea5f 1216 }
0a60c33c
JB
1217 }
1218 }
cc6e8ab5 1219 this.stationInfo.maximumAmperage = this.getMaximumAmperage();
01efc60a 1220 this.stationInfo = this.createStationInfoHash(this.stationInfo);
cc6e8ab5 1221 this.saveStationInfo();
7a3a2ebb 1222 // Avoid duplication of connectors related information in RAM
94ec7e96 1223 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
0a60c33c 1224 // Initialize transaction attributes on connectors
734d790d
JB
1225 for (const connectorId of this.connectors.keys()) {
1226 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
a2653482 1227 this.initializeConnectorStatus(connectorId);
0a60c33c
JB
1228 }
1229 }
2484ac1e
JB
1230 // OCPP configuration
1231 this.initializeOcppConfiguration();
0642c3d2
JB
1232 if (this.getEnableStatistics()) {
1233 this.performanceStatistics = PerformanceStatistics.getInstance(
1234 this.hashId,
1235 this.stationInfo.chargingStationId,
1236 this.wsConnectionUrl
1237 );
1238 }
1f5df42a 1239 switch (this.getOcppVersion()) {
c0560973 1240 case OCPPVersion.VERSION_16:
e7aeea18
JB
1241 this.ocppIncomingRequestService =
1242 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
1243 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
1244 this,
1245 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
1246 );
c0560973
JB
1247 break;
1248 default:
1f5df42a 1249 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
1250 break;
1251 }
47e22477
JB
1252 if (this.stationInfo.autoRegister) {
1253 this.bootNotificationResponse = {
1254 currentTime: new Date().toISOString(),
1255 interval: this.getHeartbeatInterval() / 1000,
e7aeea18 1256 status: RegistrationStatus.ACCEPTED,
47e22477
JB
1257 };
1258 }
147d0e0f 1259 this.stationInfo.powerDivider = this.getPowerDivider();
147d0e0f
JB
1260 }
1261
2484ac1e 1262 private initializeOcppConfiguration(): void {
f0f65a62
JB
1263 if (!this.getConfigurationKey(StandardParametersKey.HeartbeatInterval)) {
1264 this.addConfigurationKey(StandardParametersKey.HeartbeatInterval, '0');
1265 }
1266 if (!this.getConfigurationKey(StandardParametersKey.HeartBeatInterval)) {
1267 this.addConfigurationKey(StandardParametersKey.HeartBeatInterval, '0', { visible: false });
1268 }
e7aeea18
JB
1269 if (
1270 this.getSupervisionUrlOcppConfiguration() &&
a59737e3 1271 !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
e7aeea18
JB
1272 ) {
1273 this.addConfigurationKey(
a59737e3 1274 this.getSupervisionUrlOcppKey(),
e7aeea18
JB
1275 this.getConfiguredSupervisionUrl().href,
1276 { reboot: true }
1277 );
e6895390
JB
1278 } else if (
1279 !this.getSupervisionUrlOcppConfiguration() &&
1280 this.getConfigurationKey(this.getSupervisionUrlOcppKey())
1281 ) {
1282 this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
12fc74d6 1283 }
cc6e8ab5
JB
1284 if (
1285 this.stationInfo.amperageLimitationOcppKey &&
1286 !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1287 ) {
1288 this.addConfigurationKey(
1289 this.stationInfo.amperageLimitationOcppKey,
1290 (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString()
1291 );
1292 }
36f6a92e 1293 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
e7aeea18
JB
1294 this.addConfigurationKey(
1295 StandardParametersKey.SupportedFeatureProfiles,
b22787b4 1296 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
e7aeea18
JB
1297 );
1298 }
1299 this.addConfigurationKey(
1300 StandardParametersKey.NumberOfConnectors,
1301 this.getNumberOfConnectors().toString(),
a95873d8
JB
1302 { readonly: true },
1303 { overwrite: true }
e7aeea18 1304 );
c0560973 1305 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
e7aeea18
JB
1306 this.addConfigurationKey(
1307 StandardParametersKey.MeterValuesSampledData,
1308 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1309 );
7abfea5f 1310 }
7e1dc878
JB
1311 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
1312 const connectorPhaseRotation = [];
734d790d 1313 for (const connectorId of this.connectors.keys()) {
7e1dc878 1314 // AC/DC
734d790d
JB
1315 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1316 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1317 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1318 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
e7aeea18 1319 // AC
734d790d
JB
1320 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1321 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1322 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1323 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
7e1dc878
JB
1324 }
1325 }
e7aeea18
JB
1326 this.addConfigurationKey(
1327 StandardParametersKey.ConnectorPhaseRotation,
1328 connectorPhaseRotation.toString()
1329 );
7e1dc878 1330 }
36f6a92e
JB
1331 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
1332 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
1333 }
e7aeea18
JB
1334 if (
1335 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
68cb8b91 1336 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes(
b22787b4 1337 SupportedFeatureProfiles.LocalAuthListManagement
e7aeea18
JB
1338 )
1339 ) {
36f6a92e
JB
1340 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
1341 }
147d0e0f 1342 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
e7aeea18
JB
1343 this.addConfigurationKey(
1344 StandardParametersKey.ConnectionTimeOut,
1345 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1346 );
8bce55bf 1347 }
2484ac1e 1348 this.saveOcppConfiguration();
073bd098
JB
1349 }
1350
7f7b65ca 1351 private getConfigurationFromFile(): ChargingStationConfiguration | null {
073bd098 1352 let configuration: ChargingStationConfiguration = null;
2484ac1e 1353 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
073bd098 1354 try {
42a3eee7 1355 const measureId = `${FileType.ChargingStationConfiguration} read`;
0642c3d2 1356 const beginId = PerformanceStatistics.beginMeasure(measureId);
073bd098 1357 configuration = JSON.parse(
a95873d8 1358 fs.readFileSync(this.configurationFile, 'utf8')
073bd098 1359 ) as ChargingStationConfiguration;
42a3eee7 1360 PerformanceStatistics.endMeasure(measureId, beginId);
073bd098
JB
1361 } catch (error) {
1362 FileUtils.handleFileException(
1363 this.logPrefix(),
a95873d8 1364 FileType.ChargingStationConfiguration,
073bd098
JB
1365 this.configurationFile,
1366 error as NodeJS.ErrnoException
1367 );
1368 }
1369 }
1370 return configuration;
1371 }
1372
2484ac1e
JB
1373 private saveConfiguration(section?: Section): void {
1374 if (this.configurationFile) {
1375 try {
1376 const configurationData: ChargingStationConfiguration =
1377 this.getConfigurationFromFile() ?? {};
1378 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1379 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
073bd098 1380 }
2484ac1e
JB
1381 switch (section) {
1382 case Section.ocppConfiguration:
1383 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
1384 break;
1385 case Section.stationInfo:
01efc60a
JB
1386 if (configurationData?.stationInfo?.infoHash === this.stationInfo?.infoHash) {
1387 logger.debug(
1388 `${this.logPrefix()} Not saving unchanged charging station info to configuration file ${
1389 this.configurationFile
1390 }`
1391 );
1392 return;
1393 }
2484ac1e
JB
1394 configurationData.stationInfo = this.stationInfo;
1395 break;
1396 default:
1397 configurationData.configurationKey = this.ocppConfiguration.configurationKey;
01efc60a
JB
1398 if (configurationData?.stationInfo?.infoHash !== this.stationInfo?.infoHash) {
1399 configurationData.stationInfo = this.stationInfo;
1400 }
2484ac1e
JB
1401 break;
1402 }
42a3eee7
JB
1403 const measureId = `${FileType.ChargingStationConfiguration} write`;
1404 const beginId = PerformanceStatistics.beginMeasure(measureId);
2484ac1e
JB
1405 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1406 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1407 fs.closeSync(fileDescriptor);
42a3eee7 1408 PerformanceStatistics.endMeasure(measureId, beginId);
2484ac1e
JB
1409 } catch (error) {
1410 FileUtils.handleFileException(
1411 this.logPrefix(),
1412 FileType.ChargingStationConfiguration,
1413 this.configurationFile,
1414 error as NodeJS.ErrnoException
073bd098
JB
1415 );
1416 }
2484ac1e
JB
1417 } else {
1418 logger.error(
01efc60a 1419 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
2484ac1e 1420 );
073bd098
JB
1421 }
1422 }
1423
2484ac1e
JB
1424 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration {
1425 return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration);
1426 }
1427
1428 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1429 let configuration: ChargingStationConfiguration = null;
1430 if (this.getOcppPersistentConfiguration()) {
7a3a2ebb
JB
1431 const configurationFromFile = this.getConfigurationFromFile();
1432 configuration = configurationFromFile?.configurationKey && configurationFromFile;
073bd098 1433 }
2484ac1e 1434 configuration && delete configuration.stationInfo;
073bd098 1435 return configuration;
7dde0b73
JB
1436 }
1437
2484ac1e
JB
1438 private getOcppConfiguration(): ChargingStationOcppConfiguration {
1439 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1440 if (!ocppConfiguration) {
1441 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1442 }
1443 return ocppConfiguration;
1444 }
1445
1446 private saveOcppConfiguration(): void {
1447 if (this.getOcppPersistentConfiguration()) {
1448 this.saveConfiguration(Section.ocppConfiguration);
1449 }
1450 }
1451
c0560973 1452 private async onOpen(): Promise<void> {
5144f4d1
JB
1453 if (this.isWebSocketConnectionOpened()) {
1454 logger.info(
1455 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1456 );
94bb24d5 1457 if (!this.isRegistered()) {
5144f4d1
JB
1458 // Send BootNotification
1459 let registrationRetryCount = 0;
1460 do {
f7f98c68 1461 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
5144f4d1
JB
1462 BootNotificationRequest,
1463 BootNotificationResponse
1464 >(
f22266fd
JB
1465 RequestCommand.BOOT_NOTIFICATION,
1466 {
1467 chargePointModel: this.bootNotificationRequest.chargePointModel,
1468 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1469 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1470 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1471 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1472 iccid: this.bootNotificationRequest.iccid,
1473 imsi: this.bootNotificationRequest.imsi,
1474 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1475 meterType: this.bootNotificationRequest.meterType,
1476 },
1477 { skipBufferingOnError: true }
1478 );
94bb24d5 1479 if (!this.isRegistered()) {
5144f4d1
JB
1480 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1481 await Utils.sleep(
1482 this.bootNotificationResponse?.interval
1483 ? this.bootNotificationResponse.interval * 1000
1484 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1485 );
1486 }
1487 } while (
94bb24d5 1488 !this.isRegistered() &&
5144f4d1
JB
1489 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1490 this.getRegistrationMaxRetries() === -1)
1491 );
1492 }
94bb24d5
JB
1493 if (this.isRegistered()) {
1494 if (this.isInAcceptedState()) {
1495 await this.startMessageSequence();
1496 this.wsConnectionRestarted && this.flushMessageBuffer();
c0560973 1497 }
5144f4d1
JB
1498 } else {
1499 logger.error(
1500 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1501 );
caad9d6b 1502 }
94bb24d5 1503 this.stopped && (this.stopped = false);
5144f4d1
JB
1504 this.autoReconnectRetryCount = 0;
1505 this.wsConnectionRestarted = false;
2e6f5966 1506 } else {
5144f4d1
JB
1507 logger.warn(
1508 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
e7aeea18 1509 );
2e6f5966 1510 }
2e6f5966
JB
1511 }
1512
6c65a295 1513 private async onClose(code: number, reason: string): Promise<void> {
d09085e9 1514 switch (code) {
6c65a295
JB
1515 // Normal close
1516 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1517 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18
JB
1518 logger.info(
1519 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1520 code
1521 )}' and reason '${reason}'`
1522 );
c0560973
JB
1523 this.autoReconnectRetryCount = 0;
1524 break;
6c65a295
JB
1525 // Abnormal close
1526 default:
e7aeea18
JB
1527 logger.error(
1528 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1529 code
1530 )}' and reason '${reason}'`
1531 );
d09085e9 1532 await this.reconnect(code);
c0560973
JB
1533 break;
1534 }
2e6f5966
JB
1535 }
1536
16b0d4e7 1537 private async onMessage(data: Data): Promise<void> {
b3ec7bc1
JB
1538 let messageType: number;
1539 let messageId: string;
1540 let commandName: IncomingRequestCommand;
1541 let commandPayload: JsonType;
1542 let errorType: ErrorType;
1543 let errorMessage: string;
1544 let errorDetails: JsonType;
1545 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
9239b49a 1546 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
32b02249 1547 let requestCommandName: RequestCommand | IncomingRequestCommand;
b3ec7bc1 1548 let requestPayload: JsonType;
32b02249 1549 let cachedRequest: CachedRequest;
c0560973
JB
1550 let errMsg: string;
1551 try {
b3ec7bc1 1552 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
47e22477 1553 if (Utils.isIterable(request)) {
9934652c 1554 [messageType, messageId] = request;
b3ec7bc1
JB
1555 // Check the type of message
1556 switch (messageType) {
1557 // Incoming Message
1558 case MessageType.CALL_MESSAGE:
9934652c 1559 [, , commandName, commandPayload] = request as IncomingRequest;
b3ec7bc1
JB
1560 if (this.getEnableStatistics()) {
1561 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1562 }
1563 logger.debug(
1564 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1565 request
1566 )}`
1567 );
1568 // Process the message
1569 await this.ocppIncomingRequestService.incomingRequestHandler(
1570 messageId,
1571 commandName,
1572 commandPayload
1573 );
1574 break;
1575 // Outcome Message
1576 case MessageType.CALL_RESULT_MESSAGE:
9934652c 1577 [, , commandPayload] = request as Response;
b3ec7bc1
JB
1578 // Respond
1579 cachedRequest = this.requests.get(messageId);
1580 if (Utils.isIterable(cachedRequest)) {
1581 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1582 } else {
1583 throw new OCPPError(
1584 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1585 `Cached request for message id ${messageId} response is not iterable`,
1586 null,
1587 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1588 );
1589 }
1590 logger.debug(
7ec6c5c9
JB
1591 `${this.logPrefix()} << Command '${
1592 requestCommandName ?? ''
1593 }' received response payload: ${JSON.stringify(request)}`
b3ec7bc1
JB
1594 );
1595 if (!responseCallback) {
1596 // Error
1597 throw new OCPPError(
1598 ErrorType.INTERNAL_ERROR,
c2bc716f
JB
1599 `Response for unknown message id ${messageId}`,
1600 null,
1601 commandPayload
b3ec7bc1
JB
1602 );
1603 }
1604 responseCallback(commandPayload, requestPayload);
1605 break;
1606 // Error Message
1607 case MessageType.CALL_ERROR_MESSAGE:
9934652c 1608 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
b3ec7bc1
JB
1609 cachedRequest = this.requests.get(messageId);
1610 if (Utils.isIterable(cachedRequest)) {
1611 [, rejectCallback, requestCommandName] = cachedRequest;
1612 } else {
1613 throw new OCPPError(
1614 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1615 `Cached request for message id ${messageId} error response is not iterable`,
1616 null,
1617 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1618 );
1619 }
1620 logger.debug(
7ec6c5c9
JB
1621 `${this.logPrefix()} << Command '${
1622 requestCommandName ?? ''
1623 }' received error payload: ${JSON.stringify(request)}`
b3ec7bc1
JB
1624 );
1625 if (!rejectCallback) {
1626 // Error
1627 throw new OCPPError(
1628 ErrorType.INTERNAL_ERROR,
c2bc716f
JB
1629 `Error response for unknown message id ${messageId}`,
1630 null,
1631 { errorType, errorMessage, errorDetails }
b3ec7bc1
JB
1632 );
1633 }
1634 rejectCallback(
1635 new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)
1636 );
1637 break;
1638 // Error
1639 default:
1640 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1641 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1642 logger.error(errMsg);
1643 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1644 }
47e22477 1645 } else {
ac54a9bb
JB
1646 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, {
1647 payload: request,
1648 });
47e22477 1649 }
c0560973
JB
1650 } catch (error) {
1651 // Log
e7aeea18
JB
1652 logger.error(
1653 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1654 this.logPrefix(),
1655 data.toString(),
1656 this.requests.get(messageId),
1657 error
1658 );
c0560973 1659 // Send error
e7aeea18 1660 messageType === MessageType.CALL_MESSAGE &&
b3ec7bc1
JB
1661 (await this.ocppRequestService.sendError(
1662 messageId,
1663 error as OCPPError,
ac54a9bb 1664 Utils.isString(commandName) ? commandName : requestCommandName ?? null
b3ec7bc1 1665 ));
c0560973 1666 }
2328be1e
JB
1667 }
1668
c0560973 1669 private onPing(): void {
9f2e3130 1670 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
c0560973
JB
1671 }
1672
1673 private onPong(): void {
9f2e3130 1674 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
c0560973
JB
1675 }
1676
9534e74e 1677 private onError(error: WSError): void {
9f2e3130 1678 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
c0560973
JB
1679 }
1680
6e0964c8 1681 private getAuthorizationFile(): string | undefined {
e7aeea18
JB
1682 return (
1683 this.stationInfo.authorizationFile &&
1684 path.join(
1685 path.resolve(__dirname, '../'),
1686 'assets',
1687 path.basename(this.stationInfo.authorizationFile)
1688 )
1689 );
c0560973
JB
1690 }
1691
1692 private getAuthorizedTags(): string[] {
1693 let authorizedTags: string[] = [];
1694 const authorizationFile = this.getAuthorizationFile();
1695 if (authorizationFile) {
1696 try {
1697 // Load authorization file
a95873d8 1698 authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
c0560973 1699 } catch (error) {
e7aeea18
JB
1700 FileUtils.handleFileException(
1701 this.logPrefix(),
a95873d8 1702 FileType.Authorization,
e7aeea18
JB
1703 authorizationFile,
1704 error as NodeJS.ErrnoException
1705 );
c0560973
JB
1706 }
1707 } else {
e7aeea18 1708 logger.info(
2484ac1e 1709 this.logPrefix() + ' No authorization file given in template file ' + this.templateFile
e7aeea18 1710 );
8c4da341 1711 }
c0560973
JB
1712 return authorizedTags;
1713 }
1714
6e0964c8 1715 private getUseConnectorId0(): boolean | undefined {
e7aeea18
JB
1716 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1717 ? this.stationInfo.useConnectorId0
1718 : true;
8bce55bf
JB
1719 }
1720
c0560973 1721 private getNumberOfRunningTransactions(): number {
6ecb15e4 1722 let trxCount = 0;
734d790d
JB
1723 for (const connectorId of this.connectors.keys()) {
1724 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
6ecb15e4
JB
1725 trxCount++;
1726 }
1727 }
1728 return trxCount;
1729 }
1730
1f761b9a 1731 // 0 for disabling
6e0964c8 1732 private getConnectionTimeout(): number | undefined {
291cb255 1733 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
e7aeea18
JB
1734 return (
1735 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1736 Constants.DEFAULT_CONNECTION_TIMEOUT
1737 );
291cb255 1738 }
291cb255 1739 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
1740 }
1741
1f761b9a 1742 // -1 for unlimited, 0 for disabling
6e0964c8 1743 private getAutoReconnectMaxRetries(): number | undefined {
ad2f27c3
JB
1744 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1745 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
1746 }
1747 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1748 return Configuration.getAutoReconnectMaxRetries();
1749 }
1750 return -1;
1751 }
1752
ec977daf 1753 // 0 for disabling
6e0964c8 1754 private getRegistrationMaxRetries(): number | undefined {
ad2f27c3
JB
1755 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1756 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
1757 }
1758 return -1;
1759 }
1760
c0560973
JB
1761 private getPowerDivider(): number {
1762 let powerDivider = this.getNumberOfConnectors();
ad2f27c3 1763 if (this.stationInfo.powerSharedByConnectors) {
c0560973 1764 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
1765 }
1766 return powerDivider;
1767 }
1768
c0560973 1769 private getTemplateMaxNumberOfConnectors(): number {
94ec7e96
JB
1770 if (!this.stationInfo?.Connectors) {
1771 return -1;
1772 }
1773 return Object.keys(this.stationInfo?.Connectors).length;
7abfea5f
JB
1774 }
1775
c0560973 1776 private getMaxNumberOfConnectors(): number {
e58068fd 1777 let maxConnectors: number;
ad2f27c3
JB
1778 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1779 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
6ecb15e4 1780 // Distribute evenly the number of connectors
ad2f27c3
JB
1781 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1782 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1783 maxConnectors = this.stationInfo.numberOfConnectors as number;
488fd3a7 1784 } else {
94ec7e96 1785 maxConnectors = this.stationInfo?.Connectors[0]
e7aeea18
JB
1786 ? this.getTemplateMaxNumberOfConnectors() - 1
1787 : this.getTemplateMaxNumberOfConnectors();
5ad8570f
JB
1788 }
1789 return maxConnectors;
2e6f5966
JB
1790 }
1791
0642c3d2
JB
1792 private getMaximumPower(): number {
1793 return (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower;
1794 }
1795
cc6e8ab5 1796 private getMaximumAmperage(): number | undefined {
0642c3d2 1797 const maximumPower = this.getMaximumPower();
cc6e8ab5
JB
1798 switch (this.getCurrentOutType()) {
1799 case CurrentType.AC:
1800 return ACElectricUtils.amperagePerPhaseFromPower(
1801 this.getNumberOfPhases(),
ad8537a7 1802 maximumPower / this.getNumberOfConnectors(),
cc6e8ab5
JB
1803 this.getVoltageOut()
1804 );
1805 case CurrentType.DC:
ad8537a7 1806 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut());
cc6e8ab5
JB
1807 }
1808 }
1809
1810 private getAmperageLimitationUnitDivider(): number {
1811 let unitDivider = 1;
1812 switch (this.stationInfo.amperageLimitationUnit) {
1813 case AmpereUnits.DECI_AMPERE:
1814 unitDivider = 10;
1815 break;
1816 case AmpereUnits.CENTI_AMPERE:
1817 unitDivider = 100;
1818 break;
1819 case AmpereUnits.MILLI_AMPERE:
1820 unitDivider = 1000;
1821 break;
1822 }
1823 return unitDivider;
1824 }
1825
1826 private getAmperageLimitation(): number | undefined {
1827 if (
1828 this.stationInfo.amperageLimitationOcppKey &&
1829 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey)
1830 ) {
1831 return (
1832 Utils.convertToInt(
1833 this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value
1834 ) / this.getAmperageLimitationUnitDivider()
1835 );
1836 }
1837 }
1838
c0560973 1839 private async startMessageSequence(): Promise<void> {
6114e6f1 1840 if (this.stationInfo.autoRegister) {
f7f98c68 1841 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1842 BootNotificationRequest,
1843 BootNotificationResponse
1844 >(
6a8b180d
JB
1845 RequestCommand.BOOT_NOTIFICATION,
1846 {
1847 chargePointModel: this.bootNotificationRequest.chargePointModel,
1848 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1849 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1850 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
29d1e2e7
JB
1851 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1852 iccid: this.bootNotificationRequest.iccid,
1853 imsi: this.bootNotificationRequest.imsi,
1854 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1855 meterType: this.bootNotificationRequest.meterType,
6a8b180d
JB
1856 },
1857 { skipBufferingOnError: true }
e7aeea18 1858 );
6114e6f1 1859 }
136c90ba 1860 // Start WebSocket ping
c0560973 1861 this.startWebSocketPing();
5ad8570f 1862 // Start heartbeat
c0560973 1863 this.startHeartbeat();
0a60c33c 1864 // Initialize connectors status
734d790d
JB
1865 for (const connectorId of this.connectors.keys()) {
1866 if (connectorId === 0) {
593cf3f9 1867 continue;
e7aeea18
JB
1868 } else if (
1869 !this.stopped &&
1870 !this.getConnectorStatus(connectorId)?.status &&
1871 this.getConnectorStatus(connectorId)?.bootStatus
1872 ) {
136c90ba 1873 // Send status in template at startup
f7f98c68 1874 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1875 StatusNotificationRequest,
1876 StatusNotificationResponse
1877 >(RequestCommand.STATUS_NOTIFICATION, {
1878 connectorId,
1879 status: this.getConnectorStatus(connectorId).bootStatus,
1880 errorCode: ChargePointErrorCode.NO_ERROR,
1881 });
e7aeea18
JB
1882 this.getConnectorStatus(connectorId).status =
1883 this.getConnectorStatus(connectorId).bootStatus;
1884 } else if (
1885 this.stopped &&
1886 this.getConnectorStatus(connectorId)?.status &&
1887 this.getConnectorStatus(connectorId)?.bootStatus
1888 ) {
136c90ba 1889 // Send status in template after reset
f7f98c68 1890 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1891 StatusNotificationRequest,
1892 StatusNotificationResponse
1893 >(RequestCommand.STATUS_NOTIFICATION, {
1894 connectorId,
1895 status: this.getConnectorStatus(connectorId).bootStatus,
1896 errorCode: ChargePointErrorCode.NO_ERROR,
1897 });
e7aeea18
JB
1898 this.getConnectorStatus(connectorId).status =
1899 this.getConnectorStatus(connectorId).bootStatus;
734d790d 1900 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
136c90ba 1901 // Send previous status at template reload
f7f98c68 1902 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1903 StatusNotificationRequest,
1904 StatusNotificationResponse
1905 >(RequestCommand.STATUS_NOTIFICATION, {
1906 connectorId,
1907 status: this.getConnectorStatus(connectorId).status,
1908 errorCode: ChargePointErrorCode.NO_ERROR,
1909 });
5ad8570f 1910 } else {
136c90ba 1911 // Send default status
f7f98c68 1912 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1913 StatusNotificationRequest,
1914 StatusNotificationResponse
1915 >(RequestCommand.STATUS_NOTIFICATION, {
1916 connectorId,
1917 status: ChargePointStatus.AVAILABLE,
1918 errorCode: ChargePointErrorCode.NO_ERROR,
1919 });
734d790d 1920 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
1921 }
1922 }
0a60c33c 1923 // Start the ATG
dd119a6b 1924 this.startAutomaticTransactionGenerator();
dd119a6b
JB
1925 }
1926
1927 private startAutomaticTransactionGenerator() {
ad2f27c3 1928 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
265e4266 1929 if (!this.automaticTransactionGenerator) {
73b9adec 1930 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
5ad8570f 1931 }
265e4266
JB
1932 if (!this.automaticTransactionGenerator.started) {
1933 this.automaticTransactionGenerator.start();
5ad8570f
JB
1934 }
1935 }
5ad8570f
JB
1936 }
1937
e7aeea18
JB
1938 private async stopMessageSequence(
1939 reason: StopTransactionReason = StopTransactionReason.NONE
1940 ): Promise<void> {
136c90ba 1941 // Stop WebSocket ping
c0560973 1942 this.stopWebSocketPing();
79411696 1943 // Stop heartbeat
c0560973 1944 this.stopHeartbeat();
79411696 1945 // Stop the ATG
e7aeea18
JB
1946 if (
1947 this.stationInfo.AutomaticTransactionGenerator.enable &&
1948 this.automaticTransactionGenerator?.started
1949 ) {
0045cef5 1950 this.automaticTransactionGenerator.stop();
79411696 1951 } else {
734d790d
JB
1952 for (const connectorId of this.connectors.keys()) {
1953 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1954 const transactionId = this.getConnectorStatus(connectorId).transactionId;
68c993d5
JB
1955 if (
1956 this.getBeginEndMeterValues() &&
1957 this.getOcppStrictCompliance() &&
1958 !this.getOutOfOrderEndMeterValues()
1959 ) {
1960 // FIXME: Implement OCPP version agnostic helpers
1961 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1962 this,
1963 connectorId,
1964 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1965 );
f7f98c68
JB
1966 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
1967 RequestCommand.METER_VALUES,
1968 {
1969 connectorId,
1970 transactionId,
1971 meterValue: transactionEndMeterValue,
1972 }
1973 );
ef6fa3fb 1974 }
f7f98c68 1975 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1976 StopTransactionRequest,
1977 StopTransactionResponse
1978 >(RequestCommand.STOP_TRANSACTION, {
1979 transactionId,
1980 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1981 idTag: this.getTransactionIdTag(transactionId),
1982 reason,
1983 });
79411696
JB
1984 }
1985 }
1986 }
1987 }
1988
c0560973 1989 private startWebSocketPing(): void {
e7aeea18
JB
1990 const webSocketPingInterval: number = this.getConfigurationKey(
1991 StandardParametersKey.WebSocketPingInterval
1992 )
1993 ? Utils.convertToInt(
1994 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1995 )
9cd3dfb0 1996 : 0;
ad2f27c3
JB
1997 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1998 this.webSocketPingSetInterval = setInterval(() => {
d5bff457 1999 if (this.isWebSocketConnectionOpened()) {
e7aeea18
JB
2000 this.wsConnection.ping((): void => {
2001 /* This is intentional */
2002 });
136c90ba
JB
2003 }
2004 }, webSocketPingInterval * 1000);
e7aeea18
JB
2005 logger.info(
2006 this.logPrefix() +
2007 ' WebSocket ping started every ' +
2008 Utils.formatDurationSeconds(webSocketPingInterval)
2009 );
ad2f27c3 2010 } else if (this.webSocketPingSetInterval) {
e7aeea18
JB
2011 logger.info(
2012 this.logPrefix() +
2013 ' WebSocket ping every ' +
2014 Utils.formatDurationSeconds(webSocketPingInterval) +
2015 ' already started'
2016 );
136c90ba 2017 } else {
e7aeea18
JB
2018 logger.error(
2019 `${this.logPrefix()} WebSocket ping interval set to ${
2020 webSocketPingInterval
2021 ? Utils.formatDurationSeconds(webSocketPingInterval)
2022 : webSocketPingInterval
2023 }, not starting the WebSocket ping`
2024 );
136c90ba
JB
2025 }
2026 }
2027
c0560973 2028 private stopWebSocketPing(): void {
ad2f27c3
JB
2029 if (this.webSocketPingSetInterval) {
2030 clearInterval(this.webSocketPingSetInterval);
136c90ba
JB
2031 }
2032 }
2033
e7aeea18
JB
2034 private warnDeprecatedTemplateKey(
2035 template: ChargingStationTemplate,
2036 key: string,
2037 chargingStationId: string,
2038 logMsgToAppend = ''
2039 ): void {
2dcfe98e 2040 if (!Utils.isUndefined(template[key])) {
e7aeea18
JB
2041 const logPrefixStr = ` ${chargingStationId} |`;
2042 logger.warn(
2043 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
2484ac1e 2044 this.templateFile
e7aeea18
JB
2045 }'${logMsgToAppend && '. ' + logMsgToAppend}`
2046 );
2dcfe98e
JB
2047 }
2048 }
2049
e7aeea18
JB
2050 private convertDeprecatedTemplateKey(
2051 template: ChargingStationTemplate,
2052 deprecatedKey: string,
2053 key: string
2054 ): void {
2dcfe98e 2055 if (!Utils.isUndefined(template[deprecatedKey])) {
c0f4be74 2056 template[key] = template[deprecatedKey] as unknown;
2dcfe98e
JB
2057 delete template[deprecatedKey];
2058 }
2059 }
2060
1f5df42a 2061 private getConfiguredSupervisionUrl(): URL {
e7aeea18
JB
2062 const supervisionUrls = Utils.cloneObject<string | string[]>(
2063 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
2064 );
c0560973 2065 if (!Utils.isEmptyArray(supervisionUrls)) {
2dcfe98e
JB
2066 let urlIndex = 0;
2067 switch (Configuration.getSupervisionUrlDistribution()) {
2068 case SupervisionUrlDistribution.ROUND_ROBIN:
2069 urlIndex = (this.index - 1) % supervisionUrls.length;
2070 break;
2071 case SupervisionUrlDistribution.RANDOM:
2072 // Get a random url
2073 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
2074 break;
2075 case SupervisionUrlDistribution.SEQUENTIAL:
2076 if (this.index <= supervisionUrls.length) {
2077 urlIndex = this.index - 1;
2078 } else {
e7aeea18
JB
2079 logger.warn(
2080 `${this.logPrefix()} No more configured supervision urls available, using the first one`
2081 );
2dcfe98e
JB
2082 }
2083 break;
2084 default:
e7aeea18
JB
2085 logger.error(
2086 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
2087 SupervisionUrlDistribution.ROUND_ROBIN
2088 }`
2089 );
2dcfe98e
JB
2090 urlIndex = (this.index - 1) % supervisionUrls.length;
2091 break;
c0560973 2092 }
2dcfe98e 2093 return new URL(supervisionUrls[urlIndex]);
c0560973 2094 }
57939a9d 2095 return new URL(supervisionUrls as string);
136c90ba
JB
2096 }
2097
6e0964c8 2098 private getHeartbeatInterval(): number | undefined {
c0560973
JB
2099 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
2100 if (HeartbeatInterval) {
2101 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
2102 }
2103 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
2104 if (HeartBeatInterval) {
2105 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c 2106 }
e7aeea18
JB
2107 !this.stationInfo.autoRegister &&
2108 logger.warn(
2109 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
2110 Constants.DEFAULT_HEARTBEAT_INTERVAL
2111 }`
2112 );
47e22477 2113 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
0a60c33c
JB
2114 }
2115
c0560973 2116 private stopHeartbeat(): void {
ad2f27c3
JB
2117 if (this.heartbeatSetInterval) {
2118 clearInterval(this.heartbeatSetInterval);
7dde0b73 2119 }
5ad8570f
JB
2120 }
2121
e7aeea18 2122 private openWSConnection(
2484ac1e 2123 options: WsOptions = this.stationInfo.wsOptions,
e7aeea18
JB
2124 forceCloseOpened = false
2125 ): void {
37486900 2126 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
e7aeea18
JB
2127 if (
2128 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
2129 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
2130 ) {
15042c5f
JB
2131 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
2132 }
d5bff457 2133 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
c0560973
JB
2134 this.wsConnection.close();
2135 }
88184022 2136 let protocol: string;
1f5df42a 2137 switch (this.getOcppVersion()) {
c0560973
JB
2138 case OCPPVersion.VERSION_16:
2139 protocol = 'ocpp' + OCPPVersion.VERSION_16;
2140 break;
2141 default:
1f5df42a 2142 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
2143 break;
2144 }
2145 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
e7aeea18
JB
2146 logger.info(
2147 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
2148 );
136c90ba
JB
2149 }
2150
dd119a6b 2151 private stopMeterValues(connectorId: number) {
734d790d
JB
2152 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
2153 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
dd119a6b
JB
2154 }
2155 }
2156
6e0964c8 2157 private getReconnectExponentialDelay(): boolean | undefined {
e7aeea18
JB
2158 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
2159 ? this.stationInfo.reconnectExponentialDelay
2160 : false;
5ad8570f
JB
2161 }
2162
d09085e9 2163 private async reconnect(code: number): Promise<void> {
7874b0b1
JB
2164 // Stop WebSocket ping
2165 this.stopWebSocketPing();
136c90ba 2166 // Stop heartbeat
c0560973 2167 this.stopHeartbeat();
5ad8570f 2168 // Stop the ATG if needed
e7aeea18
JB
2169 if (
2170 this.stationInfo.AutomaticTransactionGenerator.enable &&
ad2f27c3 2171 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
e7aeea18
JB
2172 this.automaticTransactionGenerator?.started
2173 ) {
0045cef5 2174 this.automaticTransactionGenerator.stop();
ad2f27c3 2175 }
e7aeea18
JB
2176 if (
2177 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
2178 this.getAutoReconnectMaxRetries() === -1
2179 ) {
ad2f27c3 2180 this.autoReconnectRetryCount++;
e7aeea18
JB
2181 const reconnectDelay = this.getReconnectExponentialDelay()
2182 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
2183 : this.getConnectionTimeout() * 1000;
2184 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
2185 logger.error(
2186 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2187 reconnectDelay,
2188 2
2189 )}ms, timeout ${reconnectTimeout}ms`
2190 );
032d6efc 2191 await Utils.sleep(reconnectDelay);
e7aeea18
JB
2192 logger.error(
2193 this.logPrefix() +
2194 ' WebSocket: reconnecting try #' +
2195 this.autoReconnectRetryCount.toString()
2196 );
2197 this.openWSConnection(
2198 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
2199 true
2200 );
265e4266 2201 this.wsConnectionRestarted = true;
c0560973 2202 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18 2203 logger.error(
71a77ac2 2204 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
e7aeea18
JB
2205 this.autoReconnectRetryCount
2206 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2207 );
5ad8570f
JB
2208 }
2209 }
2210
a2653482
JB
2211 private initializeConnectorStatus(connectorId: number): void {
2212 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
2213 this.getConnectorStatus(connectorId).idTagAuthorized = false;
2214 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d
JB
2215 this.getConnectorStatus(connectorId).transactionStarted = false;
2216 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
2217 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
0a60c33c 2218 }
7dde0b73 2219}