1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import crypto from
'node:crypto';
4 import fs from
'node:fs';
5 import path from
'node:path';
6 import { URL
} from
'node:url';
7 import { parentPort
} from
'node:worker_threads';
9 import merge from
'just-merge';
10 import WebSocket
, { type RawData
} from
'ws';
13 AutomaticTransactionGenerator
,
14 ChargingStationConfigurationUtils
,
16 ChargingStationWorkerBroadcastChannel
,
22 // OCPP16IncomingRequestService,
24 // OCPP16ResponseService,
26 OCPP20IncomingRequestService
,
28 // OCPP20ResponseService,
29 type OCPPIncomingRequestService
,
30 type OCPPRequestService
,
33 import { OCPP16IncomingRequestService
} from
'./ocpp/1.6/OCPP16IncomingRequestService';
34 import { OCPP16ResponseService
} from
'./ocpp/1.6/OCPP16ResponseService';
35 import { OCPP20ResponseService
} from
'./ocpp/2.0/OCPP20ResponseService';
36 import { OCPPServiceUtils
} from
'./ocpp/OCPPServiceUtils';
37 import { BaseError
, OCPPError
} from
'../exception';
38 import { PerformanceStatistics
} from
'../performance';
40 type AutomaticTransactionGeneratorConfiguration
,
42 type BootNotificationRequest
,
43 type BootNotificationResponse
,
45 type ChargingStationConfiguration
,
46 type ChargingStationInfo
,
47 type ChargingStationOcppConfiguration
,
48 type ChargingStationTemplate
,
49 ConnectorPhaseRotation
,
58 type FirmwareStatusNotificationRequest
,
59 type FirmwareStatusNotificationResponse
,
61 type HeartbeatRequest
,
62 type HeartbeatResponse
,
64 type IncomingRequestCommand
,
69 type MeterValuesRequest
,
70 type MeterValuesResponse
,
74 RegistrationStatusEnumType
,
77 StandardParametersKey
,
78 type StatusNotificationRequest
,
79 type StatusNotificationResponse
,
80 StopTransactionReason
,
81 type StopTransactionRequest
,
82 type StopTransactionResponse
,
83 SupervisionUrlDistribution
,
84 SupportedFeatureProfiles
,
87 WebSocketCloseEventStatusCode
,
100 export class ChargingStation
{
101 public readonly index
: number;
102 public readonly templateFile
: string;
103 public stationInfo
!: ChargingStationInfo
;
104 public started
: boolean;
105 public starting
: boolean;
106 public idTagsCache
: IdTagsCache
;
107 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
108 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
109 public wsConnection
!: WebSocket
| null;
110 public readonly connectors
: Map
<number, ConnectorStatus
>;
111 public readonly requests
: Map
<string, CachedRequest
>;
112 public performanceStatistics
!: PerformanceStatistics
| undefined;
113 public heartbeatSetInterval
!: NodeJS
.Timeout
;
114 public ocppRequestService
!: OCPPRequestService
;
115 public bootNotificationRequest
!: BootNotificationRequest
;
116 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
117 public powerDivider
!: number;
118 private stopping
: boolean;
119 private configurationFile
!: string;
120 private configurationFileHash
!: string;
121 private connectorsConfigurationHash
!: string;
122 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
123 private readonly messageBuffer
: Set
<string>;
124 private configuredSupervisionUrl
!: URL
;
125 private wsConnectionRestarted
: boolean;
126 private autoReconnectRetryCount
: number;
127 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
128 private readonly sharedLRUCache
: SharedLRUCache
;
129 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
130 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
132 constructor(index
: number, templateFile
: string) {
133 this.started
= false;
134 this.starting
= false;
135 this.stopping
= false;
136 this.wsConnectionRestarted
= false;
137 this.autoReconnectRetryCount
= 0;
139 this.templateFile
= templateFile
;
140 this.connectors
= new Map
<number, ConnectorStatus
>();
141 this.requests
= new Map
<string, CachedRequest
>();
142 this.messageBuffer
= new Set
<string>();
143 this.sharedLRUCache
= SharedLRUCache
.getInstance();
144 this.idTagsCache
= IdTagsCache
.getInstance();
145 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
150 private get
wsConnectionUrl(): URL
{
153 this.getSupervisionUrlOcppConfiguration() &&
154 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey())
155 ? ChargingStationConfigurationUtils.getConfigurationKey(
157 this.getSupervisionUrlOcppKey()
159 : this.configuredSupervisionUrl.href
160 }/${this.stationInfo.chargingStationId}`
164 public logPrefix
= (): string => {
165 return Utils
.logPrefix(
167 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) &&
168 this?.stationInfo?.chargingStationId) ??
169 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) ??
175 public hasIdTags(): boolean {
176 const idTagsFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
177 return Utils
.isNotEmptyArray(this.idTagsCache
.getIdTags(idTagsFile
));
180 public getEnableStatistics(): boolean {
181 return this.stationInfo
.enableStatistics
?? false;
184 public getMustAuthorizeAtRemoteStart(): boolean {
185 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
188 public getPayloadSchemaValidation(): boolean {
189 return this.stationInfo
.payloadSchemaValidation
?? true;
192 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
193 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
194 switch (this.getCurrentOutType(stationInfo
)) {
196 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
197 ? localStationInfo
.numberOfPhases
204 public isWebSocketConnectionOpened(): boolean {
205 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
208 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
209 return this?.bootNotificationResponse
?.status;
212 public isInUnknownState(): boolean {
213 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
216 public isInPendingState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
220 public isInAcceptedState(): boolean {
221 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
224 public isInRejectedState(): boolean {
225 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
228 public isRegistered(): boolean {
230 this.isInUnknownState() === false &&
231 (this.isInAcceptedState() === true || this.isInPendingState() === true)
235 public isChargingStationAvailable(): boolean {
236 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.OPERATIVE
;
239 public isConnectorAvailable(id
: number): boolean {
240 return id
> 0 && this.getConnectorStatus(id
)?.availability
=== AvailabilityType
.OPERATIVE
;
243 public getNumberOfConnectors(): number {
244 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
247 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
248 return this.connectors
.get(id
);
251 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
252 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
255 public getOcppStrictCompliance(): boolean {
256 return this.stationInfo
?.ocppStrictCompliance
?? false;
259 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
260 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
261 this.getCurrentOutType(stationInfo
),
265 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
266 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
267 ? localStationInfo
.voltageOut
271 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
272 const localStationInfo
= stationInfo
?? this.stationInfo
;
273 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
276 public getConnectorMaximumAvailablePower(connectorId
: number): number {
277 let connectorAmperageLimitationPowerLimit
: number;
279 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
280 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
282 connectorAmperageLimitationPowerLimit
=
283 (this.getCurrentOutType() === CurrentType
.AC
284 ? ACElectricUtils
.powerTotal(
285 this.getNumberOfPhases(),
286 this.getVoltageOut(),
287 this.getAmperageLimitation() * this.getNumberOfConnectors()
289 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
292 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
293 const connectorChargingProfilesPowerLimit
=
294 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
296 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
297 isNaN(connectorAmperageLimitationPowerLimit
)
299 : connectorAmperageLimitationPowerLimit
,
300 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
304 public getTransactionIdTag(transactionId
: number): string | undefined {
305 for (const connectorId
of this.connectors
.keys()) {
308 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
310 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
315 public getOutOfOrderEndMeterValues(): boolean {
316 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
319 public getBeginEndMeterValues(): boolean {
320 return this.stationInfo
?.beginEndMeterValues
?? false;
323 public getMeteringPerTransaction(): boolean {
324 return this.stationInfo
?.meteringPerTransaction
?? true;
327 public getTransactionDataMeterValues(): boolean {
328 return this.stationInfo
?.transactionDataMeterValues
?? false;
331 public getMainVoltageMeterValues(): boolean {
332 return this.stationInfo
?.mainVoltageMeterValues
?? true;
335 public getPhaseLineToLineVoltageMeterValues(): boolean {
336 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
339 public getCustomValueLimitationMeterValues(): boolean {
340 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
343 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
344 for (const connectorId
of this.connectors
.keys()) {
347 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
354 public getEnergyActiveImportRegisterByTransactionId(
355 transactionId
: number,
358 return this.getEnergyActiveImportRegister(
359 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
364 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
365 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
368 public getAuthorizeRemoteTxRequests(): boolean {
369 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
371 StandardParametersKey
.AuthorizeRemoteTxRequests
373 return authorizeRemoteTxRequests
374 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
378 public getLocalAuthListEnabled(): boolean {
379 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
381 StandardParametersKey
.LocalAuthListEnabled
383 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
386 public getHeartbeatInterval(): number {
387 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
389 StandardParametersKey
.HeartbeatInterval
391 if (HeartbeatInterval
) {
392 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
394 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
396 StandardParametersKey
.HeartBeatInterval
398 if (HeartBeatInterval
) {
399 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
401 this.stationInfo
?.autoRegister
=== false &&
403 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
404 Constants.DEFAULT_HEARTBEAT_INTERVAL
407 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
410 public setSupervisionUrl(url
: string): void {
412 this.getSupervisionUrlOcppConfiguration() &&
413 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
415 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
417 this.getSupervisionUrlOcppKey(),
421 this.stationInfo
.supervisionUrls
= url
;
422 this.saveStationInfo();
423 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
427 public startHeartbeat(): void {
428 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
429 this.heartbeatSetInterval
= setInterval(() => {
430 this.ocppRequestService
431 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
434 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
438 }, this.getHeartbeatInterval());
440 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
441 this.getHeartbeatInterval()
444 } else if (this.heartbeatSetInterval
) {
446 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
447 this.getHeartbeatInterval()
452 `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
457 public restartHeartbeat(): void {
459 this.stopHeartbeat();
461 this.startHeartbeat();
464 public restartWebSocketPing(): void {
465 // Stop WebSocket ping
466 this.stopWebSocketPing();
467 // Start WebSocket ping
468 this.startWebSocketPing();
471 public startMeterValues(connectorId
: number, interval
: number): void {
472 if (connectorId
=== 0) {
474 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
478 if (!this.getConnectorStatus(connectorId
)) {
480 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
484 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
486 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
490 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
491 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
494 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
499 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
500 // FIXME: Implement OCPP version agnostic helpers
501 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
504 this.getConnectorStatus(connectorId
).transactionId
,
507 this.ocppRequestService
508 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
510 RequestCommand
.METER_VALUES
,
513 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
514 meterValue
: [meterValue
],
519 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
526 `${this.logPrefix()} Charging station ${
527 StandardParametersKey.MeterValueSampleInterval
528 } configuration set to ${interval}, not sending MeterValues`
533 public start(): void {
534 if (this.started
=== false) {
535 if (this.starting
=== false) {
536 this.starting
= true;
537 if (this.getEnableStatistics() === true) {
538 this.performanceStatistics
?.start();
540 this.openWSConnection();
541 // Monitor charging station template file
542 this.templateFileWatcher
= FileUtils
.watchJsonFile(
544 FileType
.ChargingStationTemplate
,
547 (event
, filename
): void => {
548 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
551 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
553 } file have changed, reload`
555 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
559 this.stopAutomaticTransactionGenerator();
561 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
563 this.startAutomaticTransactionGenerator();
565 if (this.getEnableStatistics() === true) {
566 this.performanceStatistics
?.restart();
568 this.performanceStatistics
?.stop();
570 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
573 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
581 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
582 this.starting
= false;
584 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
587 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
591 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
592 if (this.started
=== true) {
593 if (this.stopping
=== false) {
594 this.stopping
= true;
595 await this.stopMessageSequence(reason
);
596 this.closeWSConnection();
597 if (this.getEnableStatistics() === true) {
598 this.performanceStatistics
?.stop();
600 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
601 this.templateFileWatcher
?.close();
602 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
603 delete this.bootNotificationResponse
;
604 this.started
= false;
605 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
606 this.stopping
= false;
608 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
611 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
615 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
616 await this.stop(reason
);
617 await Utils
.sleep(this.stationInfo
.resetTime
);
622 public saveOcppConfiguration(): void {
623 if (this.getOcppPersistentConfiguration()) {
624 this.saveConfiguration();
628 public resetConnectorStatus(connectorId
: number): void {
629 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
630 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
631 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
632 this.getConnectorStatus(connectorId
).transactionStarted
= false;
633 delete this.getConnectorStatus(connectorId
)?.localAuthorizeIdTag
;
634 delete this.getConnectorStatus(connectorId
)?.authorizeIdTag
;
635 delete this.getConnectorStatus(connectorId
)?.transactionId
;
636 delete this.getConnectorStatus(connectorId
)?.transactionIdTag
;
637 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
638 delete this.getConnectorStatus(connectorId
)?.transactionBeginMeterValue
;
639 this.stopMeterValues(connectorId
);
640 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
643 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
644 return ChargingStationConfigurationUtils
.getConfigurationKey(
646 StandardParametersKey
.SupportedFeatureProfiles
647 )?.value
?.includes(featureProfile
);
650 public bufferMessage(message
: string): void {
651 this.messageBuffer
.add(message
);
654 public openWSConnection(
655 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
656 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
658 terminateOpened
: false,
661 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
662 params
.closeOpened
= params
?.closeOpened
?? false;
663 params
.terminateOpened
= params
?.terminateOpened
?? false;
664 if (this.started
=== false && this.starting
=== false) {
666 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
671 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
672 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
674 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
676 if (params
?.closeOpened
) {
677 this.closeWSConnection();
679 if (params
?.terminateOpened
) {
680 this.terminateWSConnection();
683 if (this.isWebSocketConnectionOpened() === true) {
685 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
691 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
694 this.wsConnection
= new WebSocket(
695 this.wsConnectionUrl
,
696 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
700 // Handle WebSocket message
701 this.wsConnection
.on(
703 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
705 // Handle WebSocket error
706 this.wsConnection
.on(
708 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
710 // Handle WebSocket close
711 this.wsConnection
.on(
713 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
715 // Handle WebSocket open
716 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
717 // Handle WebSocket ping
718 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
719 // Handle WebSocket pong
720 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
723 public closeWSConnection(): void {
724 if (this.isWebSocketConnectionOpened() === true) {
725 this.wsConnection
?.close();
726 this.wsConnection
= null;
730 public startAutomaticTransactionGenerator(
731 connectorIds
?: number[],
732 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
734 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
735 automaticTransactionGeneratorConfiguration
??
736 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
739 if (Utils
.isNotEmptyArray(connectorIds
)) {
740 for (const connectorId
of connectorIds
) {
741 this.automaticTransactionGenerator
?.startConnector(connectorId
);
744 this.automaticTransactionGenerator
?.start();
746 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
749 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
750 if (Utils
.isNotEmptyArray(connectorIds
)) {
751 for (const connectorId
of connectorIds
) {
752 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
755 this.automaticTransactionGenerator
?.stop();
757 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
760 public async stopTransactionOnConnector(
762 reason
= StopTransactionReason
.NONE
763 ): Promise
<StopTransactionResponse
> {
764 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
766 this.getBeginEndMeterValues() === true &&
767 this.getOcppStrictCompliance() === true &&
768 this.getOutOfOrderEndMeterValues() === false
770 // FIXME: Implement OCPP version agnostic helpers
771 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
774 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
776 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
778 RequestCommand
.METER_VALUES
,
782 meterValue
: [transactionEndMeterValue
],
786 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
788 RequestCommand
.STOP_TRANSACTION
,
791 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
797 private flushMessageBuffer(): void {
798 if (this.messageBuffer
.size
> 0) {
799 this.messageBuffer
.forEach((message
) => {
801 let commandName
: RequestCommand
;
802 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
803 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
805 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
806 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
808 this.wsConnection
?.send(message
);
809 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
811 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
813 )} payload sent: ${message}`
815 this.messageBuffer
.delete(message
);
820 private getSupervisionUrlOcppConfiguration(): boolean {
821 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
824 private getSupervisionUrlOcppKey(): string {
825 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
828 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
829 let template
: ChargingStationTemplate
;
831 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
832 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
834 const measureId
= `${FileType.ChargingStationTemplate} read`;
835 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
836 template
= JSON
.parse(
837 fs
.readFileSync(this.templateFile
, 'utf8')
838 ) as ChargingStationTemplate
;
839 PerformanceStatistics
.endMeasure(measureId
, beginId
);
840 template
.templateHash
= crypto
841 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
842 .update(JSON
.stringify(template
))
844 this.sharedLRUCache
.setChargingStationTemplate(template
);
847 FileUtils
.handleFileException(
849 FileType
.ChargingStationTemplate
,
850 error
as NodeJS
.ErrnoException
,
857 private getStationInfoFromTemplate(): ChargingStationInfo
{
858 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
859 if (Utils
.isNullOrUndefined(stationTemplate
)) {
860 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
861 logger
.error(`${this.logPrefix()} ${errorMsg}`);
862 throw new BaseError(errorMsg
);
864 if (Utils
.isEmptyObject(stationTemplate
)) {
865 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
866 logger
.error(`${this.logPrefix()} ${errorMsg}`);
867 throw new BaseError(errorMsg
);
869 // Deprecation template keys section
870 ChargingStationUtils
.warnDeprecatedTemplateKey(
875 "Use 'supervisionUrls' instead"
877 ChargingStationUtils
.convertDeprecatedTemplateKey(
882 const stationInfo
: ChargingStationInfo
=
883 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
884 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
885 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
889 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
890 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
891 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
892 stationTemplate
.power
= stationTemplate
.power
as number[];
893 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
894 stationInfo
.maximumPower
=
895 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
896 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
897 : stationTemplate
.power
[powerArrayRandomIndex
];
899 stationTemplate
.power
= stationTemplate
?.power
as number;
900 stationInfo
.maximumPower
=
901 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
902 ? stationTemplate
.power
* 1000
903 : stationTemplate
.power
;
905 stationInfo
.firmwareVersionPattern
=
906 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
908 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
909 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
912 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
914 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
917 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
924 stationTemplate
?.firmwareUpgrade
?? {}
926 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
927 ? stationTemplate
.resetTime
* 1000
928 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
929 const configuredMaxConnectors
=
930 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
931 ChargingStationUtils
.checkConfiguredMaxConnectors(
932 configuredMaxConnectors
,
936 const templateMaxConnectors
=
937 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
938 ChargingStationUtils
.checkTemplateMaxConnectors(
939 templateMaxConnectors
,
944 configuredMaxConnectors
>
945 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
946 !stationTemplate
?.randomConnectors
949 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
951 }, forcing random connector configurations affectation`
953 stationInfo
.randomConnectors
= true;
955 // Build connectors if needed (FIXME: should be factored out)
956 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
957 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
958 ChargingStationUtils
.createStationInfoHash(stationInfo
);
962 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
963 let stationInfo
: ChargingStationInfo
| undefined;
964 this.getStationInfoPersistentConfiguration() &&
965 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
966 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
970 private getStationInfo(): ChargingStationInfo
{
971 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
972 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
973 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
974 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
975 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
976 return this.stationInfo
;
978 return stationInfoFromFile
;
980 stationInfoFromFile
&&
981 ChargingStationUtils
.propagateSerialNumber(
982 this.getTemplateFromFile(),
984 stationInfoFromTemplate
986 return stationInfoFromTemplate
;
989 private saveStationInfo(): void {
990 if (this.getStationInfoPersistentConfiguration()) {
991 this.saveConfiguration();
995 private getOcppPersistentConfiguration(): boolean {
996 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
999 private getStationInfoPersistentConfiguration(): boolean {
1000 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
1003 private handleUnsupportedVersion(version
: OCPPVersion
) {
1004 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
1005 logger
.error(`${this.logPrefix()} ${errMsg}`);
1006 throw new BaseError(errMsg
);
1009 private initialize(): void {
1010 this.configurationFile
= path
.join(
1011 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
1012 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
1014 this.stationInfo
= this.getStationInfo();
1016 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1017 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1018 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1020 const patternGroup
: number | undefined =
1021 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1022 this.stationInfo
.firmwareVersion
?.split('.').length
;
1023 const match
= this.stationInfo
?.firmwareVersion
1024 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1025 ?.slice(1, patternGroup
+ 1);
1026 const patchLevelIndex
= match
.length
- 1;
1027 match
[patchLevelIndex
] = (
1028 Utils
.convertToInt(match
[patchLevelIndex
]) +
1029 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1031 this.stationInfo
.firmwareVersion
= match
?.join('.');
1033 this.saveStationInfo();
1034 // Avoid duplication of connectors related information in RAM
1035 delete this.stationInfo
?.Connectors
;
1036 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1037 if (this.getEnableStatistics() === true) {
1038 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1039 this.stationInfo
.hashId
,
1040 this.stationInfo
.chargingStationId
,
1041 this.configuredSupervisionUrl
1044 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1047 this.powerDivider
= this.getPowerDivider();
1048 // OCPP configuration
1049 this.ocppConfiguration
= this.getOcppConfiguration();
1050 this.initializeOcppConfiguration();
1051 this.initializeOcppServices();
1052 if (this.stationInfo
?.autoRegister
=== true) {
1053 this.bootNotificationResponse
= {
1054 currentTime
: new Date(),
1055 interval
: this.getHeartbeatInterval() / 1000,
1056 status: RegistrationStatusEnumType
.ACCEPTED
,
1061 private initializeOcppServices(): void {
1062 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1063 switch (ocppVersion
) {
1064 case OCPPVersion
.VERSION_16
:
1065 this.ocppIncomingRequestService
=
1066 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1067 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1068 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1071 case OCPPVersion
.VERSION_20
:
1072 case OCPPVersion
.VERSION_201
:
1073 this.ocppIncomingRequestService
=
1074 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1075 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1076 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1080 this.handleUnsupportedVersion(ocppVersion
);
1085 private initializeOcppConfiguration(): void {
1087 !ChargingStationConfigurationUtils
.getConfigurationKey(
1089 StandardParametersKey
.HeartbeatInterval
1092 ChargingStationConfigurationUtils
.addConfigurationKey(
1094 StandardParametersKey
.HeartbeatInterval
,
1099 !ChargingStationConfigurationUtils
.getConfigurationKey(
1101 StandardParametersKey
.HeartBeatInterval
1104 ChargingStationConfigurationUtils
.addConfigurationKey(
1106 StandardParametersKey
.HeartBeatInterval
,
1112 this.getSupervisionUrlOcppConfiguration() &&
1113 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1114 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1116 ChargingStationConfigurationUtils
.addConfigurationKey(
1118 this.getSupervisionUrlOcppKey(),
1119 this.configuredSupervisionUrl
.href
,
1123 !this.getSupervisionUrlOcppConfiguration() &&
1124 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1125 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1127 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1129 this.getSupervisionUrlOcppKey(),
1134 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1135 !ChargingStationConfigurationUtils
.getConfigurationKey(
1137 this.stationInfo
.amperageLimitationOcppKey
1140 ChargingStationConfigurationUtils
.addConfigurationKey(
1142 this.stationInfo
.amperageLimitationOcppKey
,
1144 this.stationInfo
.maximumAmperage
*
1145 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1150 !ChargingStationConfigurationUtils
.getConfigurationKey(
1152 StandardParametersKey
.SupportedFeatureProfiles
1155 ChargingStationConfigurationUtils
.addConfigurationKey(
1157 StandardParametersKey
.SupportedFeatureProfiles
,
1158 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1161 ChargingStationConfigurationUtils
.addConfigurationKey(
1163 StandardParametersKey
.NumberOfConnectors
,
1164 this.getNumberOfConnectors().toString(),
1169 !ChargingStationConfigurationUtils
.getConfigurationKey(
1171 StandardParametersKey
.MeterValuesSampledData
1174 ChargingStationConfigurationUtils
.addConfigurationKey(
1176 StandardParametersKey
.MeterValuesSampledData
,
1177 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1181 !ChargingStationConfigurationUtils
.getConfigurationKey(
1183 StandardParametersKey
.ConnectorPhaseRotation
1186 const connectorPhaseRotation
= [];
1187 for (const connectorId
of this.connectors
.keys()) {
1189 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1190 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1191 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1192 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1194 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1195 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1196 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1197 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1200 ChargingStationConfigurationUtils
.addConfigurationKey(
1202 StandardParametersKey
.ConnectorPhaseRotation
,
1203 connectorPhaseRotation
.toString()
1207 !ChargingStationConfigurationUtils
.getConfigurationKey(
1209 StandardParametersKey
.AuthorizeRemoteTxRequests
1212 ChargingStationConfigurationUtils
.addConfigurationKey(
1214 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1219 !ChargingStationConfigurationUtils
.getConfigurationKey(
1221 StandardParametersKey
.LocalAuthListEnabled
1223 ChargingStationConfigurationUtils
.getConfigurationKey(
1225 StandardParametersKey
.SupportedFeatureProfiles
1226 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1228 ChargingStationConfigurationUtils
.addConfigurationKey(
1230 StandardParametersKey
.LocalAuthListEnabled
,
1235 !ChargingStationConfigurationUtils
.getConfigurationKey(
1237 StandardParametersKey
.ConnectionTimeOut
1240 ChargingStationConfigurationUtils
.addConfigurationKey(
1242 StandardParametersKey
.ConnectionTimeOut
,
1243 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1246 this.saveOcppConfiguration();
1249 private initializeConnectors(
1250 stationInfo
: ChargingStationInfo
,
1251 configuredMaxConnectors
: number,
1252 templateMaxConnectors
: number
1254 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1255 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1256 logger
.error(`${this.logPrefix()} ${logMsg}`);
1257 throw new BaseError(logMsg
);
1259 if (!stationInfo
?.Connectors
[0]) {
1261 `${this.logPrefix()} Charging station information from template ${
1263 } with no connector Id 0 configuration`
1266 if (stationInfo
?.Connectors
) {
1267 const connectorsConfigHash
= crypto
1268 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1269 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1271 const connectorsConfigChanged
=
1272 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1273 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1274 connectorsConfigChanged
&& this.connectors
.clear();
1275 this.connectorsConfigurationHash
= connectorsConfigHash
;
1276 // Add connector Id 0
1277 let lastConnector
= '0';
1278 for (lastConnector
in stationInfo
?.Connectors
) {
1279 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1280 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1282 lastConnectorId
=== 0 &&
1283 this.getUseConnectorId0(stationInfo
) === true &&
1286 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1287 this.connectors
.set(
1289 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1291 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1292 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1293 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1297 // Generate all connectors
1298 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1299 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1300 const randConnectorId
= stationInfo
?.randomConnectors
1301 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1303 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1304 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1305 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1306 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1307 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1308 this.getConnectorStatus(index
).chargingProfiles
= [];
1315 `${this.logPrefix()} Charging station information from template ${
1317 } with no connectors configuration defined, using already defined connectors`
1320 // Initialize transaction attributes on connectors
1321 for (const connectorId
of this.connectors
.keys()) {
1322 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1324 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1325 this.getConnectorStatus(connectorId)?.transactionId
1331 (this.getConnectorStatus(connectorId
)?.transactionStarted
=== undefined ||
1332 this.getConnectorStatus(connectorId
)?.transactionStarted
=== null)
1334 this.initializeConnectorStatus(connectorId
);
1339 private checkStationInfoConnectorStatus(
1340 connectorId
: number,
1341 connectorStatus
: ConnectorStatus
1343 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1345 `${this.logPrefix()} Charging station information from template ${
1347 } with connector ${connectorId} status configuration defined, undefine it`
1349 delete connectorStatus
.status;
1353 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1354 let configuration
: ChargingStationConfiguration
| undefined;
1355 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1357 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1358 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1359 this.configurationFileHash
1362 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1363 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1364 configuration
= JSON
.parse(
1365 fs
.readFileSync(this.configurationFile
, 'utf8')
1366 ) as ChargingStationConfiguration
;
1367 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1368 this.configurationFileHash
= configuration
.configurationHash
;
1369 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1372 FileUtils
.handleFileException(
1373 this.configurationFile
,
1374 FileType
.ChargingStationConfiguration
,
1375 error
as NodeJS
.ErrnoException
,
1380 return configuration
;
1383 private saveConfiguration(): void {
1384 if (this.configurationFile
) {
1386 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1387 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1389 const configurationData
: ChargingStationConfiguration
=
1390 Utils
.cloneObject(this.getConfigurationFromFile()) ?? {};
1391 this.ocppConfiguration
?.configurationKey
&&
1392 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1393 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1394 delete configurationData
.configurationHash
;
1395 const configurationHash
= crypto
1396 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1397 .update(JSON
.stringify(configurationData
))
1399 if (this.configurationFileHash
!== configurationHash
) {
1400 configurationData
.configurationHash
= configurationHash
;
1401 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1402 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1403 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1404 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1405 fs
.closeSync(fileDescriptor
);
1406 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1407 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1408 this.configurationFileHash
= configurationHash
;
1409 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1412 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1413 this.configurationFile
1418 FileUtils
.handleFileException(
1419 this.configurationFile
,
1420 FileType
.ChargingStationConfiguration
,
1421 error
as NodeJS
.ErrnoException
,
1427 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1432 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1433 return this.getTemplateFromFile()?.Configuration
;
1436 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1437 let configuration
: ChargingStationConfiguration
| undefined;
1438 if (this.getOcppPersistentConfiguration() === true) {
1439 const configurationFromFile
= this.getConfigurationFromFile();
1440 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1442 if (!Utils
.isNullOrUndefined(configuration
)) {
1443 delete configuration
.stationInfo
;
1444 delete configuration
.configurationHash
;
1446 return configuration
;
1449 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1450 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1451 this.getOcppConfigurationFromFile();
1452 if (!ocppConfiguration
) {
1453 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1455 return ocppConfiguration
;
1458 private async onOpen(): Promise
<void> {
1459 if (this.isWebSocketConnectionOpened() === true) {
1461 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1463 if (this.isRegistered() === false) {
1464 // Send BootNotification
1465 let registrationRetryCount
= 0;
1467 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1468 BootNotificationRequest
,
1469 BootNotificationResponse
1470 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1471 skipBufferingOnError
: true,
1473 if (this.isRegistered() === false) {
1474 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1476 this?.bootNotificationResponse
?.interval
1477 ? this.bootNotificationResponse
.interval
* 1000
1478 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1482 this.isRegistered() === false &&
1483 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1484 this.getRegistrationMaxRetries() === -1)
1487 if (this.isRegistered() === true) {
1488 if (this.isInAcceptedState() === true) {
1489 await this.startMessageSequence();
1493 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1496 this.wsConnectionRestarted
= false;
1497 this.autoReconnectRetryCount
= 0;
1498 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1501 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1506 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1509 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1510 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1512 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1514 )}' and reason '${reason.toString()}'`
1516 this.autoReconnectRetryCount
= 0;
1521 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1523 )}' and reason '${reason.toString()}'`
1525 this.started
=== true && (await this.reconnect());
1528 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1531 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1532 const cachedRequest
= this.requests
.get(messageId
);
1533 if (Array.isArray(cachedRequest
) === true) {
1534 return cachedRequest
;
1536 throw new OCPPError(
1537 ErrorType
.PROTOCOL_ERROR
,
1538 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1540 )} is not an array`,
1542 cachedRequest
as JsonType
1546 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1547 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1548 if (this.getEnableStatistics() === true) {
1549 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1552 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1556 // Process the message
1557 await this.ocppIncomingRequestService
.incomingRequestHandler(
1565 private handleResponseMessage(response
: Response
): void {
1566 const [messageType
, messageId
, commandPayload
] = response
;
1567 if (this.requests
.has(messageId
) === false) {
1569 throw new OCPPError(
1570 ErrorType
.INTERNAL_ERROR
,
1571 `Response for unknown message id ${messageId}`,
1577 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1582 `${this.logPrefix()} << Command '${
1583 requestCommandName ?? Constants.UNKNOWN_COMMAND
1584 }' received response payload: ${JSON.stringify(response)}`
1586 responseCallback(commandPayload
, requestPayload
);
1589 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1590 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1591 if (this.requests
.has(messageId
) === false) {
1593 throw new OCPPError(
1594 ErrorType
.INTERNAL_ERROR
,
1595 `Error response for unknown message id ${messageId}`,
1597 { errorType
, errorMessage
, errorDetails
}
1600 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1602 `${this.logPrefix()} << Command '${
1603 requestCommandName ?? Constants.UNKNOWN_COMMAND
1604 }' received error response payload: ${JSON.stringify(errorResponse)}`
1606 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1609 private async onMessage(data
: RawData
): Promise
<void> {
1610 let request
: IncomingRequest
| Response
| ErrorResponse
;
1611 let messageType
: number;
1614 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1615 if (Array.isArray(request
) === true) {
1616 [messageType
] = request
;
1617 // Check the type of message
1618 switch (messageType
) {
1620 case MessageType
.CALL_MESSAGE
:
1621 await this.handleIncomingMessage(request
as IncomingRequest
);
1624 case MessageType
.CALL_RESULT_MESSAGE
:
1625 this.handleResponseMessage(request
as Response
);
1628 case MessageType
.CALL_ERROR_MESSAGE
:
1629 this.handleErrorMessage(request
as ErrorResponse
);
1633 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1634 errMsg
= `Wrong message type ${messageType}`;
1635 logger
.error(`${this.logPrefix()} ${errMsg}`);
1636 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1638 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1640 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1645 let commandName
: IncomingRequestCommand
;
1646 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1647 let errorCallback
: ErrorCallback
;
1648 const [, messageId
] = request
;
1649 switch (messageType
) {
1650 case MessageType
.CALL_MESSAGE
:
1651 [, , commandName
] = request
as IncomingRequest
;
1653 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1655 case MessageType
.CALL_RESULT_MESSAGE
:
1656 case MessageType
.CALL_ERROR_MESSAGE
:
1657 if (this.requests
.has(messageId
) === true) {
1658 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1659 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1660 errorCallback(error
as OCPPError
, false);
1662 // Remove the request from the cache in case of error at response handling
1663 this.requests
.delete(messageId
);
1667 if (error
instanceof OCPPError
=== false) {
1669 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1670 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1671 }' message '${data.toString()}' handling is not an OCPPError:`,
1676 `${this.logPrefix()} Incoming OCPP command '${
1677 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1678 }' message '${data.toString()}'${
1679 messageType !== MessageType.CALL_MESSAGE
1680 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1682 } processing error:`,
1688 private onPing(): void {
1689 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1692 private onPong(): void {
1693 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1696 private onError(error
: WSError
): void {
1697 this.closeWSConnection();
1698 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1701 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1702 if (this.getMeteringPerTransaction() === true) {
1705 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1706 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1711 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1712 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1716 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1717 const localStationInfo
= stationInfo
?? this.stationInfo
;
1718 return localStationInfo
?.useConnectorId0
?? true;
1721 private getNumberOfRunningTransactions(): number {
1723 for (const connectorId
of this.connectors
.keys()) {
1724 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1731 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1732 for (const connectorId
of this.connectors
.keys()) {
1733 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1734 await this.stopTransactionOnConnector(connectorId
, reason
);
1740 private getConnectionTimeout(): number {
1742 ChargingStationConfigurationUtils
.getConfigurationKey(
1744 StandardParametersKey
.ConnectionTimeOut
1749 ChargingStationConfigurationUtils
.getConfigurationKey(
1751 StandardParametersKey
.ConnectionTimeOut
1753 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1756 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1759 // -1 for unlimited, 0 for disabling
1760 private getAutoReconnectMaxRetries(): number | undefined {
1761 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1762 return this.stationInfo
.autoReconnectMaxRetries
;
1764 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1765 return Configuration
.getAutoReconnectMaxRetries();
1771 private getRegistrationMaxRetries(): number | undefined {
1772 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1773 return this.stationInfo
.registrationMaxRetries
;
1778 private getPowerDivider(): number {
1779 let powerDivider
= this.getNumberOfConnectors();
1780 if (this.stationInfo
?.powerSharedByConnectors
) {
1781 powerDivider
= this.getNumberOfRunningTransactions();
1783 return powerDivider
;
1786 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1787 const maximumPower
= this.getMaximumPower(stationInfo
);
1788 switch (this.getCurrentOutType(stationInfo
)) {
1789 case CurrentType
.AC
:
1790 return ACElectricUtils
.amperagePerPhaseFromPower(
1791 this.getNumberOfPhases(stationInfo
),
1792 maximumPower
/ this.getNumberOfConnectors(),
1793 this.getVoltageOut(stationInfo
)
1795 case CurrentType
.DC
:
1796 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1800 private getAmperageLimitation(): number | undefined {
1802 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1803 ChargingStationConfigurationUtils
.getConfigurationKey(
1805 this.stationInfo
.amperageLimitationOcppKey
1810 ChargingStationConfigurationUtils
.getConfigurationKey(
1812 this.stationInfo
.amperageLimitationOcppKey
1814 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1819 private async startMessageSequence(): Promise
<void> {
1820 if (this.stationInfo
?.autoRegister
=== true) {
1821 await this.ocppRequestService
.requestHandler
<
1822 BootNotificationRequest
,
1823 BootNotificationResponse
1824 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1825 skipBufferingOnError
: true,
1828 // Start WebSocket ping
1829 this.startWebSocketPing();
1831 this.startHeartbeat();
1832 // Initialize connectors status
1833 for (const connectorId
of this.connectors
.keys()) {
1834 let connectorStatus
: ConnectorStatusEnum
| undefined;
1835 if (connectorId
=== 0) {
1838 !this.getConnectorStatus(connectorId
)?.status &&
1839 (this.isChargingStationAvailable() === false ||
1840 this.isConnectorAvailable(connectorId
) === false)
1842 connectorStatus
= ConnectorStatusEnum
.Unavailable
;
1844 !this.getConnectorStatus(connectorId
)?.status &&
1845 this.getConnectorStatus(connectorId
)?.bootStatus
1847 // Set boot status in template at startup
1848 connectorStatus
= this.getConnectorStatus(connectorId
)?.bootStatus
;
1849 } else if (this.getConnectorStatus(connectorId
)?.status) {
1850 // Set previous status at startup
1851 connectorStatus
= this.getConnectorStatus(connectorId
)?.status;
1853 // Set default status
1854 connectorStatus
= ConnectorStatusEnum
.Available
;
1856 await this.ocppRequestService
.requestHandler
<
1857 StatusNotificationRequest
,
1858 StatusNotificationResponse
1861 RequestCommand
.STATUS_NOTIFICATION
,
1862 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1864 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1866 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1867 await this.ocppRequestService
.requestHandler
<
1868 FirmwareStatusNotificationRequest
,
1869 FirmwareStatusNotificationResponse
1870 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1871 status: FirmwareStatus
.Installed
,
1873 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1877 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1878 this.startAutomaticTransactionGenerator();
1880 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1883 private async stopMessageSequence(
1884 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1886 // Stop WebSocket ping
1887 this.stopWebSocketPing();
1889 this.stopHeartbeat();
1890 // Stop ongoing transactions
1891 if (this.automaticTransactionGenerator
?.started
=== true) {
1892 this.stopAutomaticTransactionGenerator();
1894 await this.stopRunningTransactions(reason
);
1896 for (const connectorId
of this.connectors
.keys()) {
1897 if (connectorId
> 0) {
1898 await this.ocppRequestService
.requestHandler
<
1899 StatusNotificationRequest
,
1900 StatusNotificationResponse
1903 RequestCommand
.STATUS_NOTIFICATION
,
1904 OCPPServiceUtils
.buildStatusNotificationRequest(
1907 ConnectorStatusEnum
.Unavailable
1910 delete this.getConnectorStatus(connectorId
)?.status;
1915 private startWebSocketPing(): void {
1916 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1918 StandardParametersKey
.WebSocketPingInterval
1920 ? Utils
.convertToInt(
1921 ChargingStationConfigurationUtils
.getConfigurationKey(
1923 StandardParametersKey
.WebSocketPingInterval
1927 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1928 this.webSocketPingSetInterval
= setInterval(() => {
1929 if (this.isWebSocketConnectionOpened() === true) {
1930 this.wsConnection
?.ping();
1932 }, webSocketPingInterval
* 1000);
1934 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1935 webSocketPingInterval
1938 } else if (this.webSocketPingSetInterval
) {
1940 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1941 webSocketPingInterval
1946 `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`
1951 private stopWebSocketPing(): void {
1952 if (this.webSocketPingSetInterval
) {
1953 clearInterval(this.webSocketPingSetInterval
);
1954 delete this.webSocketPingSetInterval
;
1958 private getConfiguredSupervisionUrl(): URL
{
1959 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
1960 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
1961 let configuredSupervisionUrlIndex
: number;
1962 switch (Configuration
.getSupervisionUrlDistribution()) {
1963 case SupervisionUrlDistribution
.RANDOM
:
1964 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1966 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1967 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1969 Object.values(SupervisionUrlDistribution
).includes(
1970 Configuration
.getSupervisionUrlDistribution()
1973 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1974 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1977 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1980 return new URL(supervisionUrls
[configuredSupervisionUrlIndex
]);
1982 return new URL(supervisionUrls
as string);
1985 private stopHeartbeat(): void {
1986 if (this.heartbeatSetInterval
) {
1987 clearInterval(this.heartbeatSetInterval
);
1988 delete this.heartbeatSetInterval
;
1992 private terminateWSConnection(): void {
1993 if (this.isWebSocketConnectionOpened() === true) {
1994 this.wsConnection
?.terminate();
1995 this.wsConnection
= null;
1999 private stopMeterValues(connectorId
: number) {
2000 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2001 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
2005 private getReconnectExponentialDelay(): boolean {
2006 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2009 private async reconnect(): Promise
<void> {
2010 // Stop WebSocket ping
2011 this.stopWebSocketPing();
2013 this.stopHeartbeat();
2014 // Stop the ATG if needed
2015 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2016 this.stopAutomaticTransactionGenerator();
2019 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2020 this.getAutoReconnectMaxRetries() === -1
2022 this.autoReconnectRetryCount
++;
2023 const reconnectDelay
= this.getReconnectExponentialDelay()
2024 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2025 : this.getConnectionTimeout() * 1000;
2026 const reconnectDelayWithdraw
= 1000;
2027 const reconnectTimeout
=
2028 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2029 ? reconnectDelay
- reconnectDelayWithdraw
2032 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2035 )}ms, timeout ${reconnectTimeout}ms`
2037 await Utils
.sleep(reconnectDelay
);
2039 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2041 this.openWSConnection(
2043 ...(this.stationInfo
?.wsOptions
?? {}),
2044 handshakeTimeout
: reconnectTimeout
,
2046 { closeOpened
: true }
2048 this.wsConnectionRestarted
= true;
2049 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2051 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2052 this.autoReconnectRetryCount
2053 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2058 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2059 | AutomaticTransactionGeneratorConfiguration
2061 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
2064 private initializeConnectorStatus(connectorId
: number): void {
2065 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2066 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2067 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2068 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2069 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2070 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;