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