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