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