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