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