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