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