1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public readonly templateFile
: string;
88 public stationInfo
!: ChargingStationInfo
;
89 public started
: boolean;
90 public authorizedTagsCache
: AuthorizedTagsCache
;
91 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly connectors
: Map
<number, ConnectorStatus
>;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationRequest
!: BootNotificationRequest
;
100 public bootNotificationResponse
!: BootNotificationResponse
| null;
101 public powerDivider
!: number;
102 private readonly index
: number;
103 private configurationFile
!: string;
104 private configurationFileHash
!: string;
105 private connectorsConfigurationHash
!: string;
106 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
107 private readonly messageBuffer
: Set
<string>;
108 private configuredSupervisionUrl
!: URL
;
109 private wsConnectionRestarted
: boolean;
110 private autoReconnectRetryCount
: number;
111 private templateFileWatcher
!: fs
.FSWatcher
;
112 private readonly sharedLRUCache
: SharedLRUCache
;
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.started
= 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;
546 this.started
= false;
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(connectorIds
?: number[]): void {
747 if (!this.automaticTransactionGenerator
) {
748 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
749 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
753 if (!Utils
.isEmptyArray(connectorIds
)) {
754 for (const connectorId
of connectorIds
) {
755 this.automaticTransactionGenerator
.startConnector(connectorId
);
758 this.automaticTransactionGenerator
.start();
762 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
763 if (!Utils
.isEmptyArray(connectorIds
)) {
764 for (const connectorId
of connectorIds
) {
765 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
768 this.automaticTransactionGenerator
?.stop();
769 this.automaticTransactionGenerator
= null;
773 private flushMessageBuffer(): void {
774 if (this.messageBuffer
.size
> 0) {
775 this.messageBuffer
.forEach((message
) => {
776 // TODO: evaluate the need to track performance
777 this.wsConnection
.send(message
);
778 this.messageBuffer
.delete(message
);
783 private getSupervisionUrlOcppConfiguration(): boolean {
784 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
787 private getSupervisionUrlOcppKey(): string {
788 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
791 private getTemplateFromFile(): ChargingStationTemplate
| null {
792 let template
: ChargingStationTemplate
= null;
794 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
795 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
797 const measureId
= `${FileType.ChargingStationTemplate} read`;
798 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
799 template
= JSON
.parse(
800 fs
.readFileSync(this.templateFile
, 'utf8')
801 ) as ChargingStationTemplate
;
802 PerformanceStatistics
.endMeasure(measureId
, beginId
);
803 template
.templateHash
= crypto
804 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
805 .update(JSON
.stringify(template
))
807 this.sharedLRUCache
.setChargingStationTemplate(template
);
810 FileUtils
.handleFileException(
812 FileType
.ChargingStationTemplate
,
814 error
as NodeJS
.ErrnoException
820 private getStationInfoFromTemplate(): ChargingStationInfo
{
821 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
822 if (Utils
.isNullOrUndefined(stationTemplate
)) {
823 const errorMsg
= 'Failed to read charging station template file';
824 logger
.error(`${this.logPrefix()} ${errorMsg}`);
825 throw new BaseError(errorMsg
);
827 if (Utils
.isEmptyObject(stationTemplate
)) {
828 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
829 logger
.error(`${this.logPrefix()} ${errorMsg}`);
830 throw new BaseError(errorMsg
);
832 // Deprecation template keys section
833 ChargingStationUtils
.warnDeprecatedTemplateKey(
838 "Use 'supervisionUrls' instead"
840 ChargingStationUtils
.convertDeprecatedTemplateKey(
845 const stationInfo
: ChargingStationInfo
=
846 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
847 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
848 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
852 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
853 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
854 stationTemplate
.power
= stationTemplate
.power
as number[];
855 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
856 stationInfo
.maximumPower
=
857 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
858 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
859 : stationTemplate
.power
[powerArrayRandomIndex
];
861 stationTemplate
.power
= stationTemplate
.power
as number;
862 stationInfo
.maximumPower
=
863 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
864 ? stationTemplate
.power
* 1000
865 : stationTemplate
.power
;
867 stationInfo
.resetTime
= stationTemplate
.resetTime
868 ? stationTemplate
.resetTime
* 1000
869 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
870 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
874 ChargingStationUtils
.checkConfiguredMaxConnectors(
875 configuredMaxConnectors
,
879 const templateMaxConnectors
=
880 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
881 ChargingStationUtils
.checkTemplateMaxConnectors(
882 templateMaxConnectors
,
887 configuredMaxConnectors
>
888 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
889 !stationTemplate
?.randomConnectors
892 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
894 }, forcing random connector configurations affectation`
896 stationInfo
.randomConnectors
= true;
898 // Build connectors if needed (FIXME: should be factored out)
899 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
900 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
901 ChargingStationUtils
.createStationInfoHash(stationInfo
);
905 private getStationInfoFromFile(): ChargingStationInfo
| null {
906 let stationInfo
: ChargingStationInfo
= null;
907 this.getStationInfoPersistentConfiguration() &&
908 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
909 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
913 private getStationInfo(): ChargingStationInfo
{
914 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
915 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
916 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
917 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
918 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
919 return this.stationInfo
;
921 return stationInfoFromFile
;
923 stationInfoFromFile
&&
924 ChargingStationUtils
.propagateSerialNumber(
925 this.getTemplateFromFile(),
927 stationInfoFromTemplate
929 return stationInfoFromTemplate
;
932 private saveStationInfo(): void {
933 if (this.getStationInfoPersistentConfiguration()) {
934 this.saveConfiguration();
938 private getOcppVersion(): OCPPVersion
{
939 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
942 private getOcppPersistentConfiguration(): boolean {
943 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
946 private getStationInfoPersistentConfiguration(): boolean {
947 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
950 private handleUnsupportedVersion(version
: OCPPVersion
) {
951 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
952 logger
.error(`${this.logPrefix()} ${errMsg}`);
953 throw new BaseError(errMsg
);
956 private initialize(): void {
957 this.configurationFile
= path
.join(
958 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
959 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
961 this.stationInfo
= this.getStationInfo();
962 this.saveStationInfo();
963 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
964 // Avoid duplication of connectors related information in RAM
965 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
966 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
967 if (this.getEnableStatistics()) {
968 this.performanceStatistics
= PerformanceStatistics
.getInstance(
969 this.stationInfo
.hashId
,
970 this.stationInfo
.chargingStationId
,
971 this.configuredSupervisionUrl
974 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
977 this.powerDivider
= this.getPowerDivider();
978 // OCPP configuration
979 this.ocppConfiguration
= this.getOcppConfiguration();
980 this.initializeOcppConfiguration();
981 switch (this.getOcppVersion()) {
982 case OCPPVersion
.VERSION_16
:
983 this.ocppIncomingRequestService
=
984 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
985 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
986 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
990 this.handleUnsupportedVersion(this.getOcppVersion());
993 if (this.stationInfo
?.autoRegister
) {
994 this.bootNotificationResponse
= {
995 currentTime
: new Date().toISOString(),
996 interval
: this.getHeartbeatInterval() / 1000,
997 status: RegistrationStatus
.ACCEPTED
,
1002 private initializeOcppConfiguration(): void {
1004 !ChargingStationConfigurationUtils
.getConfigurationKey(
1006 StandardParametersKey
.HeartbeatInterval
1009 ChargingStationConfigurationUtils
.addConfigurationKey(
1011 StandardParametersKey
.HeartbeatInterval
,
1016 !ChargingStationConfigurationUtils
.getConfigurationKey(
1018 StandardParametersKey
.HeartBeatInterval
1021 ChargingStationConfigurationUtils
.addConfigurationKey(
1023 StandardParametersKey
.HeartBeatInterval
,
1029 this.getSupervisionUrlOcppConfiguration() &&
1030 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1032 ChargingStationConfigurationUtils
.addConfigurationKey(
1034 this.getSupervisionUrlOcppKey(),
1035 this.configuredSupervisionUrl
.href
,
1039 !this.getSupervisionUrlOcppConfiguration() &&
1040 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1042 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1044 this.getSupervisionUrlOcppKey(),
1049 this.stationInfo
.amperageLimitationOcppKey
&&
1050 !ChargingStationConfigurationUtils
.getConfigurationKey(
1052 this.stationInfo
.amperageLimitationOcppKey
1055 ChargingStationConfigurationUtils
.addConfigurationKey(
1057 this.stationInfo
.amperageLimitationOcppKey
,
1059 this.stationInfo
.maximumAmperage
*
1060 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1065 !ChargingStationConfigurationUtils
.getConfigurationKey(
1067 StandardParametersKey
.SupportedFeatureProfiles
1070 ChargingStationConfigurationUtils
.addConfigurationKey(
1072 StandardParametersKey
.SupportedFeatureProfiles
,
1073 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1076 ChargingStationConfigurationUtils
.addConfigurationKey(
1078 StandardParametersKey
.NumberOfConnectors
,
1079 this.getNumberOfConnectors().toString(),
1084 !ChargingStationConfigurationUtils
.getConfigurationKey(
1086 StandardParametersKey
.MeterValuesSampledData
1089 ChargingStationConfigurationUtils
.addConfigurationKey(
1091 StandardParametersKey
.MeterValuesSampledData
,
1092 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1096 !ChargingStationConfigurationUtils
.getConfigurationKey(
1098 StandardParametersKey
.ConnectorPhaseRotation
1101 const connectorPhaseRotation
= [];
1102 for (const connectorId
of this.connectors
.keys()) {
1104 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1105 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1106 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1107 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1109 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1110 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1111 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1112 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1115 ChargingStationConfigurationUtils
.addConfigurationKey(
1117 StandardParametersKey
.ConnectorPhaseRotation
,
1118 connectorPhaseRotation
.toString()
1122 !ChargingStationConfigurationUtils
.getConfigurationKey(
1124 StandardParametersKey
.AuthorizeRemoteTxRequests
1127 ChargingStationConfigurationUtils
.addConfigurationKey(
1129 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1134 !ChargingStationConfigurationUtils
.getConfigurationKey(
1136 StandardParametersKey
.LocalAuthListEnabled
1138 ChargingStationConfigurationUtils
.getConfigurationKey(
1140 StandardParametersKey
.SupportedFeatureProfiles
1141 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1143 ChargingStationConfigurationUtils
.addConfigurationKey(
1145 StandardParametersKey
.LocalAuthListEnabled
,
1150 !ChargingStationConfigurationUtils
.getConfigurationKey(
1152 StandardParametersKey
.ConnectionTimeOut
1155 ChargingStationConfigurationUtils
.addConfigurationKey(
1157 StandardParametersKey
.ConnectionTimeOut
,
1158 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1161 this.saveOcppConfiguration();
1164 private initializeConnectors(
1165 stationInfo
: ChargingStationInfo
,
1166 configuredMaxConnectors
: number,
1167 templateMaxConnectors
: number
1169 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1170 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1171 logger
.error(`${this.logPrefix()} ${logMsg}`);
1172 throw new BaseError(logMsg
);
1174 if (!stationInfo
?.Connectors
[0]) {
1176 `${this.logPrefix()} Charging station information from template ${
1178 } with no connector Id 0 configuration`
1181 if (stationInfo
?.Connectors
) {
1182 const connectorsConfigHash
= crypto
1183 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1184 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1186 const connectorsConfigChanged
=
1187 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1188 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1189 connectorsConfigChanged
&& this.connectors
.clear();
1190 this.connectorsConfigurationHash
= connectorsConfigHash
;
1191 // Add connector Id 0
1192 let lastConnector
= '0';
1193 for (lastConnector
in stationInfo
?.Connectors
) {
1194 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1196 lastConnectorId
=== 0 &&
1197 this.getUseConnectorId0(stationInfo
) &&
1198 stationInfo
?.Connectors
[lastConnector
]
1200 this.connectors
.set(
1202 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1204 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1205 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1206 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1210 // Generate all connectors
1211 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1212 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1213 const randConnectorId
= stationInfo
?.randomConnectors
1214 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1216 this.connectors
.set(
1218 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1220 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1221 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1222 this.getConnectorStatus(index
).chargingProfiles
= [];
1229 `${this.logPrefix()} Charging station information from template ${
1231 } with no connectors configuration defined, using already defined connectors`
1234 // Initialize transaction attributes on connectors
1235 for (const connectorId
of this.connectors
.keys()) {
1236 if (connectorId
> 0 && !this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1237 this.initializeConnectorStatus(connectorId
);
1242 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1243 let configuration
: ChargingStationConfiguration
= null;
1244 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1246 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1247 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1248 this.configurationFileHash
1251 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1252 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1253 configuration
= JSON
.parse(
1254 fs
.readFileSync(this.configurationFile
, 'utf8')
1255 ) as ChargingStationConfiguration
;
1256 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1257 this.configurationFileHash
= configuration
.configurationHash
;
1258 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1261 FileUtils
.handleFileException(
1263 FileType
.ChargingStationConfiguration
,
1264 this.configurationFile
,
1265 error
as NodeJS
.ErrnoException
1269 return configuration
;
1272 private saveConfiguration(): void {
1273 if (this.configurationFile
) {
1275 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1276 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1278 const configurationData
: ChargingStationConfiguration
=
1279 this.getConfigurationFromFile() ?? {};
1280 this.ocppConfiguration
?.configurationKey
&&
1281 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1282 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1283 delete configurationData
.configurationHash
;
1284 const configurationHash
= crypto
1285 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1286 .update(JSON
.stringify(configurationData
))
1288 if (this.configurationFileHash
!== configurationHash
) {
1289 configurationData
.configurationHash
= configurationHash
;
1290 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1291 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1292 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1293 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1294 fs
.closeSync(fileDescriptor
);
1295 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1296 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1297 this.configurationFileHash
= configurationHash
;
1298 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1301 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1302 this.configurationFile
1307 FileUtils
.handleFileException(
1309 FileType
.ChargingStationConfiguration
,
1310 this.configurationFile
,
1311 error
as NodeJS
.ErrnoException
1316 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1321 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1322 return this.getTemplateFromFile()?.Configuration
?? null;
1325 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1326 let configuration
: ChargingStationConfiguration
= null;
1327 if (this.getOcppPersistentConfiguration()) {
1328 const configurationFromFile
= this.getConfigurationFromFile();
1329 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1331 configuration
&& delete configuration
.stationInfo
;
1332 return configuration
;
1335 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1336 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1337 if (!ocppConfiguration
) {
1338 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1340 return ocppConfiguration
;
1343 private async onOpen(): Promise
<void> {
1344 if (this.isWebSocketConnectionOpened()) {
1346 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1348 if (!this.isRegistered()) {
1349 // Send BootNotification
1350 let registrationRetryCount
= 0;
1352 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1353 BootNotificationRequest
,
1354 BootNotificationResponse
1357 RequestCommand
.BOOT_NOTIFICATION
,
1359 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1360 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1361 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1362 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1363 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1364 iccid
: this.bootNotificationRequest
.iccid
,
1365 imsi
: this.bootNotificationRequest
.imsi
,
1366 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1367 meterType
: this.bootNotificationRequest
.meterType
,
1369 { skipBufferingOnError
: true }
1371 if (!this.isRegistered()) {
1372 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1374 this.bootNotificationResponse
?.interval
1375 ? this.bootNotificationResponse
.interval
* 1000
1376 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1380 !this.isRegistered() &&
1381 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1382 this.getRegistrationMaxRetries() === -1)
1385 if (this.isRegistered()) {
1386 if (this.isInAcceptedState()) {
1387 await this.startMessageSequence();
1388 this.wsConnectionRestarted
&& this.flushMessageBuffer();
1392 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1395 this.started
=== false && (this.started
= true);
1396 this.autoReconnectRetryCount
= 0;
1397 this.wsConnectionRestarted
= false;
1400 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1405 private async onClose(code
: number, reason
: string): Promise
<void> {
1408 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1409 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1411 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1413 )}' and reason '${reason}'`
1415 this.autoReconnectRetryCount
= 0;
1420 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
1422 )}' and reason '${reason}'`
1424 await this.reconnect(code
);
1429 private async onMessage(data
: Data
): Promise
<void> {
1430 let messageType
: number;
1431 let messageId
: string;
1432 let commandName
: IncomingRequestCommand
;
1433 let commandPayload
: JsonType
;
1434 let errorType
: ErrorType
;
1435 let errorMessage
: string;
1436 let errorDetails
: JsonType
;
1437 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1438 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1439 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1440 let requestPayload
: JsonType
;
1441 let cachedRequest
: CachedRequest
;
1444 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1445 if (Array.isArray(request
) === true) {
1446 [messageType
, messageId
] = request
;
1447 // Check the type of message
1448 switch (messageType
) {
1450 case MessageType
.CALL_MESSAGE
:
1451 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1452 if (this.getEnableStatistics()) {
1453 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1456 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1460 // Process the message
1461 await this.ocppIncomingRequestService
.incomingRequestHandler(
1469 case MessageType
.CALL_RESULT_MESSAGE
:
1470 [, , commandPayload
] = request
as Response
;
1471 if (!this.requests
.has(messageId
)) {
1473 throw new OCPPError(
1474 ErrorType
.INTERNAL_ERROR
,
1475 `Response for unknown message id ${messageId}`,
1481 cachedRequest
= this.requests
.get(messageId
);
1482 if (Array.isArray(cachedRequest
) === true) {
1483 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1485 throw new OCPPError(
1486 ErrorType
.PROTOCOL_ERROR
,
1487 `Cached request for message id ${messageId} response is not an array`,
1489 cachedRequest
as unknown
as JsonType
1493 `${this.logPrefix()} << Command '${
1494 requestCommandName ?? 'unknown'
1495 }' received response payload: ${JSON.stringify(request)}`
1497 responseCallback(commandPayload
, requestPayload
);
1500 case MessageType
.CALL_ERROR_MESSAGE
:
1501 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1502 if (!this.requests
.has(messageId
)) {
1504 throw new OCPPError(
1505 ErrorType
.INTERNAL_ERROR
,
1506 `Error response for unknown message id ${messageId}`,
1508 { errorType
, errorMessage
, errorDetails
}
1511 cachedRequest
= this.requests
.get(messageId
);
1512 if (Array.isArray(cachedRequest
) === true) {
1513 [, errorCallback
, requestCommandName
] = cachedRequest
;
1515 throw new OCPPError(
1516 ErrorType
.PROTOCOL_ERROR
,
1517 `Cached request for message id ${messageId} error response is not an array`,
1519 cachedRequest
as unknown
as JsonType
1523 `${this.logPrefix()} << Command '${
1524 requestCommandName ?? 'unknown'
1525 }' received error payload: ${JSON.stringify(request)}`
1527 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1531 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1532 errMsg
= `Wrong message type ${messageType}`;
1533 logger
.error(`${this.logPrefix()} ${errMsg}`);
1534 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1536 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1538 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1545 `${this.logPrefix()} Incoming OCPP command '${
1546 commandName ?? requestCommandName ?? null
1547 }' message '${data.toString()}' matching cached request '${JSON.stringify(
1548 this.requests.get(messageId)
1549 )}' processing error:`,
1552 if (!(error
instanceof OCPPError
)) {
1554 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1555 commandName ?? requestCommandName ?? null
1556 }' message '${data.toString()}' handling is not an OCPPError:`,
1561 messageType
=== MessageType
.CALL_MESSAGE
&&
1562 (await this.ocppRequestService
.sendError(
1566 commandName
?? requestCommandName
?? null
1571 private onPing(): void {
1572 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1575 private onPong(): void {
1576 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1579 private onError(error
: WSError
): void {
1580 this.closeWSConnection();
1581 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1584 private getEnergyActiveImportRegister(
1585 connectorStatus
: ConnectorStatus
,
1588 if (this.getMeteringPerTransaction()) {
1591 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1592 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1597 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1598 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1602 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean | undefined {
1603 const localStationInfo
= stationInfo
?? this.stationInfo
;
1604 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1605 ? localStationInfo
.useConnectorId0
1609 private getNumberOfRunningTransactions(): number {
1611 for (const connectorId
of this.connectors
.keys()) {
1612 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1620 private getConnectionTimeout(): number | undefined {
1622 ChargingStationConfigurationUtils
.getConfigurationKey(
1624 StandardParametersKey
.ConnectionTimeOut
1629 ChargingStationConfigurationUtils
.getConfigurationKey(
1631 StandardParametersKey
.ConnectionTimeOut
1633 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1636 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1639 // -1 for unlimited, 0 for disabling
1640 private getAutoReconnectMaxRetries(): number | undefined {
1641 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1642 return this.stationInfo
.autoReconnectMaxRetries
;
1644 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1645 return Configuration
.getAutoReconnectMaxRetries();
1651 private getRegistrationMaxRetries(): number | undefined {
1652 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1653 return this.stationInfo
.registrationMaxRetries
;
1658 private getPowerDivider(): number {
1659 let powerDivider
= this.getNumberOfConnectors();
1660 if (this.stationInfo
?.powerSharedByConnectors
) {
1661 powerDivider
= this.getNumberOfRunningTransactions();
1663 return powerDivider
;
1666 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1667 const localStationInfo
= stationInfo
?? this.stationInfo
;
1668 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1671 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1672 const maximumPower
= this.getMaximumPower(stationInfo
);
1673 switch (this.getCurrentOutType(stationInfo
)) {
1674 case CurrentType
.AC
:
1675 return ACElectricUtils
.amperagePerPhaseFromPower(
1676 this.getNumberOfPhases(stationInfo
),
1677 maximumPower
/ this.getNumberOfConnectors(),
1678 this.getVoltageOut(stationInfo
)
1680 case CurrentType
.DC
:
1681 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1685 private getAmperageLimitation(): number | undefined {
1687 this.stationInfo
.amperageLimitationOcppKey
&&
1688 ChargingStationConfigurationUtils
.getConfigurationKey(
1690 this.stationInfo
.amperageLimitationOcppKey
1695 ChargingStationConfigurationUtils
.getConfigurationKey(
1697 this.stationInfo
.amperageLimitationOcppKey
1699 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1704 private async startMessageSequence(): Promise
<void> {
1705 if (this.stationInfo
?.autoRegister
) {
1706 await this.ocppRequestService
.requestHandler
<
1707 BootNotificationRequest
,
1708 BootNotificationResponse
1711 RequestCommand
.BOOT_NOTIFICATION
,
1713 chargePointModel
: this.bootNotificationRequest
.chargePointModel
,
1714 chargePointVendor
: this.bootNotificationRequest
.chargePointVendor
,
1715 chargeBoxSerialNumber
: this.bootNotificationRequest
.chargeBoxSerialNumber
,
1716 firmwareVersion
: this.bootNotificationRequest
.firmwareVersion
,
1717 chargePointSerialNumber
: this.bootNotificationRequest
.chargePointSerialNumber
,
1718 iccid
: this.bootNotificationRequest
.iccid
,
1719 imsi
: this.bootNotificationRequest
.imsi
,
1720 meterSerialNumber
: this.bootNotificationRequest
.meterSerialNumber
,
1721 meterType
: this.bootNotificationRequest
.meterType
,
1723 { skipBufferingOnError
: true }
1726 // Start WebSocket ping
1727 this.startWebSocketPing();
1729 this.startHeartbeat();
1730 // Initialize connectors status
1731 for (const connectorId
of this.connectors
.keys()) {
1732 if (connectorId
=== 0) {
1735 this.started
=== true &&
1736 !this.getConnectorStatus(connectorId
)?.status &&
1737 this.getConnectorStatus(connectorId
)?.bootStatus
1739 // Send status in template at startup
1740 await this.ocppRequestService
.requestHandler
<
1741 StatusNotificationRequest
,
1742 StatusNotificationResponse
1743 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1745 status: this.getConnectorStatus(connectorId
).bootStatus
,
1746 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1748 this.getConnectorStatus(connectorId
).status =
1749 this.getConnectorStatus(connectorId
).bootStatus
;
1751 this.started
=== false &&
1752 this.getConnectorStatus(connectorId
)?.status &&
1753 this.getConnectorStatus(connectorId
)?.bootStatus
1755 // Send status in template after reset
1756 await this.ocppRequestService
.requestHandler
<
1757 StatusNotificationRequest
,
1758 StatusNotificationResponse
1759 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1761 status: this.getConnectorStatus(connectorId
).bootStatus
,
1762 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1764 this.getConnectorStatus(connectorId
).status =
1765 this.getConnectorStatus(connectorId
).bootStatus
;
1766 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1767 // Send previous status at template reload
1768 await this.ocppRequestService
.requestHandler
<
1769 StatusNotificationRequest
,
1770 StatusNotificationResponse
1771 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1773 status: this.getConnectorStatus(connectorId
).status,
1774 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1777 // Send default status
1778 await this.ocppRequestService
.requestHandler
<
1779 StatusNotificationRequest
,
1780 StatusNotificationResponse
1781 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1783 status: ChargePointStatus
.AVAILABLE
,
1784 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1786 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1790 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
) {
1791 this.startAutomaticTransactionGenerator();
1795 private async stopMessageSequence(
1796 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1798 // Stop WebSocket ping
1799 this.stopWebSocketPing();
1801 this.stopHeartbeat();
1802 // Stop ongoing transactions
1803 if (this.getNumberOfRunningTransactions() > 0) {
1804 if (this.automaticTransactionGenerator
?.started
) {
1805 this.stopAutomaticTransactionGenerator();
1807 for (const connectorId
of this.connectors
.keys()) {
1808 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
) {
1809 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
1811 this.getBeginEndMeterValues() &&
1812 this.getOcppStrictCompliance() &&
1813 !this.getOutOfOrderEndMeterValues()
1815 // FIXME: Implement OCPP version agnostic helpers
1816 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1819 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1821 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
1823 RequestCommand
.METER_VALUES
,
1827 meterValue
: [transactionEndMeterValue
],
1831 await this.ocppRequestService
.requestHandler
<
1832 StopTransactionRequest
,
1833 StopTransactionResponse
1834 >(this, RequestCommand
.STOP_TRANSACTION
, {
1836 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
1837 idTag
: this.getTransactionIdTag(transactionId
),
1846 private startWebSocketPing(): void {
1847 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1849 StandardParametersKey
.WebSocketPingInterval
1851 ? Utils
.convertToInt(
1852 ChargingStationConfigurationUtils
.getConfigurationKey(
1854 StandardParametersKey
.WebSocketPingInterval
1858 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1859 this.webSocketPingSetInterval
= setInterval(() => {
1860 if (this.isWebSocketConnectionOpened()) {
1861 this.wsConnection
.ping((): void => {
1862 /* This is intentional */
1865 }, webSocketPingInterval
* 1000);
1868 ' WebSocket ping started every ' +
1869 Utils
.formatDurationSeconds(webSocketPingInterval
)
1871 } else if (this.webSocketPingSetInterval
) {
1874 ' WebSocket ping every ' +
1875 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1880 `${this.logPrefix()} WebSocket ping interval set to ${
1881 webSocketPingInterval
1882 ? Utils.formatDurationSeconds(webSocketPingInterval)
1883 : webSocketPingInterval
1884 }, not starting the WebSocket ping`
1889 private stopWebSocketPing(): void {
1890 if (this.webSocketPingSetInterval
) {
1891 clearInterval(this.webSocketPingSetInterval
);
1895 private getConfiguredSupervisionUrl(): URL
{
1896 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1897 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1899 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1901 switch (Configuration
.getSupervisionUrlDistribution()) {
1902 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1903 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1905 case SupervisionUrlDistribution
.RANDOM
:
1907 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1909 case SupervisionUrlDistribution
.SEQUENTIAL
:
1910 if (this.index
<= supervisionUrls
.length
) {
1911 urlIndex
= this.index
- 1;
1914 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1920 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1921 SupervisionUrlDistribution.ROUND_ROBIN
1924 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1927 return new URL(supervisionUrls
[urlIndex
]);
1929 return new URL(supervisionUrls
as string);
1932 private getHeartbeatInterval(): number | undefined {
1933 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1935 StandardParametersKey
.HeartbeatInterval
1937 if (HeartbeatInterval
) {
1938 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1940 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1942 StandardParametersKey
.HeartBeatInterval
1944 if (HeartBeatInterval
) {
1945 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1947 !this.stationInfo
?.autoRegister
&&
1949 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1950 Constants.DEFAULT_HEARTBEAT_INTERVAL
1953 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1956 private stopHeartbeat(): void {
1957 if (this.heartbeatSetInterval
) {
1958 clearInterval(this.heartbeatSetInterval
);
1962 private terminateWSConnection(): void {
1963 if (this.isWebSocketConnectionOpened()) {
1964 this.wsConnection
.terminate();
1965 this.wsConnection
= null;
1969 private stopMeterValues(connectorId
: number) {
1970 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1971 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1975 private getReconnectExponentialDelay(): boolean | undefined {
1976 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
1977 ? this.stationInfo
.reconnectExponentialDelay
1981 private async reconnect(code
: number): Promise
<void> {
1982 // Stop WebSocket ping
1983 this.stopWebSocketPing();
1985 this.stopHeartbeat();
1986 // Stop the ATG if needed
1987 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
) {
1988 this.stopAutomaticTransactionGenerator();
1991 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
1992 this.getAutoReconnectMaxRetries() === -1
1994 this.autoReconnectRetryCount
++;
1995 const reconnectDelay
= this.getReconnectExponentialDelay()
1996 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
1997 : this.getConnectionTimeout() * 1000;
1998 const reconnectDelayWithdraw
= 1000;
1999 const reconnectTimeout
=
2000 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2001 ? reconnectDelay
- reconnectDelayWithdraw
2004 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2007 )}ms, timeout ${reconnectTimeout}ms`
2009 await Utils
.sleep(reconnectDelay
);
2012 ' WebSocket: reconnecting try #' +
2013 this.autoReconnectRetryCount
.toString()
2015 this.openWSConnection(
2016 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2017 { closeOpened
: true }
2019 this.wsConnectionRestarted
= true;
2020 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2022 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2023 this.autoReconnectRetryCount
2024 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2029 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2030 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2033 private initializeConnectorStatus(connectorId
: number): void {
2034 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2035 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2036 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2037 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2038 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2039 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;