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 authorizedTagsCache
: AuthorizedTagsCache
;
89 public stationInfo
!: ChargingStationInfo
;
90 public stopped
: boolean;
91 public readonly connectors
: Map
<number, ConnectorStatus
>;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly requests
: Map
<string, CachedRequest
>;
95 public performanceStatistics
!: PerformanceStatistics
;
96 public heartbeatSetInterval
!: NodeJS
.Timeout
;
97 public ocppRequestService
!: OCPPRequestService
;
98 public bootNotificationRequest
!: BootNotificationRequest
;
99 public bootNotificationResponse
!: BootNotificationResponse
| null;
100 public powerDivider
!: number;
101 private readonly index
: number;
102 private configurationFile
!: string;
103 private configurationFileHash
!: string;
104 private connectorsConfigurationHash
!: string;
105 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
106 private readonly messageBuffer
: Set
<string>;
107 private configuredSupervisionUrl
!: URL
;
108 private wsConnectionRestarted
: boolean;
109 private autoReconnectRetryCount
: number;
110 private templateFileWatcher
!: fs
.FSWatcher
;
111 private readonly sharedLRUCache
: SharedLRUCache
;
112 private automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
113 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
114 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
116 constructor(index
: number, templateFile
: string) {
118 this.templateFile
= templateFile
;
119 this.connectors
= new Map
<number, ConnectorStatus
>();
120 this.requests
= new Map
<string, CachedRequest
>();
121 this.messageBuffer
= new Set
<string>();
122 this.sharedLRUCache
= SharedLRUCache
.getInstance();
123 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
124 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
125 this.stopped
= false;
126 this.wsConnectionRestarted
= false;
127 this.autoReconnectRetryCount
= 0;
132 private get
wsConnectionUrl(): URL
{
134 (this.getSupervisionUrlOcppConfiguration()
135 ? ChargingStationConfigurationUtils
.getConfigurationKey(
137 this.getSupervisionUrlOcppKey()
139 : this.configuredSupervisionUrl
.href
) +
141 this.stationInfo
.chargingStationId
145 public logPrefix(): string {
146 return Utils
.logPrefix(
148 this?.stationInfo?.chargingStationId ??
149 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
154 public getRandomIdTag(): string {
155 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
156 const index
= Math.floor(
157 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
159 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
162 public hasAuthorizedTags(): boolean {
163 return !Utils
.isEmptyArray(
164 this.authorizedTagsCache
.getAuthorizedTags(
165 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
170 public getEnableStatistics(): boolean | undefined {
171 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
172 ? this.stationInfo
.enableStatistics
176 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
177 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
180 public getPayloadSchemaValidation(): boolean | undefined {
181 return this.stationInfo
.payloadSchemaValidation
?? true;
184 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
185 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
186 switch (this.getCurrentOutType(stationInfo
)) {
188 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
189 ? localStationInfo
.numberOfPhases
196 public isWebSocketConnectionOpened(): boolean {
197 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
200 public getRegistrationStatus(): RegistrationStatus
{
201 return this?.bootNotificationResponse
?.status;
204 public isInUnknownState(): boolean {
205 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
208 public isInPendingState(): boolean {
209 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
212 public isInAcceptedState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
216 public isInRejectedState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
220 public isRegistered(): boolean {
221 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
224 public isChargingStationAvailable(): boolean {
225 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
228 public isConnectorAvailable(id
: number): boolean {
229 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
232 public getNumberOfConnectors(): number {
233 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
236 public getConnectorStatus(id
: number): ConnectorStatus
{
237 return this.connectors
.get(id
);
240 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
241 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
244 public getOcppStrictCompliance(): boolean {
245 return this.stationInfo
?.ocppStrictCompliance
?? false;
248 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
249 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
250 this.getCurrentOutType(stationInfo
),
254 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
255 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
256 ? localStationInfo
.voltageOut
260 public getConnectorMaximumAvailablePower(connectorId
: number): number {
261 let connectorAmperageLimitationPowerLimit
: number;
263 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
264 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
266 connectorAmperageLimitationPowerLimit
=
267 (this.getCurrentOutType() === CurrentType
.AC
268 ? ACElectricUtils
.powerTotal(
269 this.getNumberOfPhases(),
270 this.getVoltageOut(),
271 this.getAmperageLimitation() * this.getNumberOfConnectors()
273 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
276 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
277 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
279 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
280 isNaN(connectorAmperageLimitationPowerLimit
)
282 : connectorAmperageLimitationPowerLimit
,
283 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
287 public getTransactionIdTag(transactionId
: number): string | undefined {
288 for (const connectorId
of this.connectors
.keys()) {
289 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
290 return this.getConnectorStatus(connectorId
).transactionIdTag
;
295 public getOutOfOrderEndMeterValues(): boolean {
296 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
299 public getBeginEndMeterValues(): boolean {
300 return this.stationInfo
?.beginEndMeterValues
?? false;
303 public getMeteringPerTransaction(): boolean {
304 return this.stationInfo
?.meteringPerTransaction
?? true;
307 public getTransactionDataMeterValues(): boolean {
308 return this.stationInfo
?.transactionDataMeterValues
?? false;
311 public getMainVoltageMeterValues(): boolean {
312 return this.stationInfo
?.mainVoltageMeterValues
?? true;
315 public getPhaseLineToLineVoltageMeterValues(): boolean {
316 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
319 public getCustomValueLimitationMeterValues(): boolean {
320 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
323 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
324 for (const connectorId
of this.connectors
.keys()) {
327 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
334 public getEnergyActiveImportRegisterByTransactionId(
335 transactionId
: number,
338 return this.getEnergyActiveImportRegister(
339 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
344 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
345 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
348 public getAuthorizeRemoteTxRequests(): boolean {
349 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.AuthorizeRemoteTxRequests
353 return authorizeRemoteTxRequests
354 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
358 public getLocalAuthListEnabled(): boolean {
359 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
361 StandardParametersKey
.LocalAuthListEnabled
363 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
366 public startHeartbeat(): void {
368 this.getHeartbeatInterval() &&
369 this.getHeartbeatInterval() > 0 &&
370 !this.heartbeatSetInterval
372 // eslint-disable-next-line @typescript-eslint/no-misused-promises
373 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
374 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
376 RequestCommand
.HEARTBEAT
378 }, this.getHeartbeatInterval());
381 ' Heartbeat started every ' +
382 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
384 } else if (this.heartbeatSetInterval
) {
387 ' Heartbeat already started every ' +
388 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
392 `${this.logPrefix()} Heartbeat interval set to ${
393 this.getHeartbeatInterval()
394 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
395 : this.getHeartbeatInterval()
396 }, not starting the heartbeat`
401 public restartHeartbeat(): void {
403 this.stopHeartbeat();
405 this.startHeartbeat();
408 public restartWebSocketPing(): void {
409 // Stop WebSocket ping
410 this.stopWebSocketPing();
411 // Start WebSocket ping
412 this.startWebSocketPing();
415 public startMeterValues(connectorId
: number, interval
: number): void {
416 if (connectorId
=== 0) {
418 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
422 if (!this.getConnectorStatus(connectorId
)) {
424 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
428 if (!this.getConnectorStatus(connectorId
)?.transactionStarted
) {
430 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
434 this.getConnectorStatus(connectorId
)?.transactionStarted
&&
435 !this.getConnectorStatus(connectorId
)?.transactionId
438 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
443 // eslint-disable-next-line @typescript-eslint/no-misused-promises
444 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
445 // eslint-disable-next-line @typescript-eslint/no-misused-promises
446 async (): Promise
<void> => {
447 // FIXME: Implement OCPP version agnostic helpers
448 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
451 this.getConnectorStatus(connectorId
).transactionId
,
454 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
456 RequestCommand
.METER_VALUES
,
459 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
460 meterValue
: [meterValue
],
468 `${this.logPrefix()} Charging station ${
469 StandardParametersKey.MeterValueSampleInterval
470 } configuration set to ${
471 interval ? Utils.formatDurationMilliSeconds(interval) : interval
472 }, not sending MeterValues`
477 public start(): void {
478 if (this.getEnableStatistics()) {
479 this.performanceStatistics
.start();
481 this.openWSConnection();
482 // Monitor charging station template file
483 this.templateFileWatcher
= FileUtils
.watchJsonFile(
485 FileType
.ChargingStationTemplate
,
488 (event
, filename
): void => {
489 if (filename
&& event
=== 'change') {
492 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
494 } file have changed, reload`
496 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
500 this.stopAutomaticTransactionGenerator();
501 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
502 this.startAutomaticTransactionGenerator();
504 if (this.getEnableStatistics()) {
505 this.performanceStatistics
.restart();
507 this.performanceStatistics
.stop();
509 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
512 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
519 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
522 public async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
523 // Stop message sequence
524 await this.stopMessageSequence(reason
);
525 for (const connectorId
of this.connectors
.keys()) {
526 if (connectorId
> 0) {
527 await this.ocppRequestService
.requestHandler
<
528 StatusNotificationRequest
,
529 StatusNotificationResponse
530 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
532 status: ChargePointStatus
.UNAVAILABLE
,
533 errorCode
: ChargePointErrorCode
.NO_ERROR
,
535 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
538 this.closeWSConnection();
539 if (this.getEnableStatistics()) {
540 this.performanceStatistics
.stop();
542 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
543 this.templateFileWatcher
.close();
544 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
545 this.bootNotificationResponse
= null;
547 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
550 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
551 await this.stop(reason
);
552 await Utils
.sleep(this.stationInfo
.resetTime
);
557 public saveOcppConfiguration(): void {
558 if (this.getOcppPersistentConfiguration()) {
559 this.saveConfiguration();
563 public getChargingProfilePowerLimit(connectorId
: number): number | undefined {
564 let limit
: number, matchingChargingProfile
: ChargingProfile
;
565 let chargingProfiles
: ChargingProfile
[] = [];
566 // Get charging profiles for connector and sort by stack level
567 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
568 (a
, b
) => b
.stackLevel
- a
.stackLevel
570 // Get profiles on connector 0
571 if (this.getConnectorStatus(0).chargingProfiles
) {
572 chargingProfiles
.push(
573 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
576 if (!Utils
.isEmptyArray(chargingProfiles
)) {
577 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
581 if (!Utils
.isNullOrUndefined(result
)) {
582 limit
= result
.limit
;
583 matchingChargingProfile
= result
.matchingChargingProfile
;
584 switch (this.getCurrentOutType()) {
587 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
588 ChargingRateUnitType
.WATT
590 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
594 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
595 ChargingRateUnitType
.WATT
597 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
600 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
601 if (limit
> connectorMaximumPower
) {
603 `${this.logPrefix()} Charging profile id ${
604 matchingChargingProfile.chargingProfileId
605 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
606 this.getConnectorStatus(connectorId
).chargingProfiles
608 limit
= connectorMaximumPower
;
615 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
616 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
618 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
620 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
622 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
624 `${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`
626 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
628 let cpReplaced
= false;
629 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
630 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
631 (chargingProfile
: ChargingProfile
, index
: number) => {
633 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
634 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
635 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
637 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
643 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
646 public resetConnectorStatus(connectorId
: number): void {
647 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
648 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
649 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
650 this.getConnectorStatus(connectorId
).transactionStarted
= false;
651 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
652 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
653 delete this.getConnectorStatus(connectorId
).transactionId
;
654 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
655 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
656 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
657 this.stopMeterValues(connectorId
);
660 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
661 return ChargingStationConfigurationUtils
.getConfigurationKey(
663 StandardParametersKey
.SupportedFeatureProfiles
664 )?.value
.includes(featureProfile
);
667 public bufferMessage(message
: string): void {
668 this.messageBuffer
.add(message
);
671 public openWSConnection(
672 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
673 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
675 terminateOpened
: false,
678 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
679 params
.closeOpened
= params
?.closeOpened
?? false;
680 params
.terminateOpened
= params
?.terminateOpened
?? false;
682 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
683 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
685 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
687 if (params
?.closeOpened
) {
688 this.closeWSConnection();
690 if (params
?.terminateOpened
) {
691 this.terminateWSConnection();
693 let protocol
: string;
694 switch (this.getOcppVersion()) {
695 case OCPPVersion
.VERSION_16
:
696 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
699 this.handleUnsupportedVersion(this.getOcppVersion());
703 if (this.isWebSocketConnectionOpened()) {
705 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
711 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
714 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
716 // Handle WebSocket message
717 this.wsConnection
.on(
719 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
721 // Handle WebSocket error
722 this.wsConnection
.on(
724 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
726 // Handle WebSocket close
727 this.wsConnection
.on(
729 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
731 // Handle WebSocket open
732 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
733 // Handle WebSocket ping
734 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
735 // Handle WebSocket pong
736 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
739 public closeWSConnection(): void {
740 if (this.isWebSocketConnectionOpened()) {
741 this.wsConnection
.close();
742 this.wsConnection
= null;
746 public startAutomaticTransactionGenerator(): void {
747 if (!this.automaticTransactionGenerator
) {
748 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
749 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
753 if (!this.automaticTransactionGenerator
.started
) {
754 this.automaticTransactionGenerator
.start();
758 public stopAutomaticTransactionGenerator(): void {
759 if (this.automaticTransactionGenerator
?.started
) {
760 this.automaticTransactionGenerator
.stop();
761 this.automaticTransactionGenerator
= null;
765 private flushMessageBuffer(): void {
766 if (this.messageBuffer
.size
> 0) {
767 this.messageBuffer
.forEach((message
) => {
768 // TODO: evaluate the need to track performance
769 this.wsConnection
.send(message
);
770 this.messageBuffer
.delete(message
);
775 private getSupervisionUrlOcppConfiguration(): boolean {
776 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
779 private getSupervisionUrlOcppKey(): string {
780 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
783 private getTemplateFromFile(): ChargingStationTemplate
| null {
784 let template
: ChargingStationTemplate
= null;
786 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
787 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
789 const measureId
= `${FileType.ChargingStationTemplate} read`;
790 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
791 template
= JSON
.parse(
792 fs
.readFileSync(this.templateFile
, 'utf8')
793 ) as ChargingStationTemplate
;
794 PerformanceStatistics
.endMeasure(measureId
, beginId
);
795 template
.templateHash
= crypto
796 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
797 .update(JSON
.stringify(template
))
799 this.sharedLRUCache
.setChargingStationTemplate(template
);
802 FileUtils
.handleFileException(
804 FileType
.ChargingStationTemplate
,
806 error
as NodeJS
.ErrnoException
812 private getStationInfoFromTemplate(): ChargingStationInfo
{
813 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
814 if (Utils
.isNullOrUndefined(stationTemplate
)) {
815 const errorMsg
= 'Failed to read charging station template file';
816 logger
.error(`${this.logPrefix()} ${errorMsg}`);
817 throw new BaseError(errorMsg
);
819 if (Utils
.isEmptyObject(stationTemplate
)) {
820 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
821 logger
.error(`${this.logPrefix()} ${errorMsg}`);
822 throw new BaseError(errorMsg
);
824 // Deprecation template keys section
825 ChargingStationUtils
.warnDeprecatedTemplateKey(
830 "Use 'supervisionUrls' instead"
832 ChargingStationUtils
.convertDeprecatedTemplateKey(
837 const stationInfo
: ChargingStationInfo
=
838 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
839 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
840 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
844 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
845 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
846 stationTemplate
.power
= stationTemplate
.power
as number[];
847 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
848 stationInfo
.maximumPower
=
849 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
850 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
851 : stationTemplate
.power
[powerArrayRandomIndex
];
853 stationTemplate
.power
= stationTemplate
.power
as number;
854 stationInfo
.maximumPower
=
855 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
856 ? stationTemplate
.power
* 1000
857 : stationTemplate
.power
;
859 stationInfo
.resetTime
= stationTemplate
.resetTime
860 ? stationTemplate
.resetTime
* 1000
861 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
862 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
866 ChargingStationUtils
.checkConfiguredMaxConnectors(
867 configuredMaxConnectors
,
871 const templateMaxConnectors
=
872 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
873 ChargingStationUtils
.checkTemplateMaxConnectors(
874 templateMaxConnectors
,
879 configuredMaxConnectors
>
880 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
881 !stationTemplate
?.randomConnectors
884 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
886 }, forcing random connector configurations affectation`
888 stationInfo
.randomConnectors
= true;
890 // Build connectors if needed (FIXME: should be factored out)
891 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
892 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
893 ChargingStationUtils
.createStationInfoHash(stationInfo
);
897 private getStationInfoFromFile(): ChargingStationInfo
| null {
898 let stationInfo
: ChargingStationInfo
= null;
899 this.getStationInfoPersistentConfiguration() &&
900 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
901 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
905 private getStationInfo(): ChargingStationInfo
{
906 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
907 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
908 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
909 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
910 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
911 return this.stationInfo
;
913 return stationInfoFromFile
;
915 stationInfoFromFile
&&
916 ChargingStationUtils
.propagateSerialNumber(
917 this.getTemplateFromFile(),
919 stationInfoFromTemplate
921 return stationInfoFromTemplate
;
924 private saveStationInfo(): void {
925 if (this.getStationInfoPersistentConfiguration()) {
926 this.saveConfiguration();
930 private getOcppVersion(): OCPPVersion
{
931 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
934 private getOcppPersistentConfiguration(): boolean {
935 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
938 private getStationInfoPersistentConfiguration(): boolean {
939 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
942 private handleUnsupportedVersion(version
: OCPPVersion
) {
943 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
944 logger
.error(`${this.logPrefix()} ${errMsg}`);
945 throw new BaseError(errMsg
);
948 private initialize(): void {
949 this.configurationFile
= path
.join(
950 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
951 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
953 this.stationInfo
= this.getStationInfo();
954 this.saveStationInfo();
955 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
956 // Avoid duplication of connectors related information in RAM
957 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
958 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
959 if (this.getEnableStatistics()) {
960 this.performanceStatistics
= PerformanceStatistics
.getInstance(
961 this.stationInfo
.hashId
,
962 this.stationInfo
.chargingStationId
,
963 this.configuredSupervisionUrl
966 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
969 this.powerDivider
= this.getPowerDivider();
970 // OCPP configuration
971 this.ocppConfiguration
= this.getOcppConfiguration();
972 this.initializeOcppConfiguration();
973 switch (this.getOcppVersion()) {
974 case OCPPVersion
.VERSION_16
:
975 this.ocppIncomingRequestService
=
976 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
977 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
978 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
982 this.handleUnsupportedVersion(this.getOcppVersion());
985 if (this.stationInfo
?.autoRegister
) {
986 this.bootNotificationResponse
= {
987 currentTime
: new Date().toISOString(),
988 interval
: this.getHeartbeatInterval() / 1000,
989 status: RegistrationStatus
.ACCEPTED
,
994 private initializeOcppConfiguration(): void {
996 !ChargingStationConfigurationUtils
.getConfigurationKey(
998 StandardParametersKey
.HeartbeatInterval
1001 ChargingStationConfigurationUtils
.addConfigurationKey(
1003 StandardParametersKey
.HeartbeatInterval
,
1008 !ChargingStationConfigurationUtils
.getConfigurationKey(
1010 StandardParametersKey
.HeartBeatInterval
1013 ChargingStationConfigurationUtils
.addConfigurationKey(
1015 StandardParametersKey
.HeartBeatInterval
,
1021 this.getSupervisionUrlOcppConfiguration() &&
1022 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1024 ChargingStationConfigurationUtils
.addConfigurationKey(
1026 this.getSupervisionUrlOcppKey(),
1027 this.configuredSupervisionUrl
.href
,
1031 !this.getSupervisionUrlOcppConfiguration() &&
1032 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1034 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1036 this.getSupervisionUrlOcppKey(),
1041 this.stationInfo
.amperageLimitationOcppKey
&&
1042 !ChargingStationConfigurationUtils
.getConfigurationKey(
1044 this.stationInfo
.amperageLimitationOcppKey
1047 ChargingStationConfigurationUtils
.addConfigurationKey(
1049 this.stationInfo
.amperageLimitationOcppKey
,
1051 this.stationInfo
.maximumAmperage
*
1052 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1057 !ChargingStationConfigurationUtils
.getConfigurationKey(
1059 StandardParametersKey
.SupportedFeatureProfiles
1062 ChargingStationConfigurationUtils
.addConfigurationKey(
1064 StandardParametersKey
.SupportedFeatureProfiles
,
1065 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1068 ChargingStationConfigurationUtils
.addConfigurationKey(
1070 StandardParametersKey
.NumberOfConnectors
,
1071 this.getNumberOfConnectors().toString(),
1076 !ChargingStationConfigurationUtils
.getConfigurationKey(
1078 StandardParametersKey
.MeterValuesSampledData
1081 ChargingStationConfigurationUtils
.addConfigurationKey(
1083 StandardParametersKey
.MeterValuesSampledData
,
1084 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1088 !ChargingStationConfigurationUtils
.getConfigurationKey(
1090 StandardParametersKey
.ConnectorPhaseRotation
1093 const connectorPhaseRotation
= [];
1094 for (const connectorId
of this.connectors
.keys()) {
1096 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1097 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1098 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1099 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1101 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1102 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1103 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1104 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1107 ChargingStationConfigurationUtils
.addConfigurationKey(
1109 StandardParametersKey
.ConnectorPhaseRotation
,
1110 connectorPhaseRotation
.toString()
1114 !ChargingStationConfigurationUtils
.getConfigurationKey(
1116 StandardParametersKey
.AuthorizeRemoteTxRequests
1119 ChargingStationConfigurationUtils
.addConfigurationKey(
1121 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1126 !ChargingStationConfigurationUtils
.getConfigurationKey(
1128 StandardParametersKey
.LocalAuthListEnabled
1130 ChargingStationConfigurationUtils
.getConfigurationKey(
1132 StandardParametersKey
.SupportedFeatureProfiles
1133 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1135 ChargingStationConfigurationUtils
.addConfigurationKey(
1137 StandardParametersKey
.LocalAuthListEnabled
,
1142 !ChargingStationConfigurationUtils
.getConfigurationKey(
1144 StandardParametersKey
.ConnectionTimeOut
1147 ChargingStationConfigurationUtils
.addConfigurationKey(
1149 StandardParametersKey
.ConnectionTimeOut
,
1150 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1153 this.saveOcppConfiguration();
1156 private initializeConnectors(
1157 stationInfo
: ChargingStationInfo
,
1158 configuredMaxConnectors
: number,
1159 templateMaxConnectors
: number
1161 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1162 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1163 logger
.error(`${this.logPrefix()} ${logMsg}`);
1164 throw new BaseError(logMsg
);
1166 if (!stationInfo
?.Connectors
[0]) {
1168 `${this.logPrefix()} Charging station information from template ${
1170 } with no connector Id 0 configuration`
1173 if (stationInfo
?.Connectors
) {
1174 const connectorsConfigHash
= crypto
1175 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1176 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1178 const connectorsConfigChanged
=
1179 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1180 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1181 connectorsConfigChanged
&& this.connectors
.clear();
1182 this.connectorsConfigurationHash
= connectorsConfigHash
;
1183 // Add connector Id 0
1184 let lastConnector
= '0';
1185 for (lastConnector
in stationInfo
?.Connectors
) {
1186 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1188 lastConnectorId
=== 0 &&
1189 this.getUseConnectorId0(stationInfo
) &&
1190 stationInfo
?.Connectors
[lastConnector
]
1192 this.connectors
.set(
1194 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1196 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1197 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1198 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1202 // Generate all connectors
1203 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1204 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1205 const randConnectorId
= stationInfo
?.randomConnectors
1206 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1208 this.connectors
.set(
1210 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1212 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1213 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1214 this.getConnectorStatus(index
).chargingProfiles
= [];
1221 `${this.logPrefix()} Charging station information from template ${
1223 } with no connectors configuration defined, using already defined connectors`
1226 // Initialize transaction attributes on connectors
1227 for (const connectorId
of this.connectors
.keys()) {
1228 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1229 this.initializeConnectorStatus(connectorId
);
1234 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1235 let configuration
: ChargingStationConfiguration
= null;
1236 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1238 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1239 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1240 this.configurationFileHash
1243 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1244 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1245 configuration
= JSON
.parse(
1246 fs
.readFileSync(this.configurationFile
, 'utf8')
1247 ) as ChargingStationConfiguration
;
1248 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1249 this.configurationFileHash
= configuration
.configurationHash
;
1250 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1253 FileUtils
.handleFileException(
1255 FileType
.ChargingStationConfiguration
,
1256 this.configurationFile
,
1257 error
as NodeJS
.ErrnoException
1261 return configuration
;
1264 private saveConfiguration(): void {
1265 if (this.configurationFile
) {
1267 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1268 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1270 const configurationData
: ChargingStationConfiguration
=
1271 this.getConfigurationFromFile() ?? {};
1272 this.ocppConfiguration
?.configurationKey
&&
1273 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1274 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1275 delete configurationData
.configurationHash
;
1276 const configurationHash
= crypto
1277 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1278 .update(JSON
.stringify(configurationData
))
1280 if (this.configurationFileHash
!== configurationHash
) {
1281 configurationData
.configurationHash
= configurationHash
;
1282 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1283 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1284 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1285 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1286 fs
.closeSync(fileDescriptor
);
1287 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1288 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1289 this.configurationFileHash
= configurationHash
;
1290 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1293 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1294 this.configurationFile
1299 FileUtils
.handleFileException(
1301 FileType
.ChargingStationConfiguration
,
1302 this.configurationFile
,
1303 error
as NodeJS
.ErrnoException
1308 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1313 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1314 return this.getTemplateFromFile()?.Configuration
?? null;
1317 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1318 let configuration
: ChargingStationConfiguration
= null;
1319 if (this.getOcppPersistentConfiguration()) {
1320 const configurationFromFile
= this.getConfigurationFromFile();
1321 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1323 configuration
&& delete configuration
.stationInfo
;
1324 return configuration
;
1327 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1328 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1329 if (!ocppConfiguration
) {
1330 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1332 return ocppConfiguration
;
1335 private async onOpen(): Promise
<void> {
1336 if (this.isWebSocketConnectionOpened()) {
1338 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1340 if (!this.isRegistered()) {
1341 // Send BootNotification
1342 let registrationRetryCount
= 0;
1344 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1345 BootNotificationRequest
,
1346 BootNotificationResponse
1349 RequestCommand
.BOOT_NOTIFICATION
,
1351 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1352 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1353 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1354 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1355 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1356 iccid
: this.bootNotificationRequest
.iccid
,
1357 imsi
: this.bootNotificationRequest
.imsi
,
1358 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1359 meterType
: this.bootNotificationRequest
.meterType
,
1361 { skipBufferingOnError
: true }
1363 if (!this.isRegistered()) {
1364 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1366 this.bootNotificationResponse
?.interval
1367 ? this.bootNotificationResponse
.interval
* 1000
1368 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1372 !this.isRegistered() &&
1373 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1374 this.getRegistrationMaxRetries() === -1)
1377 if (this.isRegistered()) {
1378 if (this.isInAcceptedState()) {
1379 await this.startMessageSequence();
1380 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1384 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1387 this.stopped
&& (this.stopped
= false);
1388 this.autoReconnectRetryCount
= 0;
1389 this.wsConnectionRestarted
= false;
1392 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1397 private async onClose(code
: number, reason
: string): Promise
<void> {
1400 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1401 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1403 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1405 )}' and reason '${reason}'`
1407 this.autoReconnectRetryCount
= 0;
1412 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1414 )}' and reason '${reason}'`
1416 await this.reconnect(code
);
1421 private async onMessage(data
: Data
): Promise
<void> {
1422 let messageType
: number;
1423 let messageId
: string;
1424 let commandName
: IncomingRequestCommand
;
1425 let commandPayload
: JsonType
;
1426 let errorType
: ErrorType
;
1427 let errorMessage
: string;
1428 let errorDetails
: JsonType
;
1429 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1430 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1431 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1432 let requestPayload
: JsonType
;
1433 let cachedRequest
: CachedRequest
;
1436 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1437 if (Array.isArray(request
) === true) {
1438 [messageType
, messageId
] = request
;
1439 // Check the type of message
1440 switch (messageType
) {
1442 case MessageType
.CALL_MESSAGE
:
1443 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1444 if (this.getEnableStatistics()) {
1445 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1448 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1452 // Process the message
1453 await this.ocppIncomingRequestService
.incomingRequestHandler(
1461 case MessageType
.CALL_RESULT_MESSAGE
:
1462 [, , commandPayload
] = request
as Response
;
1463 if (!this.requests
.has(messageId
)) {
1465 throw new OCPPError(
1466 ErrorType
.INTERNAL_ERROR
,
1467 `Response for unknown message id ${messageId}`,
1473 cachedRequest
= this.requests
.get(messageId
);
1474 if (Array.isArray(cachedRequest
) === true) {
1475 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1477 throw new OCPPError(
1478 ErrorType
.PROTOCOL_ERROR
,
1479 `Cached request for message id ${messageId} response is not an array`,
1481 cachedRequest
as unknown
as JsonType
1485 `${this.logPrefix()} << Command '${
1486 requestCommandName ?? 'unknown'
1487 }' received response payload: ${JSON.stringify(request)}`
1489 responseCallback(commandPayload
, requestPayload
);
1492 case MessageType
.CALL_ERROR_MESSAGE
:
1493 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1494 if (!this.requests
.has(messageId
)) {
1496 throw new OCPPError(
1497 ErrorType
.INTERNAL_ERROR
,
1498 `Error response for unknown message id ${messageId}`,
1500 { errorType
, errorMessage
, errorDetails
}
1503 cachedRequest
= this.requests
.get(messageId
);
1504 if (Array.isArray(cachedRequest
) === true) {
1505 [, errorCallback
, requestCommandName
] = cachedRequest
;
1507 throw new OCPPError(
1508 ErrorType
.PROTOCOL_ERROR
,
1509 `Cached request for message id ${messageId} error response is not an array`,
1511 cachedRequest
as unknown
as JsonType
1515 `${this.logPrefix()} << Command '${
1516 requestCommandName ?? 'unknown'
1517 }' received error payload: ${JSON.stringify(request)}`
1519 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1523 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1524 errMsg
= `Wrong message type ${messageType}`;
1525 logger
.error(`${this.logPrefix()} ${errMsg}`);
1526 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1528 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1530 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1537 `${this.logPrefix()} Incoming OCPP command '${
1538 commandName ?? requestCommandName ?? null
1539 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1540 this.requests.get(messageId)
1541 )}' processing error:`,
1544 if (!(error
instanceof OCPPError
)) {
1546 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1547 commandName ?? requestCommandName ?? null
1548 }' message '${data.toString()}' handling is not an OCPPError:`,
1553 messageType
=== MessageType
.CALL_MESSAGE
&&
1554 (await this.ocppRequestService
.sendError(
1558 commandName
?? requestCommandName
?? null
1563 private onPing(): void {
1564 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1567 private onPong(): void {
1568 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1571 private onError(error
: WSError
): void {
1572 this.closeWSConnection();
1573 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1576 private getEnergyActiveImportRegister(
1577 connectorStatus
: ConnectorStatus
,
1580 if (this.getMeteringPerTransaction()) {
1583 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1584 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1589 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1590 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1594 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1595 const localStationInfo
= stationInfo
?? this.stationInfo
;
1596 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1597 ? localStationInfo
.useConnectorId0
1601 private getNumberOfRunningTransactions(): number {
1603 for (const connectorId
of this.connectors
.keys()) {
1604 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1612 private getConnectionTimeout(): number | undefined {
1614 ChargingStationConfigurationUtils
.getConfigurationKey(
1616 StandardParametersKey
.ConnectionTimeOut
1621 ChargingStationConfigurationUtils
.getConfigurationKey(
1623 StandardParametersKey
.ConnectionTimeOut
1625 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1628 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1631 // -1 for unlimited, 0 for disabling
1632 private getAutoReconnectMaxRetries(): number | undefined {
1633 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1634 return this.stationInfo
.autoReconnectMaxRetries
;
1636 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1637 return Configuration
.getAutoReconnectMaxRetries();
1643 private getRegistrationMaxRetries(): number | undefined {
1644 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1645 return this.stationInfo
.registrationMaxRetries
;
1650 private getPowerDivider(): number {
1651 let powerDivider
= this.getNumberOfConnectors();
1652 if (this.stationInfo
?.powerSharedByConnectors
) {
1653 powerDivider
= this.getNumberOfRunningTransactions();
1655 return powerDivider
;
1658 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1659 const localStationInfo
= stationInfo
?? this.stationInfo
;
1660 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1663 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1664 const maximumPower
= this.getMaximumPower(stationInfo
);
1665 switch (this.getCurrentOutType(stationInfo
)) {
1666 case CurrentType
.AC
:
1667 return ACElectricUtils
.amperagePerPhaseFromPower(
1668 this.getNumberOfPhases(stationInfo
),
1669 maximumPower
/ this.getNumberOfConnectors(),
1670 this.getVoltageOut(stationInfo
)
1672 case CurrentType
.DC
:
1673 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1677 private getAmperageLimitation(): number | undefined {
1679 this.stationInfo
.amperageLimitationOcppKey
&&
1680 ChargingStationConfigurationUtils
.getConfigurationKey(
1682 this.stationInfo
.amperageLimitationOcppKey
1687 ChargingStationConfigurationUtils
.getConfigurationKey(
1689 this.stationInfo
.amperageLimitationOcppKey
1691 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1696 private async startMessageSequence(): Promise
<void> {
1697 if (this.stationInfo
?.autoRegister
) {
1698 await this.ocppRequestService
.requestHandler
<
1699 BootNotificationRequest
,
1700 BootNotificationResponse
1703 RequestCommand
.BOOT_NOTIFICATION
,
1705 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1706 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1707 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1708 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1709 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1710 iccid
: this.bootNotificationRequest
.iccid
,
1711 imsi
: this.bootNotificationRequest
.imsi
,
1712 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1713 meterType
: this.bootNotificationRequest
.meterType
,
1715 { skipBufferingOnError
: true }
1718 // Start WebSocket ping
1719 this.startWebSocketPing();
1721 this.startHeartbeat();
1722 // Initialize connectors status
1723 for (const connectorId
of this.connectors
.keys()) {
1724 if (connectorId
=== 0) {
1728 !this.getConnectorStatus(connectorId
)?.status &&
1729 this.getConnectorStatus(connectorId
)?.bootStatus
1731 // Send status in template at startup
1732 await this.ocppRequestService
.requestHandler
<
1733 StatusNotificationRequest
,
1734 StatusNotificationResponse
1735 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1737 status: this.getConnectorStatus(connectorId
).bootStatus
,
1738 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1740 this.getConnectorStatus(connectorId
).status =
1741 this.getConnectorStatus(connectorId
).bootStatus
;
1744 this.getConnectorStatus(connectorId
)?.status &&
1745 this.getConnectorStatus(connectorId
)?.bootStatus
1747 // Send status in template after reset
1748 await this.ocppRequestService
.requestHandler
<
1749 StatusNotificationRequest
,
1750 StatusNotificationResponse
1751 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1753 status: this.getConnectorStatus(connectorId
).bootStatus
,
1754 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1756 this.getConnectorStatus(connectorId
).status =
1757 this.getConnectorStatus(connectorId
).bootStatus
;
1758 } else if (!this.stopped
&& this.getConnectorStatus(connectorId
)?.status) {
1759 // Send previous status at template reload
1760 await this.ocppRequestService
.requestHandler
<
1761 StatusNotificationRequest
,
1762 StatusNotificationResponse
1763 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1765 status: this.getConnectorStatus(connectorId
).status,
1766 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1769 // Send default status
1770 await this.ocppRequestService
.requestHandler
<
1771 StatusNotificationRequest
,
1772 StatusNotificationResponse
1773 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1775 status: ChargePointStatus
.AVAILABLE
,
1776 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1778 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1782 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1783 this.startAutomaticTransactionGenerator();
1787 private async stopMessageSequence(
1788 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1790 // Stop WebSocket ping
1791 this.stopWebSocketPing();
1793 this.stopHeartbeat();
1794 // Stop ongoing transactions
1795 if (this.getNumberOfRunningTransactions() > 0) {
1796 if (this.automaticTransactionGenerator
?.started
) {
1797 this.stopAutomaticTransactionGenerator();
1799 for (const connectorId
of this.connectors
.keys()) {
1800 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1801 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1803 this.getBeginEndMeterValues() &&
1804 this.getOcppStrictCompliance() &&
1805 !this.getOutOfOrderEndMeterValues()
1807 // FIXME: Implement OCPP version agnostic helpers
1808 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1811 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1813 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1815 RequestCommand
.METER_VALUES
,
1819 meterValue
: [transactionEndMeterValue
],
1823 await this.ocppRequestService
.requestHandler
<
1824 StopTransactionRequest
,
1825 StopTransactionResponse
1826 >(this, RequestCommand
.STOP_TRANSACTION
, {
1828 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
1829 idTag
: this.getTransactionIdTag(transactionId
),
1838 private startWebSocketPing(): void {
1839 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1841 StandardParametersKey
.WebSocketPingInterval
1843 ? Utils
.convertToInt(
1844 ChargingStationConfigurationUtils
.getConfigurationKey(
1846 StandardParametersKey
.WebSocketPingInterval
1850 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1851 this.webSocketPingSetInterval
= setInterval(() => {
1852 if (this.isWebSocketConnectionOpened()) {
1853 this.wsConnection
.ping((): void => {
1854 /* This is intentional */
1857 }, webSocketPingInterval
* 1000);
1860 ' WebSocket ping started every ' +
1861 Utils
.formatDurationSeconds(webSocketPingInterval
)
1863 } else if (this.webSocketPingSetInterval
) {
1866 ' WebSocket ping every ' +
1867 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1872 `${this.logPrefix()} WebSocket ping interval set to ${
1873 webSocketPingInterval
1874 ? Utils.formatDurationSeconds(webSocketPingInterval)
1875 : webSocketPingInterval
1876 }, not starting the WebSocket ping`
1881 private stopWebSocketPing(): void {
1882 if (this.webSocketPingSetInterval
) {
1883 clearInterval(this.webSocketPingSetInterval
);
1887 private getConfiguredSupervisionUrl(): URL
{
1888 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1889 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1891 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1893 switch (Configuration
.getSupervisionUrlDistribution()) {
1894 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1895 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1897 case SupervisionUrlDistribution
.RANDOM
:
1899 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1901 case SupervisionUrlDistribution
.SEQUENTIAL
:
1902 if (this.index
<= supervisionUrls
.length
) {
1903 urlIndex
= this.index
- 1;
1906 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1912 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1913 SupervisionUrlDistribution.ROUND_ROBIN
1916 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1919 return new URL(supervisionUrls
[urlIndex
]);
1921 return new URL(supervisionUrls
as string);
1924 private getHeartbeatInterval(): number | undefined {
1925 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1927 StandardParametersKey
.HeartbeatInterval
1929 if (HeartbeatInterval
) {
1930 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1932 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1934 StandardParametersKey
.HeartBeatInterval
1936 if (HeartBeatInterval
) {
1937 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1939 !this.stationInfo
?.autoRegister
&&
1941 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1942 Constants.DEFAULT_HEARTBEAT_INTERVAL
1945 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1948 private stopHeartbeat(): void {
1949 if (this.heartbeatSetInterval
) {
1950 clearInterval(this.heartbeatSetInterval
);
1954 private terminateWSConnection(): void {
1955 if (this.isWebSocketConnectionOpened()) {
1956 this.wsConnection
.terminate();
1957 this.wsConnection
= null;
1961 private stopMeterValues(connectorId
: number) {
1962 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1963 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1967 private getReconnectExponentialDelay(): boolean | undefined {
1968 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1969 ? this.stationInfo
.reconnectExponentialDelay
1973 private async reconnect(code
: number): Promise
<void> {
1974 // Stop WebSocket ping
1975 this.stopWebSocketPing();
1977 this.stopHeartbeat();
1978 // Stop the ATG if needed
1979 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1980 this.stopAutomaticTransactionGenerator();
1983 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1984 this.getAutoReconnectMaxRetries() === -1
1986 this.autoReconnectRetryCount
++;
1987 const reconnectDelay
= this.getReconnectExponentialDelay()
1988 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1989 : this.getConnectionTimeout() * 1000;
1990 const reconnectDelayWithdraw
= 1000;
1991 const reconnectTimeout
=
1992 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
1993 ? reconnectDelay
- reconnectDelayWithdraw
1996 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1999 )}ms, timeout ${reconnectTimeout}ms`
2001 await Utils
.sleep(reconnectDelay
);
2004 ' WebSocket: reconnecting try #' +
2005 this.autoReconnectRetryCount
.toString()
2007 this.openWSConnection(
2008 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2009 { closeOpened
: true }
2011 this.wsConnectionRestarted
= true;
2012 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2014 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2015 this.autoReconnectRetryCount
2016 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2021 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2022 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2025 private initializeConnectorStatus(connectorId
: number): void {
2026 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2027 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2028 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2029 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2030 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2031 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;