1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public readonly templateFile
: string;
88 public stationInfo
!: ChargingStationInfo
;
89 public started
: boolean;
90 public authorizedTagsCache
: AuthorizedTagsCache
;
91 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly connectors
: Map
<number, ConnectorStatus
>;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationRequest
!: BootNotificationRequest
;
100 public bootNotificationResponse
!: BootNotificationResponse
| null;
101 public powerDivider
!: number;
102 private starting
: boolean;
103 private stopping
: boolean;
104 private readonly index
: number;
105 private configurationFile
!: string;
106 private configurationFileHash
!: string;
107 private connectorsConfigurationHash
!: string;
108 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
109 private readonly messageBuffer
: Set
<string>;
110 private configuredSupervisionUrl
!: URL
;
111 private wsConnectionRestarted
: boolean;
112 private autoReconnectRetryCount
: number;
113 private templateFileWatcher
!: fs
.FSWatcher
;
114 private readonly sharedLRUCache
: SharedLRUCache
;
115 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
116 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
118 constructor(index
: number, templateFile
: string) {
119 this.started
= false;
120 this.starting
= false;
121 this.stopping
= false;
122 this.wsConnectionRestarted
= false;
123 this.autoReconnectRetryCount
= 0;
125 this.templateFile
= templateFile
;
126 this.connectors
= new Map
<number, ConnectorStatus
>();
127 this.requests
= new Map
<string, CachedRequest
>();
128 this.messageBuffer
= new Set
<string>();
129 this.sharedLRUCache
= SharedLRUCache
.getInstance();
130 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
131 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
136 private get
wsConnectionUrl(): URL
{
138 (this.getSupervisionUrlOcppConfiguration()
139 ? ChargingStationConfigurationUtils
.getConfigurationKey(
141 this.getSupervisionUrlOcppKey()
143 : this.configuredSupervisionUrl
.href
) +
145 this.stationInfo
.chargingStationId
149 public logPrefix(): string {
150 return Utils
.logPrefix(
152 this?.stationInfo?.chargingStationId ??
153 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
158 public getRandomIdTag(): string {
159 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
160 const index
= Math.floor(
161 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
163 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
166 public hasAuthorizedTags(): boolean {
167 return !Utils
.isEmptyArray(
168 this.authorizedTagsCache
.getAuthorizedTags(
169 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
174 public getEnableStatistics(): boolean | undefined {
175 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
176 ? this.stationInfo
.enableStatistics
180 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
181 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
184 public getPayloadSchemaValidation(): boolean | undefined {
185 return this.stationInfo
.payloadSchemaValidation
?? true;
188 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
189 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
190 switch (this.getCurrentOutType(stationInfo
)) {
192 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
193 ? localStationInfo
.numberOfPhases
200 public isWebSocketConnectionOpened(): boolean {
201 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
204 public getRegistrationStatus(): RegistrationStatus
{
205 return this?.bootNotificationResponse
?.status;
208 public isInUnknownState(): boolean {
209 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
212 public isInPendingState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
216 public isInAcceptedState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
220 public isInRejectedState(): boolean {
221 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
224 public isRegistered(): boolean {
225 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
228 public isChargingStationAvailable(): boolean {
229 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
232 public isConnectorAvailable(id
: number): boolean {
233 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
236 public getNumberOfConnectors(): number {
237 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
240 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
241 return this.connectors
.get(id
);
244 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
245 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
248 public getOcppStrictCompliance(): boolean {
249 return this.stationInfo
?.ocppStrictCompliance
?? false;
252 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
253 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
254 this.getCurrentOutType(stationInfo
),
258 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
259 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
260 ? localStationInfo
.voltageOut
264 public getConnectorMaximumAvailablePower(connectorId
: number): number {
265 let connectorAmperageLimitationPowerLimit
: number;
267 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
268 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
270 connectorAmperageLimitationPowerLimit
=
271 (this.getCurrentOutType() === CurrentType
.AC
272 ? ACElectricUtils
.powerTotal(
273 this.getNumberOfPhases(),
274 this.getVoltageOut(),
275 this.getAmperageLimitation() * this.getNumberOfConnectors()
277 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
280 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
281 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
283 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
284 isNaN(connectorAmperageLimitationPowerLimit
)
286 : connectorAmperageLimitationPowerLimit
,
287 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
291 public getTransactionIdTag(transactionId
: number): string | undefined {
292 for (const connectorId
of this.connectors
.keys()) {
293 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
294 return this.getConnectorStatus(connectorId
).transactionIdTag
;
299 public getOutOfOrderEndMeterValues(): boolean {
300 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
303 public getBeginEndMeterValues(): boolean {
304 return this.stationInfo
?.beginEndMeterValues
?? false;
307 public getMeteringPerTransaction(): boolean {
308 return this.stationInfo
?.meteringPerTransaction
?? true;
311 public getTransactionDataMeterValues(): boolean {
312 return this.stationInfo
?.transactionDataMeterValues
?? false;
315 public getMainVoltageMeterValues(): boolean {
316 return this.stationInfo
?.mainVoltageMeterValues
?? true;
319 public getPhaseLineToLineVoltageMeterValues(): boolean {
320 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
323 public getCustomValueLimitationMeterValues(): boolean {
324 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
327 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
328 for (const connectorId
of this.connectors
.keys()) {
331 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
338 public getEnergyActiveImportRegisterByTransactionId(
339 transactionId
: number,
342 return this.getEnergyActiveImportRegister(
343 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
348 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
349 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
352 public getAuthorizeRemoteTxRequests(): boolean {
353 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
355 StandardParametersKey
.AuthorizeRemoteTxRequests
357 return authorizeRemoteTxRequests
358 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
362 public getLocalAuthListEnabled(): boolean {
363 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
365 StandardParametersKey
.LocalAuthListEnabled
367 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
370 public startHeartbeat(): void {
372 this.getHeartbeatInterval() &&
373 this.getHeartbeatInterval() > 0 &&
374 !this.heartbeatSetInterval
376 // eslint-disable-next-line @typescript-eslint/no-misused-promises
377 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
378 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
380 RequestCommand
.HEARTBEAT
382 }, this.getHeartbeatInterval());
385 ' Heartbeat started every ' +
386 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
388 } else if (this.heartbeatSetInterval
) {
391 ' Heartbeat already started every ' +
392 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
396 `${this.logPrefix()} Heartbeat interval set to ${
397 this.getHeartbeatInterval()
398 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
399 : this.getHeartbeatInterval()
400 }, not starting the heartbeat`
405 public restartHeartbeat(): void {
407 this.stopHeartbeat();
409 this.startHeartbeat();
412 public restartWebSocketPing(): void {
413 // Stop WebSocket ping
414 this.stopWebSocketPing();
415 // Start WebSocket ping
416 this.startWebSocketPing();
419 public startMeterValues(connectorId
: number, interval
: number): void {
420 if (connectorId
=== 0) {
422 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
426 if (!this.getConnectorStatus(connectorId
)) {
428 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
432 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
434 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
438 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
439 !this.getConnectorStatus(connectorId
)?.transactionId
442 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
447 // eslint-disable-next-line @typescript-eslint/no-misused-promises
448 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
449 // eslint-disable-next-line @typescript-eslint/no-misused-promises
450 async (): Promise
<void> => {
451 // FIXME: Implement OCPP version agnostic helpers
452 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
455 this.getConnectorStatus(connectorId
).transactionId
,
458 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
460 RequestCommand
.METER_VALUES
,
463 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
464 meterValue
: [meterValue
],
472 `${this.logPrefix()} Charging station ${
473 StandardParametersKey.MeterValueSampleInterval
474 } configuration set to ${
475 interval ? Utils.formatDurationMilliSeconds(interval) : interval
476 }, not sending MeterValues`
481 public start(): void {
482 if (this.starting
=== false) {
483 this.starting
= true;
484 if (this.getEnableStatistics()) {
485 this.performanceStatistics
.start();
487 this.openWSConnection();
488 // Monitor charging station template file
489 this.templateFileWatcher
= FileUtils
.watchJsonFile(
491 FileType
.ChargingStationTemplate
,
494 (event
, filename
): void => {
495 if (filename
&& event
=== 'change') {
498 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
500 } file have changed, reload`
502 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
506 this.stopAutomaticTransactionGenerator();
508 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
510 this.startAutomaticTransactionGenerator();
512 if (this.getEnableStatistics()) {
513 this.performanceStatistics
.restart();
515 this.performanceStatistics
.stop();
517 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
520 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
527 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
528 this.starting
= false;
530 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
534 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
535 if (this.stopping
=== false) {
536 this.stopping
= true;
537 await this.stopMessageSequence(reason
);
538 for (const connectorId
of this.connectors
.keys()) {
539 if (connectorId
> 0) {
540 await this.ocppRequestService
.requestHandler
<
541 StatusNotificationRequest
,
542 StatusNotificationResponse
543 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
545 status: ChargePointStatus
.UNAVAILABLE
,
546 errorCode
: ChargePointErrorCode
.NO_ERROR
,
548 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
551 this.closeWSConnection();
552 if (this.getEnableStatistics()) {
553 this.performanceStatistics
.stop();
555 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
556 this.templateFileWatcher
.close();
557 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
558 this.bootNotificationResponse
= null;
559 this.started
= false;
560 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
561 this.stopping
= false;
563 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
567 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
568 await this.stop(reason
);
569 await Utils
.sleep(this.stationInfo
.resetTime
);
574 public saveOcppConfiguration(): void {
575 if (this.getOcppPersistentConfiguration()) {
576 this.saveConfiguration();
580 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
581 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
583 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
585 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
587 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
589 `${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`
591 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
593 let cpReplaced
= false;
594 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
595 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
596 (chargingProfile
: ChargingProfile
, index
: number) => {
598 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
599 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
600 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
602 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
608 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
611 public resetConnectorStatus(connectorId
: number): void {
612 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
613 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
614 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
615 this.getConnectorStatus(connectorId
).transactionStarted
= false;
616 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
617 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
618 delete this.getConnectorStatus(connectorId
).transactionId
;
619 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
620 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
621 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
622 this.stopMeterValues(connectorId
);
623 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
626 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
627 return ChargingStationConfigurationUtils
.getConfigurationKey(
629 StandardParametersKey
.SupportedFeatureProfiles
630 )?.value
.includes(featureProfile
);
633 public bufferMessage(message
: string): void {
634 this.messageBuffer
.add(message
);
637 public openWSConnection(
638 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
639 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
641 terminateOpened
: false,
644 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
645 params
.closeOpened
= params
?.closeOpened
?? false;
646 params
.terminateOpened
= params
?.terminateOpened
?? false;
648 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
649 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
651 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
653 if (params
?.closeOpened
) {
654 this.closeWSConnection();
656 if (params
?.terminateOpened
) {
657 this.terminateWSConnection();
659 let protocol
: string;
660 switch (this.getOcppVersion()) {
661 case OCPPVersion
.VERSION_16
:
662 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
665 this.handleUnsupportedVersion(this.getOcppVersion());
669 if (this.isWebSocketConnectionOpened()) {
671 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
677 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
680 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
682 // Handle WebSocket message
683 this.wsConnection
.on(
685 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
687 // Handle WebSocket error
688 this.wsConnection
.on(
690 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
692 // Handle WebSocket close
693 this.wsConnection
.on(
695 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
697 // Handle WebSocket open
698 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
699 // Handle WebSocket ping
700 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
701 // Handle WebSocket pong
702 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
705 public closeWSConnection(): void {
706 if (this.isWebSocketConnectionOpened()) {
707 this.wsConnection
.close();
708 this.wsConnection
= null;
712 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
713 if (!this.automaticTransactionGenerator
) {
714 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
715 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
719 if (!Utils
.isEmptyArray(connectorIds
)) {
720 for (const connectorId
of connectorIds
) {
721 this.automaticTransactionGenerator
.startConnector(connectorId
);
724 this.automaticTransactionGenerator
.start();
728 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
729 if (!Utils
.isEmptyArray(connectorIds
)) {
730 for (const connectorId
of connectorIds
) {
731 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
734 this.automaticTransactionGenerator
?.stop();
735 this.automaticTransactionGenerator
= null;
739 public async stopTransactionOnConnector(
741 reason
= StopTransactionReason
.NONE
742 ): Promise
<StopTransactionResponse
> {
743 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
745 this.getBeginEndMeterValues() &&
746 this.getOcppStrictCompliance() &&
747 !this.getOutOfOrderEndMeterValues()
749 // FIXME: Implement OCPP version agnostic helpers
750 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
753 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
755 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
757 RequestCommand
.METER_VALUES
,
761 meterValue
: [transactionEndMeterValue
],
765 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
767 RequestCommand
.STOP_TRANSACTION
,
770 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
776 private flushMessageBuffer(): void {
777 if (this.messageBuffer
.size
> 0) {
778 this.messageBuffer
.forEach((message
) => {
779 // TODO: evaluate the need to track performance
780 this.wsConnection
.send(message
);
781 this.messageBuffer
.delete(message
);
786 private getSupervisionUrlOcppConfiguration(): boolean {
787 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
790 private getSupervisionUrlOcppKey(): string {
791 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
794 private getTemplateFromFile(): ChargingStationTemplate
| null {
795 let template
: ChargingStationTemplate
= null;
797 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
798 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
800 const measureId
= `${FileType.ChargingStationTemplate} read`;
801 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
802 template
= JSON
.parse(
803 fs
.readFileSync(this.templateFile
, 'utf8')
804 ) as ChargingStationTemplate
;
805 PerformanceStatistics
.endMeasure(measureId
, beginId
);
806 template
.templateHash
= crypto
807 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
808 .update(JSON
.stringify(template
))
810 this.sharedLRUCache
.setChargingStationTemplate(template
);
813 FileUtils
.handleFileException(
815 FileType
.ChargingStationTemplate
,
817 error
as NodeJS
.ErrnoException
823 private getStationInfoFromTemplate(): ChargingStationInfo
{
824 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
825 if (Utils
.isNullOrUndefined(stationTemplate
)) {
826 const errorMsg
= 'Failed to read charging station template file';
827 logger
.error(`${this.logPrefix()} ${errorMsg}`);
828 throw new BaseError(errorMsg
);
830 if (Utils
.isEmptyObject(stationTemplate
)) {
831 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
832 logger
.error(`${this.logPrefix()} ${errorMsg}`);
833 throw new BaseError(errorMsg
);
835 // Deprecation template keys section
836 ChargingStationUtils
.warnDeprecatedTemplateKey(
841 "Use 'supervisionUrls' instead"
843 ChargingStationUtils
.convertDeprecatedTemplateKey(
848 const stationInfo
: ChargingStationInfo
=
849 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
850 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
851 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
855 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
856 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
857 stationTemplate
.power
= stationTemplate
.power
as number[];
858 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
859 stationInfo
.maximumPower
=
860 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
861 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
862 : stationTemplate
.power
[powerArrayRandomIndex
];
864 stationTemplate
.power
= stationTemplate
.power
as number;
865 stationInfo
.maximumPower
=
866 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
867 ? stationTemplate
.power
* 1000
868 : stationTemplate
.power
;
870 stationInfo
.resetTime
= stationTemplate
.resetTime
871 ? stationTemplate
.resetTime
* 1000
872 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
873 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
877 ChargingStationUtils
.checkConfiguredMaxConnectors(
878 configuredMaxConnectors
,
882 const templateMaxConnectors
=
883 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
884 ChargingStationUtils
.checkTemplateMaxConnectors(
885 templateMaxConnectors
,
890 configuredMaxConnectors
>
891 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
892 !stationTemplate
?.randomConnectors
895 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
897 }, forcing random connector configurations affectation`
899 stationInfo
.randomConnectors
= true;
901 // Build connectors if needed (FIXME: should be factored out)
902 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
903 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
904 ChargingStationUtils
.createStationInfoHash(stationInfo
);
908 private getStationInfoFromFile(): ChargingStationInfo
| null {
909 let stationInfo
: ChargingStationInfo
= null;
910 this.getStationInfoPersistentConfiguration() &&
911 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
912 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
916 private getStationInfo(): ChargingStationInfo
{
917 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
918 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
919 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
920 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
921 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
922 return this.stationInfo
;
924 return stationInfoFromFile
;
926 stationInfoFromFile
&&
927 ChargingStationUtils
.propagateSerialNumber(
928 this.getTemplateFromFile(),
930 stationInfoFromTemplate
932 return stationInfoFromTemplate
;
935 private saveStationInfo(): void {
936 if (this.getStationInfoPersistentConfiguration()) {
937 this.saveConfiguration();
941 private getOcppVersion(): OCPPVersion
{
942 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
945 private getOcppPersistentConfiguration(): boolean {
946 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
949 private getStationInfoPersistentConfiguration(): boolean {
950 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
953 private handleUnsupportedVersion(version
: OCPPVersion
) {
954 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
955 logger
.error(`${this.logPrefix()} ${errMsg}`);
956 throw new BaseError(errMsg
);
959 private initialize(): void {
960 this.configurationFile
= path
.join(
961 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
962 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
964 this.stationInfo
= this.getStationInfo();
965 this.saveStationInfo();
966 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
967 // Avoid duplication of connectors related information in RAM
968 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
969 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
970 if (this.getEnableStatistics()) {
971 this.performanceStatistics
= PerformanceStatistics
.getInstance(
972 this.stationInfo
.hashId
,
973 this.stationInfo
.chargingStationId
,
974 this.configuredSupervisionUrl
977 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
980 this.powerDivider
= this.getPowerDivider();
981 // OCPP configuration
982 this.ocppConfiguration
= this.getOcppConfiguration();
983 this.initializeOcppConfiguration();
984 switch (this.getOcppVersion()) {
985 case OCPPVersion
.VERSION_16
:
986 this.ocppIncomingRequestService
=
987 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
988 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
989 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
993 this.handleUnsupportedVersion(this.getOcppVersion());
996 if (this.stationInfo
?.autoRegister
) {
997 this.bootNotificationResponse
= {
998 currentTime
: new Date().toISOString(),
999 interval
: this.getHeartbeatInterval() / 1000,
1000 status: RegistrationStatus
.ACCEPTED
,
1005 private initializeOcppConfiguration(): void {
1007 !ChargingStationConfigurationUtils
.getConfigurationKey(
1009 StandardParametersKey
.HeartbeatInterval
1012 ChargingStationConfigurationUtils
.addConfigurationKey(
1014 StandardParametersKey
.HeartbeatInterval
,
1019 !ChargingStationConfigurationUtils
.getConfigurationKey(
1021 StandardParametersKey
.HeartBeatInterval
1024 ChargingStationConfigurationUtils
.addConfigurationKey(
1026 StandardParametersKey
.HeartBeatInterval
,
1032 this.getSupervisionUrlOcppConfiguration() &&
1033 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1035 ChargingStationConfigurationUtils
.addConfigurationKey(
1037 this.getSupervisionUrlOcppKey(),
1038 this.configuredSupervisionUrl
.href
,
1042 !this.getSupervisionUrlOcppConfiguration() &&
1043 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1045 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1047 this.getSupervisionUrlOcppKey(),
1052 this.stationInfo
.amperageLimitationOcppKey
&&
1053 !ChargingStationConfigurationUtils
.getConfigurationKey(
1055 this.stationInfo
.amperageLimitationOcppKey
1058 ChargingStationConfigurationUtils
.addConfigurationKey(
1060 this.stationInfo
.amperageLimitationOcppKey
,
1062 this.stationInfo
.maximumAmperage
*
1063 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1068 !ChargingStationConfigurationUtils
.getConfigurationKey(
1070 StandardParametersKey
.SupportedFeatureProfiles
1073 ChargingStationConfigurationUtils
.addConfigurationKey(
1075 StandardParametersKey
.SupportedFeatureProfiles
,
1076 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1079 ChargingStationConfigurationUtils
.addConfigurationKey(
1081 StandardParametersKey
.NumberOfConnectors
,
1082 this.getNumberOfConnectors().toString(),
1087 !ChargingStationConfigurationUtils
.getConfigurationKey(
1089 StandardParametersKey
.MeterValuesSampledData
1092 ChargingStationConfigurationUtils
.addConfigurationKey(
1094 StandardParametersKey
.MeterValuesSampledData
,
1095 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1099 !ChargingStationConfigurationUtils
.getConfigurationKey(
1101 StandardParametersKey
.ConnectorPhaseRotation
1104 const connectorPhaseRotation
= [];
1105 for (const connectorId
of this.connectors
.keys()) {
1107 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1108 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1109 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1110 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1112 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1113 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1114 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1115 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1118 ChargingStationConfigurationUtils
.addConfigurationKey(
1120 StandardParametersKey
.ConnectorPhaseRotation
,
1121 connectorPhaseRotation
.toString()
1125 !ChargingStationConfigurationUtils
.getConfigurationKey(
1127 StandardParametersKey
.AuthorizeRemoteTxRequests
1130 ChargingStationConfigurationUtils
.addConfigurationKey(
1132 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1137 !ChargingStationConfigurationUtils
.getConfigurationKey(
1139 StandardParametersKey
.LocalAuthListEnabled
1141 ChargingStationConfigurationUtils
.getConfigurationKey(
1143 StandardParametersKey
.SupportedFeatureProfiles
1144 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1146 ChargingStationConfigurationUtils
.addConfigurationKey(
1148 StandardParametersKey
.LocalAuthListEnabled
,
1153 !ChargingStationConfigurationUtils
.getConfigurationKey(
1155 StandardParametersKey
.ConnectionTimeOut
1158 ChargingStationConfigurationUtils
.addConfigurationKey(
1160 StandardParametersKey
.ConnectionTimeOut
,
1161 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1164 this.saveOcppConfiguration();
1167 private initializeConnectors(
1168 stationInfo
: ChargingStationInfo
,
1169 configuredMaxConnectors
: number,
1170 templateMaxConnectors
: number
1172 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1173 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1174 logger
.error(`${this.logPrefix()} ${logMsg}`);
1175 throw new BaseError(logMsg
);
1177 if (!stationInfo
?.Connectors
[0]) {
1179 `${this.logPrefix()} Charging station information from template ${
1181 } with no connector Id 0 configuration`
1184 if (stationInfo
?.Connectors
) {
1185 const connectorsConfigHash
= crypto
1186 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1187 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1189 const connectorsConfigChanged
=
1190 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1191 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1192 connectorsConfigChanged
&& this.connectors
.clear();
1193 this.connectorsConfigurationHash
= connectorsConfigHash
;
1194 // Add connector Id 0
1195 let lastConnector
= '0';
1196 for (lastConnector
in stationInfo
?.Connectors
) {
1197 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1199 lastConnectorId
=== 0 &&
1200 this.getUseConnectorId0(stationInfo
) &&
1201 stationInfo
?.Connectors
[lastConnector
]
1203 this.connectors
.set(
1205 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1207 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1208 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1209 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1213 // Generate all connectors
1214 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1215 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1216 const randConnectorId
= stationInfo
?.randomConnectors
1217 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1219 this.connectors
.set(
1221 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1223 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1224 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1225 this.getConnectorStatus(index
).chargingProfiles
= [];
1232 `${this.logPrefix()} Charging station information from template ${
1234 } with no connectors configuration defined, using already defined connectors`
1237 // Initialize transaction attributes on connectors
1238 for (const connectorId
of this.connectors
.keys()) {
1241 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1242 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1244 this.initializeConnectorStatus(connectorId
);
1249 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1250 let configuration
: ChargingStationConfiguration
= null;
1251 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1253 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1254 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1255 this.configurationFileHash
1258 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1259 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1260 configuration
= JSON
.parse(
1261 fs
.readFileSync(this.configurationFile
, 'utf8')
1262 ) as ChargingStationConfiguration
;
1263 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1264 this.configurationFileHash
= configuration
.configurationHash
;
1265 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1268 FileUtils
.handleFileException(
1270 FileType
.ChargingStationConfiguration
,
1271 this.configurationFile
,
1272 error
as NodeJS
.ErrnoException
1276 return configuration
;
1279 private saveConfiguration(): void {
1280 if (this.configurationFile
) {
1282 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1283 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1285 const configurationData
: ChargingStationConfiguration
=
1286 this.getConfigurationFromFile() ?? {};
1287 this.ocppConfiguration
?.configurationKey
&&
1288 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1289 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1290 delete configurationData
.configurationHash
;
1291 const configurationHash
= crypto
1292 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1293 .update(JSON
.stringify(configurationData
))
1295 if (this.configurationFileHash
!== configurationHash
) {
1296 configurationData
.configurationHash
= configurationHash
;
1297 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1298 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1299 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1300 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1301 fs
.closeSync(fileDescriptor
);
1302 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1303 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1304 this.configurationFileHash
= configurationHash
;
1305 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1308 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1309 this.configurationFile
1314 FileUtils
.handleFileException(
1316 FileType
.ChargingStationConfiguration
,
1317 this.configurationFile
,
1318 error
as NodeJS
.ErrnoException
1323 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1328 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1329 return this.getTemplateFromFile()?.Configuration
?? null;
1332 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1333 let configuration
: ChargingStationConfiguration
= null;
1334 if (this.getOcppPersistentConfiguration()) {
1335 const configurationFromFile
= this.getConfigurationFromFile();
1336 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1338 configuration
&& delete configuration
.stationInfo
;
1339 return configuration
;
1342 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1343 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1344 if (!ocppConfiguration
) {
1345 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1347 return ocppConfiguration
;
1350 private async onOpen(): Promise
<void> {
1351 if (this.isWebSocketConnectionOpened()) {
1353 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1355 if (!this.isRegistered()) {
1356 // Send BootNotification
1357 let registrationRetryCount
= 0;
1359 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1360 BootNotificationRequest
,
1361 BootNotificationResponse
1362 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1363 skipBufferingOnError
: true,
1365 if (!this.isRegistered()) {
1366 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1368 this.bootNotificationResponse
?.interval
1369 ? this.bootNotificationResponse
.interval
* 1000
1370 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1374 !this.isRegistered() &&
1375 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1376 this.getRegistrationMaxRetries() === -1)
1379 if (this.isRegistered()) {
1380 if (this.isInAcceptedState()) {
1381 await this.startMessageSequence();
1385 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1388 this.wsConnectionRestarted
= false;
1389 this.autoReconnectRetryCount
= 0;
1390 this.started
= true;
1391 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1394 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1399 private async onClose(code
: number, reason
: string): Promise
<void> {
1402 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1403 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1405 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1407 )}' and reason '${reason}'`
1409 this.autoReconnectRetryCount
= 0;
1414 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1416 )}' and reason '${reason}'`
1418 await this.reconnect();
1421 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1424 private async onMessage(data
: Data
): Promise
<void> {
1425 let messageType
: number;
1426 let messageId
: string;
1427 let commandName
: IncomingRequestCommand
;
1428 let commandPayload
: JsonType
;
1429 let errorType
: ErrorType
;
1430 let errorMessage
: string;
1431 let errorDetails
: JsonType
;
1432 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1433 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1434 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1435 let requestPayload
: JsonType
;
1436 let cachedRequest
: CachedRequest
;
1439 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1440 if (Array.isArray(request
) === true) {
1441 [messageType
, messageId
] = request
;
1442 // Check the type of message
1443 switch (messageType
) {
1445 case MessageType
.CALL_MESSAGE
:
1446 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1447 if (this.getEnableStatistics()) {
1448 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1451 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1455 // Process the message
1456 await this.ocppIncomingRequestService
.incomingRequestHandler(
1464 case MessageType
.CALL_RESULT_MESSAGE
:
1465 [, , commandPayload
] = request
as Response
;
1466 if (!this.requests
.has(messageId
)) {
1468 throw new OCPPError(
1469 ErrorType
.INTERNAL_ERROR
,
1470 `Response for unknown message id ${messageId}`,
1476 cachedRequest
= this.requests
.get(messageId
);
1477 if (Array.isArray(cachedRequest
) === true) {
1478 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1480 throw new OCPPError(
1481 ErrorType
.PROTOCOL_ERROR
,
1482 `Cached request for message id ${messageId} response is not an array`,
1484 cachedRequest
as unknown
as JsonType
1488 `${this.logPrefix()} << Command '${
1489 requestCommandName ?? 'unknown'
1490 }' received response payload: ${JSON.stringify(request)}`
1492 responseCallback(commandPayload
, requestPayload
);
1495 case MessageType
.CALL_ERROR_MESSAGE
:
1496 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1497 if (!this.requests
.has(messageId
)) {
1499 throw new OCPPError(
1500 ErrorType
.INTERNAL_ERROR
,
1501 `Error response for unknown message id ${messageId}`,
1503 { errorType
, errorMessage
, errorDetails
}
1506 cachedRequest
= this.requests
.get(messageId
);
1507 if (Array.isArray(cachedRequest
) === true) {
1508 [, errorCallback
, requestCommandName
] = cachedRequest
;
1510 throw new OCPPError(
1511 ErrorType
.PROTOCOL_ERROR
,
1512 `Cached request for message id ${messageId} error response is not an array`,
1514 cachedRequest
as unknown
as JsonType
1518 `${this.logPrefix()} << Command '${
1519 requestCommandName ?? 'unknown'
1520 }' received error payload: ${JSON.stringify(request)}`
1522 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1526 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1527 errMsg
= `Wrong message type ${messageType}`;
1528 logger
.error(`${this.logPrefix()} ${errMsg}`);
1529 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1531 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1533 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1540 `${this.logPrefix()} Incoming OCPP command '${
1541 commandName ?? requestCommandName ?? null
1542 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1543 this.requests.get(messageId)
1544 )}' processing error:`,
1547 if (!(error
instanceof OCPPError
)) {
1549 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1550 commandName ?? requestCommandName ?? null
1551 }' message '${data.toString()}' handling is not an OCPPError:`,
1556 messageType
=== MessageType
.CALL_MESSAGE
&&
1557 (await this.ocppRequestService
.sendError(
1561 commandName
?? requestCommandName
?? null
1566 private onPing(): void {
1567 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1570 private onPong(): void {
1571 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1574 private onError(error
: WSError
): void {
1575 this.closeWSConnection();
1576 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1579 private getEnergyActiveImportRegister(
1580 connectorStatus
: ConnectorStatus
,
1583 if (this.getMeteringPerTransaction()) {
1586 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1587 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1592 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1593 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1597 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1598 const localStationInfo
= stationInfo
?? this.stationInfo
;
1599 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1600 ? localStationInfo
.useConnectorId0
1604 private getNumberOfRunningTransactions(): number {
1606 for (const connectorId
of this.connectors
.keys()) {
1607 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1614 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1615 for (const connectorId
of this.connectors
.keys()) {
1616 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1617 await this.stopTransactionOnConnector(connectorId
, reason
);
1623 private getConnectionTimeout(): number | undefined {
1625 ChargingStationConfigurationUtils
.getConfigurationKey(
1627 StandardParametersKey
.ConnectionTimeOut
1632 ChargingStationConfigurationUtils
.getConfigurationKey(
1634 StandardParametersKey
.ConnectionTimeOut
1636 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1639 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1642 // -1 for unlimited, 0 for disabling
1643 private getAutoReconnectMaxRetries(): number | undefined {
1644 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1645 return this.stationInfo
.autoReconnectMaxRetries
;
1647 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1648 return Configuration
.getAutoReconnectMaxRetries();
1654 private getRegistrationMaxRetries(): number | undefined {
1655 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1656 return this.stationInfo
.registrationMaxRetries
;
1661 private getPowerDivider(): number {
1662 let powerDivider
= this.getNumberOfConnectors();
1663 if (this.stationInfo
?.powerSharedByConnectors
) {
1664 powerDivider
= this.getNumberOfRunningTransactions();
1666 return powerDivider
;
1669 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1670 const localStationInfo
= stationInfo
?? this.stationInfo
;
1671 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1674 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1675 const maximumPower
= this.getMaximumPower(stationInfo
);
1676 switch (this.getCurrentOutType(stationInfo
)) {
1677 case CurrentType
.AC
:
1678 return ACElectricUtils
.amperagePerPhaseFromPower(
1679 this.getNumberOfPhases(stationInfo
),
1680 maximumPower
/ this.getNumberOfConnectors(),
1681 this.getVoltageOut(stationInfo
)
1683 case CurrentType
.DC
:
1684 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1688 private getAmperageLimitation(): number | undefined {
1690 this.stationInfo
.amperageLimitationOcppKey
&&
1691 ChargingStationConfigurationUtils
.getConfigurationKey(
1693 this.stationInfo
.amperageLimitationOcppKey
1698 ChargingStationConfigurationUtils
.getConfigurationKey(
1700 this.stationInfo
.amperageLimitationOcppKey
1702 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1707 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1708 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1709 let chargingProfiles
: ChargingProfile
[] = [];
1710 // Get charging profiles for connector and sort by stack level
1711 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1712 (a
, b
) => b
.stackLevel
- a
.stackLevel
1714 // Get profiles on connector 0
1715 if (this.getConnectorStatus(0).chargingProfiles
) {
1716 chargingProfiles
.push(
1717 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1720 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1721 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1725 if (!Utils
.isNullOrUndefined(result
)) {
1726 limit
= result
.limit
;
1727 matchingChargingProfile
= result
.matchingChargingProfile
;
1728 switch (this.getCurrentOutType()) {
1729 case CurrentType
.AC
:
1731 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1732 ChargingRateUnitType
.WATT
1734 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1736 case CurrentType
.DC
:
1738 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1739 ChargingRateUnitType
.WATT
1741 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1743 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1744 if (limit
> connectorMaximumPower
) {
1746 `${this.logPrefix()} Charging profile id ${
1747 matchingChargingProfile.chargingProfileId
1748 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1749 this.getConnectorStatus(connectorId
).chargingProfiles
1751 limit
= connectorMaximumPower
;
1758 private async startMessageSequence(): Promise
<void> {
1759 if (this.stationInfo
?.autoRegister
) {
1760 await this.ocppRequestService
.requestHandler
<
1761 BootNotificationRequest
,
1762 BootNotificationResponse
1763 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1764 skipBufferingOnError
: true,
1767 // Start WebSocket ping
1768 this.startWebSocketPing();
1770 this.startHeartbeat();
1771 // Initialize connectors status
1772 for (const connectorId
of this.connectors
.keys()) {
1773 if (connectorId
=== 0) {
1776 this.started
=== true &&
1777 !this.getConnectorStatus(connectorId
)?.status &&
1778 this.getConnectorStatus(connectorId
)?.bootStatus
1780 // Send status in template at startup
1781 await this.ocppRequestService
.requestHandler
<
1782 StatusNotificationRequest
,
1783 StatusNotificationResponse
1784 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1786 status: this.getConnectorStatus(connectorId
).bootStatus
,
1787 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1789 this.getConnectorStatus(connectorId
).status =
1790 this.getConnectorStatus(connectorId
).bootStatus
;
1792 this.started
=== false &&
1793 this.getConnectorStatus(connectorId
)?.status &&
1794 this.getConnectorStatus(connectorId
)?.bootStatus
1796 // Send status in template after reset
1797 await this.ocppRequestService
.requestHandler
<
1798 StatusNotificationRequest
,
1799 StatusNotificationResponse
1800 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1802 status: this.getConnectorStatus(connectorId
).bootStatus
,
1803 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1805 this.getConnectorStatus(connectorId
).status =
1806 this.getConnectorStatus(connectorId
).bootStatus
;
1807 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1808 // Send previous status at template reload
1809 await this.ocppRequestService
.requestHandler
<
1810 StatusNotificationRequest
,
1811 StatusNotificationResponse
1812 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1814 status: this.getConnectorStatus(connectorId
).status,
1815 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1818 // Send default status
1819 await this.ocppRequestService
.requestHandler
<
1820 StatusNotificationRequest
,
1821 StatusNotificationResponse
1822 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1824 status: ChargePointStatus
.AVAILABLE
,
1825 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1827 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1831 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1832 this.startAutomaticTransactionGenerator();
1834 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1837 private async stopMessageSequence(
1838 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1840 // Stop WebSocket ping
1841 this.stopWebSocketPing();
1843 this.stopHeartbeat();
1844 // Stop ongoing transactions
1845 if (this.automaticTransactionGenerator
?.started
=== true) {
1846 this.stopAutomaticTransactionGenerator();
1848 await this.stopRunningTransactions(reason
);
1852 private startWebSocketPing(): void {
1853 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1855 StandardParametersKey
.WebSocketPingInterval
1857 ? Utils
.convertToInt(
1858 ChargingStationConfigurationUtils
.getConfigurationKey(
1860 StandardParametersKey
.WebSocketPingInterval
1864 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1865 this.webSocketPingSetInterval
= setInterval(() => {
1866 if (this.isWebSocketConnectionOpened()) {
1867 this.wsConnection
.ping((): void => {
1868 /* This is intentional */
1871 }, webSocketPingInterval
* 1000);
1874 ' WebSocket ping started every ' +
1875 Utils
.formatDurationSeconds(webSocketPingInterval
)
1877 } else if (this.webSocketPingSetInterval
) {
1880 ' WebSocket ping every ' +
1881 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1886 `${this.logPrefix()} WebSocket ping interval set to ${
1887 webSocketPingInterval
1888 ? Utils.formatDurationSeconds(webSocketPingInterval)
1889 : webSocketPingInterval
1890 }, not starting the WebSocket ping`
1895 private stopWebSocketPing(): void {
1896 if (this.webSocketPingSetInterval
) {
1897 clearInterval(this.webSocketPingSetInterval
);
1901 private getConfiguredSupervisionUrl(): URL
{
1902 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1903 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1905 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1907 switch (Configuration
.getSupervisionUrlDistribution()) {
1908 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1909 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1911 case SupervisionUrlDistribution
.RANDOM
:
1913 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1915 case SupervisionUrlDistribution
.SEQUENTIAL
:
1916 if (this.index
<= supervisionUrls
.length
) {
1917 urlIndex
= this.index
- 1;
1920 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1926 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1927 SupervisionUrlDistribution.ROUND_ROBIN
1930 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1933 return new URL(supervisionUrls
[urlIndex
]);
1935 return new URL(supervisionUrls
as string);
1938 private getHeartbeatInterval(): number | undefined {
1939 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1941 StandardParametersKey
.HeartbeatInterval
1943 if (HeartbeatInterval
) {
1944 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1946 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1948 StandardParametersKey
.HeartBeatInterval
1950 if (HeartBeatInterval
) {
1951 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1953 !this.stationInfo
?.autoRegister
&&
1955 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1956 Constants.DEFAULT_HEARTBEAT_INTERVAL
1959 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1962 private stopHeartbeat(): void {
1963 if (this.heartbeatSetInterval
) {
1964 clearInterval(this.heartbeatSetInterval
);
1968 private terminateWSConnection(): void {
1969 if (this.isWebSocketConnectionOpened()) {
1970 this.wsConnection
.terminate();
1971 this.wsConnection
= null;
1975 private stopMeterValues(connectorId
: number) {
1976 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1977 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1981 private getReconnectExponentialDelay(): boolean | undefined {
1982 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1983 ? this.stationInfo
.reconnectExponentialDelay
1987 private async reconnect(): Promise
<void> {
1988 // Stop WebSocket ping
1989 this.stopWebSocketPing();
1991 this.stopHeartbeat();
1992 // Stop the ATG if needed
1993 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
1994 this.stopAutomaticTransactionGenerator();
1997 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1998 this.getAutoReconnectMaxRetries() === -1
2000 this.autoReconnectRetryCount
++;
2001 const reconnectDelay
= this.getReconnectExponentialDelay()
2002 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2003 : this.getConnectionTimeout() * 1000;
2004 const reconnectDelayWithdraw
= 1000;
2005 const reconnectTimeout
=
2006 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2007 ? reconnectDelay
- reconnectDelayWithdraw
2010 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2013 )}ms, timeout ${reconnectTimeout}ms`
2015 await Utils
.sleep(reconnectDelay
);
2018 ' WebSocket: reconnecting try #' +
2019 this.autoReconnectRetryCount
.toString()
2021 this.openWSConnection(
2022 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2023 { closeOpened
: true }
2025 this.wsConnectionRestarted
= true;
2026 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2028 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2029 this.autoReconnectRetryCount
2030 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2035 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2036 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2039 private initializeConnectorStatus(connectorId
: number): void {
2040 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2041 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2042 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2043 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2044 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2045 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;