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';
14 AutomaticTransactionGenerator
,
15 ChargingStationConfigurationUtils
,
17 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 type ResponseCallback
,
78 StandardParametersKey
,
79 type StatusNotificationRequest
,
80 type StatusNotificationResponse
,
81 StopTransactionReason
,
82 type StopTransactionRequest
,
83 type StopTransactionResponse
,
84 SupervisionUrlDistribution
,
85 SupportedFeatureProfiles
,
88 WebSocketCloseEventStatusCode
,
101 export class ChargingStation
{
102 public readonly index
: number;
103 public readonly templateFile
: string;
104 public stationInfo
!: ChargingStationInfo
;
105 public started
: boolean;
106 public starting
: boolean;
107 public authorizedTagsCache
: AuthorizedTagsCache
;
108 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
| undefined;
109 public ocppConfiguration
!: ChargingStationOcppConfiguration
| undefined;
110 public wsConnection
!: WebSocket
| null;
111 public readonly connectors
: Map
<number, ConnectorStatus
>;
112 public readonly requests
: Map
<string, CachedRequest
>;
113 public performanceStatistics
!: PerformanceStatistics
| undefined;
114 public heartbeatSetInterval
!: NodeJS
.Timeout
;
115 public ocppRequestService
!: OCPPRequestService
;
116 public bootNotificationRequest
!: BootNotificationRequest
;
117 public bootNotificationResponse
!: BootNotificationResponse
| undefined;
118 public powerDivider
!: number;
119 private stopping
: boolean;
120 private configurationFile
!: string;
121 private configurationFileHash
!: string;
122 private connectorsConfigurationHash
!: string;
123 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
124 private readonly messageBuffer
: Set
<string>;
125 private configuredSupervisionUrl
!: URL
;
126 private wsConnectionRestarted
: boolean;
127 private autoReconnectRetryCount
: number;
128 private templateFileWatcher
!: fs
.FSWatcher
| undefined;
129 private readonly sharedLRUCache
: SharedLRUCache
;
130 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
131 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
133 constructor(index
: number, templateFile
: string) {
134 this.started
= false;
135 this.starting
= false;
136 this.stopping
= false;
137 this.wsConnectionRestarted
= false;
138 this.autoReconnectRetryCount
= 0;
140 this.templateFile
= templateFile
;
141 this.connectors
= new Map
<number, ConnectorStatus
>();
142 this.requests
= new Map
<string, CachedRequest
>();
143 this.messageBuffer
= new Set
<string>();
144 this.sharedLRUCache
= SharedLRUCache
.getInstance();
145 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
146 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
151 private get
wsConnectionUrl(): URL
{
154 this.getSupervisionUrlOcppConfiguration() &&
155 Utils.isNotEmptyString(this.getSupervisionUrlOcppKey())
156 ? ChargingStationConfigurationUtils.getConfigurationKey(
158 this.getSupervisionUrlOcppKey()
160 : this.configuredSupervisionUrl.href
161 }/${this.stationInfo.chargingStationId}`
165 public logPrefix
= (): string => {
166 return Utils
.logPrefix(
168 (Utils.isNotEmptyString(this?.stationInfo?.chargingStationId) &&
169 this?.stationInfo?.chargingStationId) ??
170 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile()) ??
176 public hasAuthorizedTags(): boolean {
177 return Utils
.isNotEmptyArray(
178 this.authorizedTagsCache
.getAuthorizedTags(
179 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
184 public getEnableStatistics(): boolean {
185 return this.stationInfo
.enableStatistics
?? false;
188 public getMustAuthorizeAtRemoteStart(): boolean {
189 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
192 public getPayloadSchemaValidation(): boolean {
193 return this.stationInfo
.payloadSchemaValidation
?? true;
196 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
197 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
198 switch (this.getCurrentOutType(stationInfo
)) {
200 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
201 ? localStationInfo
.numberOfPhases
208 public isWebSocketConnectionOpened(): boolean {
209 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
212 public getRegistrationStatus(): RegistrationStatusEnumType
| undefined {
213 return this?.bootNotificationResponse
?.status;
216 public isInUnknownState(): boolean {
217 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
220 public isInPendingState(): boolean {
221 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.PENDING
;
224 public isInAcceptedState(): boolean {
225 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.ACCEPTED
;
228 public isInRejectedState(): boolean {
229 return this?.bootNotificationResponse
?.status === RegistrationStatusEnumType
.REJECTED
;
232 public isRegistered(): boolean {
234 this.isInUnknownState() === false &&
235 (this.isInAcceptedState() === true || this.isInPendingState() === true)
239 public isChargingStationAvailable(): boolean {
240 return this.getConnectorStatus(0)?.availability
=== AvailabilityType
.OPERATIVE
;
243 public isConnectorAvailable(id
: number): boolean {
244 return id
> 0 && this.getConnectorStatus(id
)?.availability
=== AvailabilityType
.OPERATIVE
;
247 public getNumberOfConnectors(): number {
248 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
251 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
252 return this.connectors
.get(id
);
255 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
256 return (stationInfo
?? this.stationInfo
)?.currentOutType
?? CurrentType
.AC
;
259 public getOcppStrictCompliance(): boolean {
260 return this.stationInfo
?.ocppStrictCompliance
?? false;
263 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
264 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
265 this.getCurrentOutType(stationInfo
),
269 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
270 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
271 ? localStationInfo
.voltageOut
275 public getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
276 const localStationInfo
= stationInfo
?? this.stationInfo
;
277 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
280 public getConnectorMaximumAvailablePower(connectorId
: number): number {
281 let connectorAmperageLimitationPowerLimit
: number;
283 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
284 this.getAmperageLimitation() < this.stationInfo
?.maximumAmperage
286 connectorAmperageLimitationPowerLimit
=
287 (this.getCurrentOutType() === CurrentType
.AC
288 ? ACElectricUtils
.powerTotal(
289 this.getNumberOfPhases(),
290 this.getVoltageOut(),
291 this.getAmperageLimitation() * this.getNumberOfConnectors()
293 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
296 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
297 const connectorChargingProfilesPowerLimit
=
298 ChargingStationUtils
.getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId
);
300 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
301 isNaN(connectorAmperageLimitationPowerLimit
)
303 : connectorAmperageLimitationPowerLimit
,
304 isNaN(connectorChargingProfilesPowerLimit
) ? Infinity : connectorChargingProfilesPowerLimit
308 public getTransactionIdTag(transactionId
: number): string | undefined {
309 for (const connectorId
of this.connectors
.keys()) {
312 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
314 return this.getConnectorStatus(connectorId
)?.transactionIdTag
;
319 public getOutOfOrderEndMeterValues(): boolean {
320 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
323 public getBeginEndMeterValues(): boolean {
324 return this.stationInfo
?.beginEndMeterValues
?? false;
327 public getMeteringPerTransaction(): boolean {
328 return this.stationInfo
?.meteringPerTransaction
?? true;
331 public getTransactionDataMeterValues(): boolean {
332 return this.stationInfo
?.transactionDataMeterValues
?? false;
335 public getMainVoltageMeterValues(): boolean {
336 return this.stationInfo
?.mainVoltageMeterValues
?? true;
339 public getPhaseLineToLineVoltageMeterValues(): boolean {
340 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
343 public getCustomValueLimitationMeterValues(): boolean {
344 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
347 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
348 for (const connectorId
of this.connectors
.keys()) {
351 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
358 public getEnergyActiveImportRegisterByTransactionId(
359 transactionId
: number,
362 return this.getEnergyActiveImportRegister(
363 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
368 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number, rounded
= false): number {
369 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
), rounded
);
372 public getAuthorizeRemoteTxRequests(): boolean {
373 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
375 StandardParametersKey
.AuthorizeRemoteTxRequests
377 return authorizeRemoteTxRequests
378 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
382 public getLocalAuthListEnabled(): boolean {
383 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
385 StandardParametersKey
.LocalAuthListEnabled
387 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
390 public setSupervisionUrl(url
: string): void {
392 this.getSupervisionUrlOcppConfiguration() &&
393 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey())
395 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
397 this.getSupervisionUrlOcppKey(),
401 this.stationInfo
.supervisionUrls
= url
;
402 this.saveStationInfo();
403 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
407 public startHeartbeat(): void {
408 if (this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval
) {
409 this.heartbeatSetInterval
= setInterval(() => {
410 this.ocppRequestService
411 .requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(this, RequestCommand
.HEARTBEAT
)
414 `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
418 }, this.getHeartbeatInterval());
420 `${this.logPrefix()} Heartbeat started every ${Utils.formatDurationMilliSeconds(
421 this.getHeartbeatInterval()
424 } else if (this.heartbeatSetInterval
) {
426 `${this.logPrefix()} Heartbeat already started every ${Utils.formatDurationMilliSeconds(
427 this.getHeartbeatInterval()
432 `${this.logPrefix()} Heartbeat interval set to ${
433 this.getHeartbeatInterval()
434 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
435 : this.getHeartbeatInterval()
436 }, not starting the heartbeat`
441 public restartHeartbeat(): void {
443 this.stopHeartbeat();
445 this.startHeartbeat();
448 public restartWebSocketPing(): void {
449 // Stop WebSocket ping
450 this.stopWebSocketPing();
451 // Start WebSocket ping
452 this.startWebSocketPing();
455 public startMeterValues(connectorId
: number, interval
: number): void {
456 if (connectorId
=== 0) {
458 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
462 if (!this.getConnectorStatus(connectorId
)) {
464 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
468 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
470 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
474 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
475 Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
)?.transactionId
)
478 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
483 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(() => {
484 // FIXME: Implement OCPP version agnostic helpers
485 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
488 this.getConnectorStatus(connectorId
).transactionId
,
491 this.ocppRequestService
492 .requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
494 RequestCommand
.METER_VALUES
,
497 transactionId
: this.getConnectorStatus(connectorId
)?.transactionId
,
498 meterValue
: [meterValue
],
503 `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
510 `${this.logPrefix()} Charging station ${
511 StandardParametersKey.MeterValueSampleInterval
512 } configuration set to ${
513 interval ? Utils.formatDurationMilliSeconds(interval) : interval
514 }, not sending MeterValues`
519 public start(): void {
520 if (this.started
=== false) {
521 if (this.starting
=== false) {
522 this.starting
= true;
523 if (this.getEnableStatistics() === true) {
524 this.performanceStatistics
?.start();
526 this.openWSConnection();
527 // Monitor charging station template file
528 this.templateFileWatcher
= FileUtils
.watchJsonFile(
530 FileType
.ChargingStationTemplate
,
533 (event
, filename
): void => {
534 if (Utils
.isNotEmptyString(filename
) && event
=== 'change') {
537 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
539 } file have changed, reload`
541 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
545 this.stopAutomaticTransactionGenerator();
547 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
549 this.startAutomaticTransactionGenerator();
551 if (this.getEnableStatistics() === true) {
552 this.performanceStatistics
?.restart();
554 this.performanceStatistics
?.stop();
556 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
559 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
567 parentPort
?.postMessage(MessageChannelUtils
.buildStartedMessage(this));
568 this.starting
= false;
570 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
573 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
577 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
578 if (this.started
=== true) {
579 if (this.stopping
=== false) {
580 this.stopping
= true;
581 await this.stopMessageSequence(reason
);
582 this.closeWSConnection();
583 if (this.getEnableStatistics() === true) {
584 this.performanceStatistics
?.stop();
586 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
587 this.templateFileWatcher
?.close();
588 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
589 delete this.bootNotificationResponse
;
590 this.started
= false;
591 parentPort
?.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
592 this.stopping
= false;
594 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
597 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
601 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
602 await this.stop(reason
);
603 await Utils
.sleep(this.stationInfo
.resetTime
);
608 public saveOcppConfiguration(): void {
609 if (this.getOcppPersistentConfiguration()) {
610 this.saveConfiguration();
614 public resetConnectorStatus(connectorId
: number): void {
615 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
616 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
617 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
618 this.getConnectorStatus(connectorId
).transactionStarted
= false;
619 delete this.getConnectorStatus(connectorId
)?.localAuthorizeIdTag
;
620 delete this.getConnectorStatus(connectorId
)?.authorizeIdTag
;
621 delete this.getConnectorStatus(connectorId
)?.transactionId
;
622 delete this.getConnectorStatus(connectorId
)?.transactionIdTag
;
623 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
624 delete this.getConnectorStatus(connectorId
)?.transactionBeginMeterValue
;
625 this.stopMeterValues(connectorId
);
626 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
629 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
): boolean | undefined {
630 return ChargingStationConfigurationUtils
.getConfigurationKey(
632 StandardParametersKey
.SupportedFeatureProfiles
633 )?.value
?.includes(featureProfile
);
636 public bufferMessage(message
: string): void {
637 this.messageBuffer
.add(message
);
640 public openWSConnection(
641 options
: WsOptions
= this.stationInfo
?.wsOptions
?? Constants
.EMPTY_OBJECT
,
642 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
644 terminateOpened
: false,
647 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
648 params
.closeOpened
= params
?.closeOpened
?? false;
649 params
.terminateOpened
= params
?.terminateOpened
?? false;
650 if (this.started
=== false && this.starting
=== false) {
652 `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} on stopped charging station`
657 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
658 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
660 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
662 if (params
?.closeOpened
) {
663 this.closeWSConnection();
665 if (params
?.terminateOpened
) {
666 this.terminateWSConnection();
669 if (this.isWebSocketConnectionOpened() === true) {
671 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
677 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
680 this.wsConnection
= new WebSocket(
681 this.wsConnectionUrl
,
682 `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`,
686 // Handle WebSocket message
687 this.wsConnection
.on(
689 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
691 // Handle WebSocket error
692 this.wsConnection
.on(
694 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
696 // Handle WebSocket close
697 this.wsConnection
.on(
699 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
701 // Handle WebSocket open
702 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
703 // Handle WebSocket ping
704 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
705 // Handle WebSocket pong
706 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
709 public closeWSConnection(): void {
710 if (this.isWebSocketConnectionOpened() === true) {
711 this.wsConnection
?.close();
712 this.wsConnection
= null;
716 public startAutomaticTransactionGenerator(
717 connectorIds
?: number[],
718 automaticTransactionGeneratorConfiguration
?: AutomaticTransactionGeneratorConfiguration
720 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
721 automaticTransactionGeneratorConfiguration
??
722 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
725 if (Utils
.isNotEmptyArray(connectorIds
)) {
726 for (const connectorId
of connectorIds
) {
727 this.automaticTransactionGenerator
?.startConnector(connectorId
);
730 this.automaticTransactionGenerator
?.start();
732 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
735 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
736 if (Utils
.isNotEmptyArray(connectorIds
)) {
737 for (const connectorId
of connectorIds
) {
738 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
741 this.automaticTransactionGenerator
?.stop();
743 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
746 public async stopTransactionOnConnector(
748 reason
= StopTransactionReason
.NONE
749 ): Promise
<StopTransactionResponse
> {
750 const transactionId
= this.getConnectorStatus(connectorId
)?.transactionId
;
752 this.getBeginEndMeterValues() === true &&
753 this.getOcppStrictCompliance() === true &&
754 this.getOutOfOrderEndMeterValues() === false
756 // FIXME: Implement OCPP version agnostic helpers
757 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
760 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
762 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
764 RequestCommand
.METER_VALUES
,
768 meterValue
: [transactionEndMeterValue
],
772 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
774 RequestCommand
.STOP_TRANSACTION
,
777 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
783 private flushMessageBuffer(): void {
784 if (this.messageBuffer
.size
> 0) {
785 this.messageBuffer
.forEach((message
) => {
787 let commandName
: RequestCommand
;
788 const [messageType
] = JSON
.parse(message
) as OutgoingRequest
| Response
| ErrorResponse
;
789 const isRequest
= messageType
=== MessageType
.CALL_MESSAGE
;
791 [, , commandName
] = JSON
.parse(message
) as OutgoingRequest
;
792 beginId
= PerformanceStatistics
.beginMeasure(commandName
);
794 this.wsConnection
?.send(message
);
795 isRequest
&& PerformanceStatistics
.endMeasure(commandName
, beginId
);
797 `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
799 )} payload sent: ${message}`
801 this.messageBuffer
.delete(message
);
806 private getSupervisionUrlOcppConfiguration(): boolean {
807 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
810 private getSupervisionUrlOcppKey(): string {
811 return this.stationInfo
.supervisionUrlOcppKey
?? VendorParametersKey
.ConnectionUrl
;
814 private getTemplateFromFile(): ChargingStationTemplate
| undefined {
815 let template
: ChargingStationTemplate
;
817 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
818 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
820 const measureId
= `${FileType.ChargingStationTemplate} read`;
821 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
822 template
= JSON
.parse(
823 fs
.readFileSync(this.templateFile
, 'utf8')
824 ) as ChargingStationTemplate
;
825 PerformanceStatistics
.endMeasure(measureId
, beginId
);
826 template
.templateHash
= crypto
827 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
828 .update(JSON
.stringify(template
))
830 this.sharedLRUCache
.setChargingStationTemplate(template
);
833 FileUtils
.handleFileException(
835 FileType
.ChargingStationTemplate
,
836 error
as NodeJS
.ErrnoException
,
843 private getStationInfoFromTemplate(): ChargingStationInfo
{
844 const stationTemplate
: ChargingStationTemplate
| undefined = this.getTemplateFromFile();
845 if (Utils
.isNullOrUndefined(stationTemplate
)) {
846 const errorMsg
= `Failed to read charging station template file ${this.templateFile}`;
847 logger
.error(`${this.logPrefix()} ${errorMsg}`);
848 throw new BaseError(errorMsg
);
850 if (Utils
.isEmptyObject(stationTemplate
)) {
851 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
852 logger
.error(`${this.logPrefix()} ${errorMsg}`);
853 throw new BaseError(errorMsg
);
855 // Deprecation template keys section
856 ChargingStationUtils
.warnDeprecatedTemplateKey(
861 "Use 'supervisionUrls' instead"
863 ChargingStationUtils
.convertDeprecatedTemplateKey(
868 const stationInfo
: ChargingStationInfo
=
869 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
870 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
871 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
875 stationInfo
.ocppVersion
= stationTemplate
?.ocppVersion
?? OCPPVersion
.VERSION_16
;
876 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
877 if (Utils
.isNotEmptyArray(stationTemplate
?.power
)) {
878 stationTemplate
.power
= stationTemplate
.power
as number[];
879 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
880 stationInfo
.maximumPower
=
881 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
882 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
883 : stationTemplate
.power
[powerArrayRandomIndex
];
885 stationTemplate
.power
= stationTemplate
?.power
as number;
886 stationInfo
.maximumPower
=
887 stationTemplate
?.powerUnit
=== PowerUnits
.KILO_WATT
888 ? stationTemplate
.power
* 1000
889 : stationTemplate
.power
;
891 stationInfo
.firmwareVersionPattern
=
892 stationTemplate
?.firmwareVersionPattern
?? Constants
.SEMVER_PATTERN
;
894 Utils
.isNotEmptyString(stationInfo
.firmwareVersion
) &&
895 new RegExp(stationInfo
.firmwareVersionPattern
).test(stationInfo
.firmwareVersion
) === false
898 `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${
900 } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
903 stationInfo
.firmwareUpgrade
= merge
<FirmwareUpgrade
>(
910 stationTemplate
?.firmwareUpgrade
?? Constants
.EMPTY_OBJECT
912 stationInfo
.resetTime
= !Utils
.isNullOrUndefined(stationTemplate
?.resetTime
)
913 ? stationTemplate
.resetTime
* 1000
914 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
915 const configuredMaxConnectors
=
916 ChargingStationUtils
.getConfiguredNumberOfConnectors(stationTemplate
);
917 ChargingStationUtils
.checkConfiguredMaxConnectors(
918 configuredMaxConnectors
,
922 const templateMaxConnectors
=
923 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
924 ChargingStationUtils
.checkTemplateMaxConnectors(
925 templateMaxConnectors
,
930 configuredMaxConnectors
>
931 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
932 !stationTemplate
?.randomConnectors
935 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
937 }, forcing random connector configurations affectation`
939 stationInfo
.randomConnectors
= true;
941 // Build connectors if needed (FIXME: should be factored out)
942 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
943 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
944 ChargingStationUtils
.createStationInfoHash(stationInfo
);
948 private getStationInfoFromFile(): ChargingStationInfo
| undefined {
949 let stationInfo
: ChargingStationInfo
| undefined;
950 this.getStationInfoPersistentConfiguration() &&
951 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
);
952 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
956 private getStationInfo(): ChargingStationInfo
{
957 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
958 const stationInfoFromFile
: ChargingStationInfo
| undefined = this.getStationInfoFromFile();
959 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
960 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
961 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
962 return this.stationInfo
;
964 return stationInfoFromFile
;
966 stationInfoFromFile
&&
967 ChargingStationUtils
.propagateSerialNumber(
968 this.getTemplateFromFile(),
970 stationInfoFromTemplate
972 return stationInfoFromTemplate
;
975 private saveStationInfo(): void {
976 if (this.getStationInfoPersistentConfiguration()) {
977 this.saveConfiguration();
981 private getOcppPersistentConfiguration(): boolean {
982 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
985 private getStationInfoPersistentConfiguration(): boolean {
986 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
989 private handleUnsupportedVersion(version
: OCPPVersion
) {
990 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
991 logger
.error(`${this.logPrefix()} ${errMsg}`);
992 throw new BaseError(errMsg
);
995 private initialize(): void {
996 this.configurationFile
= path
.join(
997 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
998 `${ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile())}.json`
1000 this.stationInfo
= this.getStationInfo();
1001 this.saveStationInfo();
1002 // Avoid duplication of connectors related information in RAM
1003 delete this.stationInfo
?.Connectors
;
1004 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
1005 if (this.getEnableStatistics() === true) {
1006 this.performanceStatistics
= PerformanceStatistics
.getInstance(
1007 this.stationInfo
.hashId
,
1008 this.stationInfo
.chargingStationId
,
1009 this.configuredSupervisionUrl
1012 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
1015 this.powerDivider
= this.getPowerDivider();
1016 // OCPP configuration
1017 this.ocppConfiguration
= this.getOcppConfiguration();
1018 this.initializeOcppConfiguration();
1019 this.initializeOcppServices();
1020 if (this.stationInfo
?.autoRegister
=== true) {
1021 this.bootNotificationResponse
= {
1022 currentTime
: new Date(),
1023 interval
: this.getHeartbeatInterval() / 1000,
1024 status: RegistrationStatusEnumType
.ACCEPTED
,
1028 this.stationInfo
.firmwareStatus
=== FirmwareStatus
.Installing
&&
1029 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersion
) &&
1030 Utils
.isNotEmptyString(this.stationInfo
.firmwareVersionPattern
)
1032 const patternGroup
: number | undefined =
1033 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.patternGroup
??
1034 this.stationInfo
.firmwareVersion
?.split('.').length
;
1035 const match
= this.stationInfo
?.firmwareVersion
1036 ?.match(new RegExp(this.stationInfo
.firmwareVersionPattern
))
1037 ?.slice(1, patternGroup
+ 1);
1038 const patchLevelIndex
= match
.length
- 1;
1039 match
[patchLevelIndex
] = (
1040 Utils
.convertToInt(match
[patchLevelIndex
]) +
1041 this.stationInfo
.firmwareUpgrade
?.versionUpgrade
?.step
1043 this.stationInfo
.firmwareVersion
= match
?.join('.');
1047 private initializeOcppServices(): void {
1048 const ocppVersion
= this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
1049 switch (ocppVersion
) {
1050 case OCPPVersion
.VERSION_16
:
1051 this.ocppIncomingRequestService
=
1052 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
1053 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
1054 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1057 case OCPPVersion
.VERSION_20
:
1058 case OCPPVersion
.VERSION_201
:
1059 this.ocppIncomingRequestService
=
1060 OCPP20IncomingRequestService
.getInstance
<OCPP20IncomingRequestService
>();
1061 this.ocppRequestService
= OCPP20RequestService
.getInstance
<OCPP20RequestService
>(
1062 OCPP20ResponseService
.getInstance
<OCPP20ResponseService
>()
1066 this.handleUnsupportedVersion(ocppVersion
);
1071 private initializeOcppConfiguration(): void {
1073 !ChargingStationConfigurationUtils
.getConfigurationKey(
1075 StandardParametersKey
.HeartbeatInterval
1078 ChargingStationConfigurationUtils
.addConfigurationKey(
1080 StandardParametersKey
.HeartbeatInterval
,
1085 !ChargingStationConfigurationUtils
.getConfigurationKey(
1087 StandardParametersKey
.HeartBeatInterval
1090 ChargingStationConfigurationUtils
.addConfigurationKey(
1092 StandardParametersKey
.HeartBeatInterval
,
1098 this.getSupervisionUrlOcppConfiguration() &&
1099 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1100 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1102 ChargingStationConfigurationUtils
.addConfigurationKey(
1104 this.getSupervisionUrlOcppKey(),
1105 this.configuredSupervisionUrl
.href
,
1109 !this.getSupervisionUrlOcppConfiguration() &&
1110 Utils
.isNotEmptyString(this.getSupervisionUrlOcppKey()) &&
1111 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1113 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1115 this.getSupervisionUrlOcppKey(),
1120 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1121 !ChargingStationConfigurationUtils
.getConfigurationKey(
1123 this.stationInfo
.amperageLimitationOcppKey
1126 ChargingStationConfigurationUtils
.addConfigurationKey(
1128 this.stationInfo
.amperageLimitationOcppKey
,
1130 this.stationInfo
.maximumAmperage
*
1131 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1136 !ChargingStationConfigurationUtils
.getConfigurationKey(
1138 StandardParametersKey
.SupportedFeatureProfiles
1141 ChargingStationConfigurationUtils
.addConfigurationKey(
1143 StandardParametersKey
.SupportedFeatureProfiles
,
1144 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1147 ChargingStationConfigurationUtils
.addConfigurationKey(
1149 StandardParametersKey
.NumberOfConnectors
,
1150 this.getNumberOfConnectors().toString(),
1155 !ChargingStationConfigurationUtils
.getConfigurationKey(
1157 StandardParametersKey
.MeterValuesSampledData
1160 ChargingStationConfigurationUtils
.addConfigurationKey(
1162 StandardParametersKey
.MeterValuesSampledData
,
1163 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1167 !ChargingStationConfigurationUtils
.getConfigurationKey(
1169 StandardParametersKey
.ConnectorPhaseRotation
1172 const connectorPhaseRotation
= [];
1173 for (const connectorId
of this.connectors
.keys()) {
1175 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1176 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1177 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1178 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1180 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1181 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1182 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1183 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1186 ChargingStationConfigurationUtils
.addConfigurationKey(
1188 StandardParametersKey
.ConnectorPhaseRotation
,
1189 connectorPhaseRotation
.toString()
1193 !ChargingStationConfigurationUtils
.getConfigurationKey(
1195 StandardParametersKey
.AuthorizeRemoteTxRequests
1198 ChargingStationConfigurationUtils
.addConfigurationKey(
1200 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1205 !ChargingStationConfigurationUtils
.getConfigurationKey(
1207 StandardParametersKey
.LocalAuthListEnabled
1209 ChargingStationConfigurationUtils
.getConfigurationKey(
1211 StandardParametersKey
.SupportedFeatureProfiles
1212 )?.value
?.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1214 ChargingStationConfigurationUtils
.addConfigurationKey(
1216 StandardParametersKey
.LocalAuthListEnabled
,
1221 !ChargingStationConfigurationUtils
.getConfigurationKey(
1223 StandardParametersKey
.ConnectionTimeOut
1226 ChargingStationConfigurationUtils
.addConfigurationKey(
1228 StandardParametersKey
.ConnectionTimeOut
,
1229 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1232 this.saveOcppConfiguration();
1235 private initializeConnectors(
1236 stationInfo
: ChargingStationInfo
,
1237 configuredMaxConnectors
: number,
1238 templateMaxConnectors
: number
1240 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1241 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1242 logger
.error(`${this.logPrefix()} ${logMsg}`);
1243 throw new BaseError(logMsg
);
1245 if (!stationInfo
?.Connectors
[0]) {
1247 `${this.logPrefix()} Charging station information from template ${
1249 } with no connector Id 0 configuration`
1252 if (stationInfo
?.Connectors
) {
1253 const connectorsConfigHash
= crypto
1254 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1255 .update(`${JSON.stringify(stationInfo?.Connectors)}${configuredMaxConnectors.toString()}`)
1257 const connectorsConfigChanged
=
1258 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1259 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1260 connectorsConfigChanged
&& this.connectors
.clear();
1261 this.connectorsConfigurationHash
= connectorsConfigHash
;
1262 // Add connector Id 0
1263 let lastConnector
= '0';
1264 for (lastConnector
in stationInfo
?.Connectors
) {
1265 const connectorStatus
= stationInfo
?.Connectors
[lastConnector
];
1266 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1268 lastConnectorId
=== 0 &&
1269 this.getUseConnectorId0(stationInfo
) === true &&
1272 this.checkStationInfoConnectorStatus(lastConnectorId
, connectorStatus
);
1273 this.connectors
.set(
1275 Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
)
1277 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1278 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1279 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1283 // Generate all connectors
1284 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1285 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1286 const randConnectorId
= stationInfo
?.randomConnectors
1287 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1289 const connectorStatus
= stationInfo
?.Connectors
[randConnectorId
.toString()];
1290 this.checkStationInfoConnectorStatus(randConnectorId
, connectorStatus
);
1291 this.connectors
.set(index
, Utils
.cloneObject
<ConnectorStatus
>(connectorStatus
));
1292 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1293 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1294 this.getConnectorStatus(index
).chargingProfiles
= [];
1301 `${this.logPrefix()} Charging station information from template ${
1303 } with no connectors configuration defined, using already defined connectors`
1306 // Initialize transaction attributes on connectors
1307 for (const connectorId
of this.connectors
.keys()) {
1308 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1310 `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
1311 this.getConnectorStatus(connectorId)?.transactionId
1317 (this.getConnectorStatus(connectorId
)?.transactionStarted
=== undefined ||
1318 this.getConnectorStatus(connectorId
)?.transactionStarted
=== null)
1320 this.initializeConnectorStatus(connectorId
);
1325 private checkStationInfoConnectorStatus(
1326 connectorId
: number,
1327 connectorStatus
: ConnectorStatus
1329 if (!Utils
.isNullOrUndefined(connectorStatus
?.status)) {
1331 `${this.logPrefix()} Charging station information from template ${
1333 } with connector ${connectorId} status configuration defined, undefine it`
1335 delete connectorStatus
.status;
1339 private getConfigurationFromFile(): ChargingStationConfiguration
| undefined {
1340 let configuration
: ChargingStationConfiguration
| undefined;
1341 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1343 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1344 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1345 this.configurationFileHash
1348 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1349 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1350 configuration
= JSON
.parse(
1351 fs
.readFileSync(this.configurationFile
, 'utf8')
1352 ) as ChargingStationConfiguration
;
1353 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1354 this.configurationFileHash
= configuration
.configurationHash
;
1355 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1358 FileUtils
.handleFileException(
1359 this.configurationFile
,
1360 FileType
.ChargingStationConfiguration
,
1361 error
as NodeJS
.ErrnoException
,
1366 return configuration
;
1369 private saveConfiguration(): void {
1370 if (this.configurationFile
) {
1372 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1373 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1375 const configurationData
: ChargingStationConfiguration
=
1376 Utils
.cloneObject(this.getConfigurationFromFile()) ?? Constants
.EMPTY_OBJECT
;
1377 this.ocppConfiguration
?.configurationKey
&&
1378 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1379 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1380 delete configurationData
.configurationHash
;
1381 const configurationHash
= crypto
1382 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1383 .update(JSON
.stringify(configurationData
))
1385 if (this.configurationFileHash
!== configurationHash
) {
1386 configurationData
.configurationHash
= configurationHash
;
1387 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1388 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1389 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1390 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1391 fs
.closeSync(fileDescriptor
);
1392 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1393 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1394 this.configurationFileHash
= configurationHash
;
1395 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1398 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1399 this.configurationFile
1404 FileUtils
.handleFileException(
1405 this.configurationFile
,
1406 FileType
.ChargingStationConfiguration
,
1407 error
as NodeJS
.ErrnoException
,
1413 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1418 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| undefined {
1419 return this.getTemplateFromFile()?.Configuration
;
1422 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| undefined {
1423 let configuration
: ChargingStationConfiguration
| undefined;
1424 if (this.getOcppPersistentConfiguration() === true) {
1425 const configurationFromFile
= this.getConfigurationFromFile();
1426 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1428 if (!Utils
.isNullOrUndefined(configuration
)) {
1429 delete configuration
.stationInfo
;
1430 delete configuration
.configurationHash
;
1432 return configuration
;
1435 private getOcppConfiguration(): ChargingStationOcppConfiguration
| undefined {
1436 let ocppConfiguration
: ChargingStationOcppConfiguration
| undefined =
1437 this.getOcppConfigurationFromFile();
1438 if (!ocppConfiguration
) {
1439 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1441 return ocppConfiguration
;
1444 private async onOpen(): Promise
<void> {
1445 if (this.isWebSocketConnectionOpened() === true) {
1447 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1449 if (this.isRegistered() === false) {
1450 // Send BootNotification
1451 let registrationRetryCount
= 0;
1453 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1454 BootNotificationRequest
,
1455 BootNotificationResponse
1456 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1457 skipBufferingOnError
: true,
1459 if (this.isRegistered() === false) {
1460 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1462 this?.bootNotificationResponse
?.interval
1463 ? this.bootNotificationResponse
.interval
* 1000
1464 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1468 this.isRegistered() === false &&
1469 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1470 this.getRegistrationMaxRetries() === -1)
1473 if (this.isRegistered() === true) {
1474 if (this.isInAcceptedState() === true) {
1475 await this.startMessageSequence();
1479 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1482 this.wsConnectionRestarted
= false;
1483 this.autoReconnectRetryCount
= 0;
1484 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1487 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1492 private async onClose(code
: number, reason
: Buffer
): Promise
<void> {
1495 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1496 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1498 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1500 )}' and reason '${reason.toString()}'`
1502 this.autoReconnectRetryCount
= 0;
1507 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1509 )}' and reason '${reason.toString()}'`
1511 this.started
=== true && (await this.reconnect());
1514 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1517 private getCachedRequest(messageType
: MessageType
, messageId
: string): CachedRequest
| undefined {
1518 const cachedRequest
= this.requests
.get(messageId
);
1519 if (Array.isArray(cachedRequest
) === true) {
1520 return cachedRequest
;
1522 throw new OCPPError(
1523 ErrorType
.PROTOCOL_ERROR
,
1524 `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString(
1526 )} is not an array`,
1528 cachedRequest
as JsonType
1532 private async handleIncomingMessage(request
: IncomingRequest
): Promise
<void> {
1533 const [messageType
, messageId
, commandName
, commandPayload
] = request
;
1534 if (this.getEnableStatistics() === true) {
1535 this.performanceStatistics
?.addRequestStatistic(commandName
, messageType
);
1538 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1542 // Process the message
1543 await this.ocppIncomingRequestService
.incomingRequestHandler(
1551 private handleResponseMessage(response
: Response
): void {
1552 const [messageType
, messageId
, commandPayload
] = response
;
1553 if (this.requests
.has(messageId
) === false) {
1555 throw new OCPPError(
1556 ErrorType
.INTERNAL_ERROR
,
1557 `Response for unknown message id ${messageId}`,
1563 const [responseCallback
, , requestCommandName
, requestPayload
] = this.getCachedRequest(
1568 `${this.logPrefix()} << Command '${
1569 requestCommandName ?? Constants.UNKNOWN_COMMAND
1570 }' received response payload: ${JSON.stringify(response)}`
1572 responseCallback(commandPayload
, requestPayload
);
1575 private handleErrorMessage(errorResponse
: ErrorResponse
): void {
1576 const [messageType
, messageId
, errorType
, errorMessage
, errorDetails
] = errorResponse
;
1577 if (this.requests
.has(messageId
) === false) {
1579 throw new OCPPError(
1580 ErrorType
.INTERNAL_ERROR
,
1581 `Error response for unknown message id ${messageId}`,
1583 { errorType
, errorMessage
, errorDetails
}
1586 const [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1588 `${this.logPrefix()} << Command '${
1589 requestCommandName ?? Constants.UNKNOWN_COMMAND
1590 }' received error response payload: ${JSON.stringify(errorResponse)}`
1592 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1595 private async onMessage(data
: RawData
): Promise
<void> {
1596 let request
: IncomingRequest
| Response
| ErrorResponse
;
1597 let messageType
: number;
1600 request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1601 if (Array.isArray(request
) === true) {
1602 [messageType
] = request
;
1603 // Check the type of message
1604 switch (messageType
) {
1606 case MessageType
.CALL_MESSAGE
:
1607 await this.handleIncomingMessage(request
as IncomingRequest
);
1610 case MessageType
.CALL_RESULT_MESSAGE
:
1611 this.handleResponseMessage(request
as Response
);
1614 case MessageType
.CALL_ERROR_MESSAGE
:
1615 this.handleErrorMessage(request
as ErrorResponse
);
1619 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1620 errMsg
= `Wrong message type ${messageType}`;
1621 logger
.error(`${this.logPrefix()} ${errMsg}`);
1622 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1624 parentPort
?.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1626 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1631 let commandName
: IncomingRequestCommand
;
1632 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1633 let errorCallback
: ErrorCallback
;
1634 const [, messageId
] = request
;
1635 switch (messageType
) {
1636 case MessageType
.CALL_MESSAGE
:
1637 [, , commandName
] = request
as IncomingRequest
;
1639 await this.ocppRequestService
.sendError(this, messageId
, error
as OCPPError
, commandName
);
1641 case MessageType
.CALL_RESULT_MESSAGE
:
1642 case MessageType
.CALL_ERROR_MESSAGE
:
1643 if (this.requests
.has(messageId
) === true) {
1644 [, errorCallback
, requestCommandName
] = this.getCachedRequest(messageType
, messageId
);
1645 // Reject the deferred promise in case of error at response handling (rejecting an already fulfilled promise is a no-op)
1646 errorCallback(error
as OCPPError
, false);
1648 // Remove the request from the cache in case of error at response handling
1649 this.requests
.delete(messageId
);
1653 if (error
instanceof OCPPError
=== false) {
1655 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1656 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1657 }' message '${data.toString()}' handling is not an OCPPError:`,
1662 `${this.logPrefix()} Incoming OCPP command '${
1663 commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND
1664 }' message '${data.toString()}'${
1665 messageType !== MessageType.CALL_MESSAGE
1666 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1668 } processing error:`,
1674 private onPing(): void {
1675 logger
.debug(`${this.logPrefix()} Received a WS ping (rfc6455) from the server`);
1678 private onPong(): void {
1679 logger
.debug(`${this.logPrefix()} Received a WS pong (rfc6455) from the server`);
1682 private onError(error
: WSError
): void {
1683 this.closeWSConnection();
1684 logger
.error(`${this.logPrefix()} WebSocket error:`, error
);
1687 private getEnergyActiveImportRegister(connectorStatus
: ConnectorStatus
, rounded
= false): number {
1688 if (this.getMeteringPerTransaction() === true) {
1691 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1692 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1697 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1698 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1702 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1703 const localStationInfo
= stationInfo
?? this.stationInfo
;
1704 return localStationInfo
?.useConnectorId0
?? true;
1707 private getNumberOfRunningTransactions(): number {
1709 for (const connectorId
of this.connectors
.keys()) {
1710 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1717 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1718 for (const connectorId
of this.connectors
.keys()) {
1719 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1720 await this.stopTransactionOnConnector(connectorId
, reason
);
1726 private getConnectionTimeout(): number {
1728 ChargingStationConfigurationUtils
.getConfigurationKey(
1730 StandardParametersKey
.ConnectionTimeOut
1735 ChargingStationConfigurationUtils
.getConfigurationKey(
1737 StandardParametersKey
.ConnectionTimeOut
1739 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1742 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1745 // -1 for unlimited, 0 for disabling
1746 private getAutoReconnectMaxRetries(): number | undefined {
1747 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1748 return this.stationInfo
.autoReconnectMaxRetries
;
1750 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1751 return Configuration
.getAutoReconnectMaxRetries();
1757 private getRegistrationMaxRetries(): number | undefined {
1758 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1759 return this.stationInfo
.registrationMaxRetries
;
1764 private getPowerDivider(): number {
1765 let powerDivider
= this.getNumberOfConnectors();
1766 if (this.stationInfo
?.powerSharedByConnectors
) {
1767 powerDivider
= this.getNumberOfRunningTransactions();
1769 return powerDivider
;
1772 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1773 const maximumPower
= this.getMaximumPower(stationInfo
);
1774 switch (this.getCurrentOutType(stationInfo
)) {
1775 case CurrentType
.AC
:
1776 return ACElectricUtils
.amperagePerPhaseFromPower(
1777 this.getNumberOfPhases(stationInfo
),
1778 maximumPower
/ this.getNumberOfConnectors(),
1779 this.getVoltageOut(stationInfo
)
1781 case CurrentType
.DC
:
1782 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1786 private getAmperageLimitation(): number | undefined {
1788 Utils
.isNotEmptyString(this.stationInfo
?.amperageLimitationOcppKey
) &&
1789 ChargingStationConfigurationUtils
.getConfigurationKey(
1791 this.stationInfo
.amperageLimitationOcppKey
1796 ChargingStationConfigurationUtils
.getConfigurationKey(
1798 this.stationInfo
.amperageLimitationOcppKey
1800 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1805 private async startMessageSequence(): Promise
<void> {
1806 if (this.stationInfo
?.autoRegister
=== true) {
1807 await this.ocppRequestService
.requestHandler
<
1808 BootNotificationRequest
,
1809 BootNotificationResponse
1810 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1811 skipBufferingOnError
: true,
1814 // Start WebSocket ping
1815 this.startWebSocketPing();
1817 this.startHeartbeat();
1818 // Initialize connectors status
1819 for (const connectorId
of this.connectors
.keys()) {
1820 let connectorStatus
: ConnectorStatusEnum
| undefined;
1821 if (connectorId
=== 0) {
1824 !this.getConnectorStatus(connectorId
)?.status &&
1825 (this.isChargingStationAvailable() === false ||
1826 this.isConnectorAvailable(connectorId
) === false)
1828 connectorStatus
= ConnectorStatusEnum
.Unavailable
;
1830 !this.getConnectorStatus(connectorId
)?.status &&
1831 this.getConnectorStatus(connectorId
)?.bootStatus
1833 // Set boot status in template at startup
1834 connectorStatus
= this.getConnectorStatus(connectorId
)?.bootStatus
;
1835 } else if (this.getConnectorStatus(connectorId
)?.status) {
1836 // Set previous status at startup
1837 connectorStatus
= this.getConnectorStatus(connectorId
)?.status;
1839 // Set default status
1840 connectorStatus
= ConnectorStatusEnum
.Available
;
1842 await this.ocppRequestService
.requestHandler
<
1843 StatusNotificationRequest
,
1844 StatusNotificationResponse
1847 RequestCommand
.STATUS_NOTIFICATION
,
1848 OCPPServiceUtils
.buildStatusNotificationRequest(this, connectorId
, connectorStatus
)
1850 this.getConnectorStatus(connectorId
).status = connectorStatus
;
1852 if (this.stationInfo
?.firmwareStatus
=== FirmwareStatus
.Installing
) {
1853 await this.ocppRequestService
.requestHandler
<
1854 FirmwareStatusNotificationRequest
,
1855 FirmwareStatusNotificationResponse
1856 >(this, RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1857 status: FirmwareStatus
.Installed
,
1859 this.stationInfo
.firmwareStatus
= FirmwareStatus
.Installed
;
1863 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1864 this.startAutomaticTransactionGenerator();
1866 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1869 private async stopMessageSequence(
1870 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1872 // Stop WebSocket ping
1873 this.stopWebSocketPing();
1875 this.stopHeartbeat();
1876 // Stop ongoing transactions
1877 if (this.automaticTransactionGenerator
?.started
=== true) {
1878 this.stopAutomaticTransactionGenerator();
1880 await this.stopRunningTransactions(reason
);
1882 for (const connectorId
of this.connectors
.keys()) {
1883 if (connectorId
> 0) {
1884 await this.ocppRequestService
.requestHandler
<
1885 StatusNotificationRequest
,
1886 StatusNotificationResponse
1889 RequestCommand
.STATUS_NOTIFICATION
,
1890 OCPPServiceUtils
.buildStatusNotificationRequest(
1893 ConnectorStatusEnum
.Unavailable
1896 delete this.getConnectorStatus(connectorId
)?.status;
1901 private startWebSocketPing(): void {
1902 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1904 StandardParametersKey
.WebSocketPingInterval
1906 ? Utils
.convertToInt(
1907 ChargingStationConfigurationUtils
.getConfigurationKey(
1909 StandardParametersKey
.WebSocketPingInterval
1913 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1914 this.webSocketPingSetInterval
= setInterval(() => {
1915 if (this.isWebSocketConnectionOpened() === true) {
1916 this.wsConnection
?.ping();
1918 }, webSocketPingInterval
* 1000);
1920 `${this.logPrefix()} WebSocket ping started every ${Utils.formatDurationSeconds(
1921 webSocketPingInterval
1924 } else if (this.webSocketPingSetInterval
) {
1926 `${this.logPrefix()} WebSocket ping already started every ${Utils.formatDurationSeconds(
1927 webSocketPingInterval
1932 `${this.logPrefix()} WebSocket ping interval set to ${
1933 webSocketPingInterval
1934 ? Utils.formatDurationSeconds(webSocketPingInterval)
1935 : webSocketPingInterval
1936 }, not starting the WebSocket ping`
1941 private stopWebSocketPing(): void {
1942 if (this.webSocketPingSetInterval
) {
1943 clearInterval(this.webSocketPingSetInterval
);
1947 private getConfiguredSupervisionUrl(): URL
{
1948 const supervisionUrls
= this.stationInfo
?.supervisionUrls
?? Configuration
.getSupervisionUrls();
1949 if (Utils
.isNotEmptyArray(supervisionUrls
)) {
1950 let configuredSupervisionUrlIndex
: number;
1951 switch (Configuration
.getSupervisionUrlDistribution()) {
1952 case SupervisionUrlDistribution
.RANDOM
:
1953 configuredSupervisionUrlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1955 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1956 case SupervisionUrlDistribution
.CHARGING_STATION_AFFINITY
:
1958 Object.values(SupervisionUrlDistribution
).includes(
1959 Configuration
.getSupervisionUrlDistribution()
1962 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1963 SupervisionUrlDistribution.CHARGING_STATION_AFFINITY
1966 configuredSupervisionUrlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1969 return new URL(supervisionUrls
[configuredSupervisionUrlIndex
]);
1971 return new URL(supervisionUrls
as string);
1974 private getHeartbeatInterval(): number {
1975 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1977 StandardParametersKey
.HeartbeatInterval
1979 if (HeartbeatInterval
) {
1980 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1982 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1984 StandardParametersKey
.HeartBeatInterval
1986 if (HeartBeatInterval
) {
1987 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1989 this.stationInfo
?.autoRegister
=== false &&
1991 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1992 Constants.DEFAULT_HEARTBEAT_INTERVAL
1995 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1998 private stopHeartbeat(): void {
1999 if (this.heartbeatSetInterval
) {
2000 clearInterval(this.heartbeatSetInterval
);
2004 private terminateWSConnection(): void {
2005 if (this.isWebSocketConnectionOpened() === true) {
2006 this.wsConnection
?.terminate();
2007 this.wsConnection
= null;
2011 private stopMeterValues(connectorId
: number) {
2012 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
2013 clearInterval(this.getConnectorStatus(connectorId
)?.transactionSetInterval
);
2017 private getReconnectExponentialDelay(): boolean {
2018 return this.stationInfo
?.reconnectExponentialDelay
?? false;
2021 private async reconnect(): Promise
<void> {
2022 // Stop WebSocket ping
2023 this.stopWebSocketPing();
2025 this.stopHeartbeat();
2026 // Stop the ATG if needed
2027 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2028 this.stopAutomaticTransactionGenerator();
2031 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2032 this.getAutoReconnectMaxRetries() === -1
2034 this.autoReconnectRetryCount
++;
2035 const reconnectDelay
= this.getReconnectExponentialDelay()
2036 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2037 : this.getConnectionTimeout() * 1000;
2038 const reconnectDelayWithdraw
= 1000;
2039 const reconnectTimeout
=
2040 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2041 ? reconnectDelay
- reconnectDelayWithdraw
2044 `${this.logPrefix()} WebSocket connection retry in ${Utils.roundTo(
2047 )}ms, timeout ${reconnectTimeout}ms`
2049 await Utils
.sleep(reconnectDelay
);
2051 `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`
2053 this.openWSConnection(
2055 ...(this.stationInfo
?.wsOptions
?? Constants
.EMPTY_OBJECT
),
2056 handshakeTimeout
: reconnectTimeout
,
2058 { closeOpened
: true }
2060 this.wsConnectionRestarted
= true;
2061 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2063 `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
2064 this.autoReconnectRetryCount
2065 }) or retries disabled (${this.getAutoReconnectMaxRetries()})`
2070 private getAutomaticTransactionGeneratorConfigurationFromTemplate():
2071 | AutomaticTransactionGeneratorConfiguration
2073 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
;
2076 private initializeConnectorStatus(connectorId
: number): void {
2077 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2078 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2079 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2080 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2081 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2082 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;