1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import crypto from
'crypto';
5 import path from
'path';
6 import { URL
} from
'url';
7 import { parentPort
} from
'worker_threads';
9 import WebSocket
, { Data
, RawData
} from
'ws';
11 import BaseError from
'../exception/BaseError';
12 import OCPPError from
'../exception/OCPPError';
13 import PerformanceStatistics from
'../performance/PerformanceStatistics';
14 import type { AutomaticTransactionGeneratorConfiguration
} from
'../types/AutomaticTransactionGenerator';
15 import type ChargingStationConfiguration from
'../types/ChargingStationConfiguration';
16 import type ChargingStationInfo from
'../types/ChargingStationInfo';
17 import type ChargingStationOcppConfiguration from
'../types/ChargingStationOcppConfiguration';
18 import ChargingStationTemplate
, {
22 } from
'../types/ChargingStationTemplate';
23 import { SupervisionUrlDistribution
} from
'../types/ConfigurationData';
24 import type { ConnectorStatus
} from
'../types/ConnectorStatus';
25 import { FileType
} from
'../types/FileType';
26 import type { JsonType
} from
'../types/JsonType';
27 import { ChargePointErrorCode
} from
'../types/ocpp/ChargePointErrorCode';
28 import { ChargePointStatus
} from
'../types/ocpp/ChargePointStatus';
29 import { ChargingProfile
, ChargingRateUnitType
} from
'../types/ocpp/ChargingProfile';
31 ConnectorPhaseRotation
,
32 StandardParametersKey
,
33 SupportedFeatureProfiles
,
34 VendorDefaultParametersKey
,
35 } from
'../types/ocpp/Configuration';
36 import { ErrorType
} from
'../types/ocpp/ErrorType';
37 import { MessageType
} from
'../types/ocpp/MessageType';
38 import { MeterValue
, MeterValueMeasurand
} from
'../types/ocpp/MeterValues';
39 import { OCPPVersion
} from
'../types/ocpp/OCPPVersion';
42 BootNotificationRequest
,
46 IncomingRequestCommand
,
49 StatusNotificationRequest
,
50 } from
'../types/ocpp/Requests';
52 BootNotificationResponse
,
58 StatusNotificationResponse
,
59 } from
'../types/ocpp/Responses';
61 StopTransactionReason
,
62 StopTransactionRequest
,
63 StopTransactionResponse
,
64 } from
'../types/ocpp/Transaction';
65 import { WSError
, WebSocketCloseEventStatusCode
} from
'../types/WebSocket';
66 import Configuration from
'../utils/Configuration';
67 import Constants from
'../utils/Constants';
68 import { ACElectricUtils
, DCElectricUtils
} from
'../utils/ElectricUtils';
69 import FileUtils from
'../utils/FileUtils';
70 import logger from
'../utils/Logger';
71 import Utils from
'../utils/Utils';
72 import AuthorizedTagsCache from
'./AuthorizedTagsCache';
73 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
74 import { ChargingStationConfigurationUtils
} from
'./ChargingStationConfigurationUtils';
75 import { ChargingStationUtils
} from
'./ChargingStationUtils';
76 import ChargingStationWorkerBroadcastChannel from
'./ChargingStationWorkerBroadcastChannel';
77 import { MessageChannelUtils
} from
'./MessageChannelUtils';
78 import OCPP16IncomingRequestService from
'./ocpp/1.6/OCPP16IncomingRequestService';
79 import OCPP16RequestService from
'./ocpp/1.6/OCPP16RequestService';
80 import OCPP16ResponseService from
'./ocpp/1.6/OCPP16ResponseService';
81 import { OCPP16ServiceUtils
} from
'./ocpp/1.6/OCPP16ServiceUtils';
82 import type OCPPIncomingRequestService from
'./ocpp/OCPPIncomingRequestService';
83 import type OCPPRequestService from
'./ocpp/OCPPRequestService';
84 import SharedLRUCache from
'./SharedLRUCache';
86 export default class ChargingStation
{
87 public readonly templateFile
: string;
88 public stationInfo
!: ChargingStationInfo
;
89 public started
: boolean;
90 public authorizedTagsCache
: AuthorizedTagsCache
;
91 public automaticTransactionGenerator
!: AutomaticTransactionGenerator
;
92 public ocppConfiguration
!: ChargingStationOcppConfiguration
;
93 public wsConnection
!: WebSocket
;
94 public readonly connectors
: Map
<number, ConnectorStatus
>;
95 public readonly requests
: Map
<string, CachedRequest
>;
96 public performanceStatistics
!: PerformanceStatistics
;
97 public heartbeatSetInterval
!: NodeJS
.Timeout
;
98 public ocppRequestService
!: OCPPRequestService
;
99 public bootNotificationRequest
!: BootNotificationRequest
;
100 public bootNotificationResponse
!: BootNotificationResponse
| null;
101 public powerDivider
!: number;
102 private starting
: boolean;
103 private stopping
: boolean;
104 private readonly index
: number;
105 private configurationFile
!: string;
106 private configurationFileHash
!: string;
107 private connectorsConfigurationHash
!: string;
108 private ocppIncomingRequestService
!: OCPPIncomingRequestService
;
109 private readonly messageBuffer
: Set
<string>;
110 private configuredSupervisionUrl
!: URL
;
111 private wsConnectionRestarted
: boolean;
112 private autoReconnectRetryCount
: number;
113 private templateFileWatcher
!: fs
.FSWatcher
;
114 private readonly sharedLRUCache
: SharedLRUCache
;
115 private webSocketPingSetInterval
!: NodeJS
.Timeout
;
116 private readonly chargingStationWorkerBroadcastChannel
: ChargingStationWorkerBroadcastChannel
;
118 constructor(index
: number, templateFile
: string) {
119 this.started
= false;
120 this.starting
= false;
121 this.stopping
= false;
122 this.wsConnectionRestarted
= false;
123 this.autoReconnectRetryCount
= 0;
125 this.templateFile
= templateFile
;
126 this.connectors
= new Map
<number, ConnectorStatus
>();
127 this.requests
= new Map
<string, CachedRequest
>();
128 this.messageBuffer
= new Set
<string>();
129 this.sharedLRUCache
= SharedLRUCache
.getInstance();
130 this.authorizedTagsCache
= AuthorizedTagsCache
.getInstance();
131 this.chargingStationWorkerBroadcastChannel
= new ChargingStationWorkerBroadcastChannel(this);
136 private get
wsConnectionUrl(): URL
{
138 (this.getSupervisionUrlOcppConfiguration()
139 ? ChargingStationConfigurationUtils
.getConfigurationKey(
141 this.getSupervisionUrlOcppKey()
143 : this.configuredSupervisionUrl
.href
) +
145 this.stationInfo
.chargingStationId
149 public logPrefix(): string {
150 return Utils
.logPrefix(
152 this?.stationInfo?.chargingStationId ??
153 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
158 public getRandomIdTag(): string {
159 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(this.stationInfo
);
160 const index
= Math.floor(
161 Utils
.secureRandom() * this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
).length
163 return this.authorizedTagsCache
.getAuthorizedTags(authorizationFile
)[index
];
166 public hasAuthorizedTags(): boolean {
167 return !Utils
.isEmptyArray(
168 this.authorizedTagsCache
.getAuthorizedTags(
169 ChargingStationUtils
.getAuthorizationFile(this.stationInfo
)
174 public getEnableStatistics(): boolean | undefined {
175 return !Utils
.isUndefined(this.stationInfo
.enableStatistics
)
176 ? this.stationInfo
.enableStatistics
180 public getMustAuthorizeAtRemoteStart(): boolean | undefined {
181 return this.stationInfo
.mustAuthorizeAtRemoteStart
?? true;
184 public getPayloadSchemaValidation(): boolean | undefined {
185 return this.stationInfo
.payloadSchemaValidation
?? true;
188 public getNumberOfPhases(stationInfo
?: ChargingStationInfo
): number | undefined {
189 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
190 switch (this.getCurrentOutType(stationInfo
)) {
192 return !Utils
.isUndefined(localStationInfo
.numberOfPhases
)
193 ? localStationInfo
.numberOfPhases
200 public isWebSocketConnectionOpened(): boolean {
201 return this?.wsConnection
?.readyState
=== WebSocket
.OPEN
;
204 public getRegistrationStatus(): RegistrationStatus
{
205 return this?.bootNotificationResponse
?.status;
208 public isInUnknownState(): boolean {
209 return Utils
.isNullOrUndefined(this?.bootNotificationResponse
?.status);
212 public isInPendingState(): boolean {
213 return this?.bootNotificationResponse
?.status === RegistrationStatus
.PENDING
;
216 public isInAcceptedState(): boolean {
217 return this?.bootNotificationResponse
?.status === RegistrationStatus
.ACCEPTED
;
220 public isInRejectedState(): boolean {
221 return this?.bootNotificationResponse
?.status === RegistrationStatus
.REJECTED
;
224 public isRegistered(): boolean {
225 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
228 public isChargingStationAvailable(): boolean {
229 return this.getConnectorStatus(0).availability
=== AvailabilityType
.OPERATIVE
;
232 public isConnectorAvailable(id
: number): boolean {
233 return id
> 0 && this.getConnectorStatus(id
).availability
=== AvailabilityType
.OPERATIVE
;
236 public getNumberOfConnectors(): number {
237 return this.connectors
.get(0) ? this.connectors
.size
- 1 : this.connectors
.size
;
240 public getConnectorStatus(id
: number): ConnectorStatus
| undefined {
241 return this.connectors
.get(id
);
244 public getCurrentOutType(stationInfo
?: ChargingStationInfo
): CurrentType
{
245 return (stationInfo
?? this.stationInfo
).currentOutType
?? CurrentType
.AC
;
248 public getOcppStrictCompliance(): boolean {
249 return this.stationInfo
?.ocppStrictCompliance
?? false;
252 public getVoltageOut(stationInfo
?: ChargingStationInfo
): number | undefined {
253 const defaultVoltageOut
= ChargingStationUtils
.getDefaultVoltageOut(
254 this.getCurrentOutType(stationInfo
),
258 const localStationInfo
: ChargingStationInfo
= stationInfo
?? this.stationInfo
;
259 return !Utils
.isUndefined(localStationInfo
.voltageOut
)
260 ? localStationInfo
.voltageOut
264 public getConnectorMaximumAvailablePower(connectorId
: number): number {
265 let connectorAmperageLimitationPowerLimit
: number;
267 !Utils
.isNullOrUndefined(this.getAmperageLimitation()) &&
268 this.getAmperageLimitation() < this.stationInfo
.maximumAmperage
270 connectorAmperageLimitationPowerLimit
=
271 (this.getCurrentOutType() === CurrentType
.AC
272 ? ACElectricUtils
.powerTotal(
273 this.getNumberOfPhases(),
274 this.getVoltageOut(),
275 this.getAmperageLimitation() * this.getNumberOfConnectors()
277 : DCElectricUtils
.power(this.getVoltageOut(), this.getAmperageLimitation())) /
280 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
281 const connectorChargingProfilePowerLimit
= this.getChargingProfilePowerLimit(connectorId
);
283 isNaN(connectorMaximumPower
) ? Infinity : connectorMaximumPower
,
284 isNaN(connectorAmperageLimitationPowerLimit
)
286 : connectorAmperageLimitationPowerLimit
,
287 isNaN(connectorChargingProfilePowerLimit
) ? Infinity : connectorChargingProfilePowerLimit
291 public getTransactionIdTag(transactionId
: number): string | undefined {
292 for (const connectorId
of this.connectors
.keys()) {
293 if (connectorId
> 0 && this.getConnectorStatus(connectorId
).transactionId
=== transactionId
) {
294 return this.getConnectorStatus(connectorId
).transactionIdTag
;
299 public getOutOfOrderEndMeterValues(): boolean {
300 return this.stationInfo
?.outOfOrderEndMeterValues
?? false;
303 public getBeginEndMeterValues(): boolean {
304 return this.stationInfo
?.beginEndMeterValues
?? false;
307 public getMeteringPerTransaction(): boolean {
308 return this.stationInfo
?.meteringPerTransaction
?? true;
311 public getTransactionDataMeterValues(): boolean {
312 return this.stationInfo
?.transactionDataMeterValues
?? false;
315 public getMainVoltageMeterValues(): boolean {
316 return this.stationInfo
?.mainVoltageMeterValues
?? true;
319 public getPhaseLineToLineVoltageMeterValues(): boolean {
320 return this.stationInfo
?.phaseLineToLineVoltageMeterValues
?? false;
323 public getCustomValueLimitationMeterValues(): boolean {
324 return this.stationInfo
?.customValueLimitationMeterValues
?? true;
327 public getConnectorIdByTransactionId(transactionId
: number): number | undefined {
328 for (const connectorId
of this.connectors
.keys()) {
331 this.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
338 public getEnergyActiveImportRegisterByTransactionId(
339 transactionId
: number,
342 return this.getEnergyActiveImportRegister(
343 this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId
)),
348 public getEnergyActiveImportRegisterByConnectorId(connectorId
: number): number {
349 return this.getEnergyActiveImportRegister(this.getConnectorStatus(connectorId
));
352 public getAuthorizeRemoteTxRequests(): boolean {
353 const authorizeRemoteTxRequests
= ChargingStationConfigurationUtils
.getConfigurationKey(
355 StandardParametersKey
.AuthorizeRemoteTxRequests
357 return authorizeRemoteTxRequests
358 ? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
)
362 public getLocalAuthListEnabled(): boolean {
363 const localAuthListEnabled
= ChargingStationConfigurationUtils
.getConfigurationKey(
365 StandardParametersKey
.LocalAuthListEnabled
367 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
370 public startHeartbeat(): void {
372 this.getHeartbeatInterval() &&
373 this.getHeartbeatInterval() > 0 &&
374 !this.heartbeatSetInterval
376 // eslint-disable-next-line @typescript-eslint/no-misused-promises
377 this.heartbeatSetInterval
= setInterval(async (): Promise
<void> => {
378 await this.ocppRequestService
.requestHandler
<HeartbeatRequest
, HeartbeatResponse
>(
380 RequestCommand
.HEARTBEAT
382 }, this.getHeartbeatInterval());
385 ' Heartbeat started every ' +
386 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
388 } else if (this.heartbeatSetInterval
) {
391 ' Heartbeat already started every ' +
392 Utils
.formatDurationMilliSeconds(this.getHeartbeatInterval())
396 `${this.logPrefix()} Heartbeat interval set to ${
397 this.getHeartbeatInterval()
398 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
399 : this.getHeartbeatInterval()
400 }, not starting the heartbeat`
405 public restartHeartbeat(): void {
407 this.stopHeartbeat();
409 this.startHeartbeat();
412 public restartWebSocketPing(): void {
413 // Stop WebSocket ping
414 this.stopWebSocketPing();
415 // Start WebSocket ping
416 this.startWebSocketPing();
419 public startMeterValues(connectorId
: number, interval
: number): void {
420 if (connectorId
=== 0) {
422 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
426 if (!this.getConnectorStatus(connectorId
)) {
428 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
432 if (this.getConnectorStatus(connectorId
)?.transactionStarted
=== false) {
434 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
438 this.getConnectorStatus(connectorId
)?.transactionStarted
=== true &&
439 !this.getConnectorStatus(connectorId
)?.transactionId
442 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
447 // eslint-disable-next-line @typescript-eslint/no-misused-promises
448 this.getConnectorStatus(connectorId
).transactionSetInterval
= setInterval(
449 // eslint-disable-next-line @typescript-eslint/no-misused-promises
450 async (): Promise
<void> => {
451 // FIXME: Implement OCPP version agnostic helpers
452 const meterValue
: MeterValue
= OCPP16ServiceUtils
.buildMeterValue(
455 this.getConnectorStatus(connectorId
).transactionId
,
458 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
460 RequestCommand
.METER_VALUES
,
463 transactionId
: this.getConnectorStatus(connectorId
).transactionId
,
464 meterValue
: [meterValue
],
472 `${this.logPrefix()} Charging station ${
473 StandardParametersKey.MeterValueSampleInterval
474 } configuration set to ${
475 interval ? Utils.formatDurationMilliSeconds(interval) : interval
476 }, not sending MeterValues`
481 public start(): void {
482 if (this.started
=== false) {
483 if (this.starting
=== false) {
484 this.starting
= true;
485 if (this.getEnableStatistics()) {
486 this.performanceStatistics
.start();
488 this.openWSConnection();
489 // Monitor charging station template file
490 this.templateFileWatcher
= FileUtils
.watchJsonFile(
492 FileType
.ChargingStationTemplate
,
495 (event
, filename
): void => {
496 if (filename
&& event
=== 'change') {
499 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
501 } file have changed, reload`
503 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
507 this.stopAutomaticTransactionGenerator();
509 this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true
511 this.startAutomaticTransactionGenerator();
513 if (this.getEnableStatistics()) {
514 this.performanceStatistics
.restart();
516 this.performanceStatistics
.stop();
518 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
521 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
528 parentPort
.postMessage(MessageChannelUtils
.buildStartedMessage(this));
529 this.starting
= false;
531 logger
.warn(`${this.logPrefix()} Charging station is already starting...`);
534 logger
.warn(`${this.logPrefix()} Charging station is already started...`);
538 public async stop(reason
?: StopTransactionReason
): Promise
<void> {
539 if (this.started
=== true) {
540 if (this.stopping
=== false) {
541 this.stopping
= true;
542 await this.stopMessageSequence(reason
);
543 for (const connectorId
of this.connectors
.keys()) {
544 if (connectorId
> 0) {
545 await this.ocppRequestService
.requestHandler
<
546 StatusNotificationRequest
,
547 StatusNotificationResponse
548 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
550 status: ChargePointStatus
.UNAVAILABLE
,
551 errorCode
: ChargePointErrorCode
.NO_ERROR
,
553 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.UNAVAILABLE
;
556 this.closeWSConnection();
557 if (this.getEnableStatistics()) {
558 this.performanceStatistics
.stop();
560 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
561 this.templateFileWatcher
.close();
562 this.sharedLRUCache
.deleteChargingStationTemplate(this.stationInfo
?.templateHash
);
563 this.bootNotificationResponse
= null;
564 this.started
= false;
565 parentPort
.postMessage(MessageChannelUtils
.buildStoppedMessage(this));
566 this.stopping
= false;
568 logger
.warn(`${this.logPrefix()} Charging station is already stopping...`);
571 logger
.warn(`${this.logPrefix()} Charging station is already stopped...`);
575 public async reset(reason
?: StopTransactionReason
): Promise
<void> {
576 await this.stop(reason
);
577 await Utils
.sleep(this.stationInfo
.resetTime
);
582 public saveOcppConfiguration(): void {
583 if (this.getOcppPersistentConfiguration()) {
584 this.saveConfiguration();
588 public setChargingProfile(connectorId
: number, cp
: ChargingProfile
): void {
589 if (Utils
.isNullOrUndefined(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
591 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
593 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
595 if (Array.isArray(this.getConnectorStatus(connectorId
).chargingProfiles
) === false) {
597 `${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`
599 this.getConnectorStatus(connectorId
).chargingProfiles
= [];
601 let cpReplaced
= false;
602 if (!Utils
.isEmptyArray(this.getConnectorStatus(connectorId
).chargingProfiles
)) {
603 this.getConnectorStatus(connectorId
).chargingProfiles
?.forEach(
604 (chargingProfile
: ChargingProfile
, index
: number) => {
606 chargingProfile
.chargingProfileId
=== cp
.chargingProfileId
||
607 (chargingProfile
.stackLevel
=== cp
.stackLevel
&&
608 chargingProfile
.chargingProfilePurpose
=== cp
.chargingProfilePurpose
)
610 this.getConnectorStatus(connectorId
).chargingProfiles
[index
] = cp
;
616 !cpReplaced
&& this.getConnectorStatus(connectorId
).chargingProfiles
?.push(cp
);
619 public resetConnectorStatus(connectorId
: number): void {
620 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
621 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
622 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
623 this.getConnectorStatus(connectorId
).transactionStarted
= false;
624 delete this.getConnectorStatus(connectorId
).localAuthorizeIdTag
;
625 delete this.getConnectorStatus(connectorId
).authorizeIdTag
;
626 delete this.getConnectorStatus(connectorId
).transactionId
;
627 delete this.getConnectorStatus(connectorId
).transactionIdTag
;
628 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
629 delete this.getConnectorStatus(connectorId
).transactionBeginMeterValue
;
630 this.stopMeterValues(connectorId
);
631 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
634 public hasFeatureProfile(featureProfile
: SupportedFeatureProfiles
) {
635 return ChargingStationConfigurationUtils
.getConfigurationKey(
637 StandardParametersKey
.SupportedFeatureProfiles
638 )?.value
.includes(featureProfile
);
641 public bufferMessage(message
: string): void {
642 this.messageBuffer
.add(message
);
645 public openWSConnection(
646 options
: WsOptions
= this.stationInfo
?.wsOptions
?? {},
647 params
: { closeOpened
?: boolean; terminateOpened
?: boolean } = {
649 terminateOpened
: false,
652 options
.handshakeTimeout
= options
?.handshakeTimeout
?? this.getConnectionTimeout() * 1000;
653 params
.closeOpened
= params
?.closeOpened
?? false;
654 params
.terminateOpened
= params
?.terminateOpened
?? false;
656 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionUser
) &&
657 !Utils
.isNullOrUndefined(this.stationInfo
.supervisionPassword
)
659 options
.auth
= `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
661 if (params
?.closeOpened
) {
662 this.closeWSConnection();
664 if (params
?.terminateOpened
) {
665 this.terminateWSConnection();
667 let protocol
: string;
668 switch (this.getOcppVersion()) {
669 case OCPPVersion
.VERSION_16
:
670 protocol
= 'ocpp' + OCPPVersion
.VERSION_16
;
673 this.handleUnsupportedVersion(this.getOcppVersion());
677 if (this.isWebSocketConnectionOpened()) {
679 `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} is already opened`
685 `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`
688 this.wsConnection
= new WebSocket(this.wsConnectionUrl
, protocol
, options
);
690 // Handle WebSocket message
691 this.wsConnection
.on(
693 this.onMessage
.bind(this) as (this: WebSocket
, data
: RawData
, isBinary
: boolean) => void
695 // Handle WebSocket error
696 this.wsConnection
.on(
698 this.onError
.bind(this) as (this: WebSocket
, error
: Error) => void
700 // Handle WebSocket close
701 this.wsConnection
.on(
703 this.onClose
.bind(this) as (this: WebSocket
, code
: number, reason
: Buffer
) => void
705 // Handle WebSocket open
706 this.wsConnection
.on('open', this.onOpen
.bind(this) as (this: WebSocket
) => void);
707 // Handle WebSocket ping
708 this.wsConnection
.on('ping', this.onPing
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
709 // Handle WebSocket pong
710 this.wsConnection
.on('pong', this.onPong
.bind(this) as (this: WebSocket
, data
: Buffer
) => void);
713 public closeWSConnection(): void {
714 if (this.isWebSocketConnectionOpened()) {
715 this.wsConnection
.close();
716 this.wsConnection
= null;
720 public startAutomaticTransactionGenerator(connectorIds
?: number[]): void {
721 if (!this.automaticTransactionGenerator
) {
722 this.automaticTransactionGenerator
= AutomaticTransactionGenerator
.getInstance(
723 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
727 if (!Utils
.isEmptyArray(connectorIds
)) {
728 for (const connectorId
of connectorIds
) {
729 this.automaticTransactionGenerator
.startConnector(connectorId
);
732 this.automaticTransactionGenerator
.start();
736 public stopAutomaticTransactionGenerator(connectorIds
?: number[]): void {
737 if (!Utils
.isEmptyArray(connectorIds
)) {
738 for (const connectorId
of connectorIds
) {
739 this.automaticTransactionGenerator
?.stopConnector(connectorId
);
740 // FIXME: check if the number of connectors match the CS number of connectors
743 this.automaticTransactionGenerator
?.stop();
744 this.automaticTransactionGenerator
= null;
748 public async stopTransactionOnConnector(
750 reason
= StopTransactionReason
.NONE
751 ): Promise
<StopTransactionResponse
> {
752 const transactionId
= this.getConnectorStatus(connectorId
).transactionId
;
754 this.getBeginEndMeterValues() &&
755 this.getOcppStrictCompliance() &&
756 !this.getOutOfOrderEndMeterValues()
758 // FIXME: Implement OCPP version agnostic helpers
759 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
762 this.getEnergyActiveImportRegisterByTransactionId(transactionId
)
764 await this.ocppRequestService
.requestHandler
<MeterValuesRequest
, MeterValuesResponse
>(
766 RequestCommand
.METER_VALUES
,
770 meterValue
: [transactionEndMeterValue
],
774 return this.ocppRequestService
.requestHandler
<StopTransactionRequest
, StopTransactionResponse
>(
776 RequestCommand
.STOP_TRANSACTION
,
779 meterStop
: this.getEnergyActiveImportRegisterByTransactionId(transactionId
, true),
785 private flushMessageBuffer(): void {
786 if (this.messageBuffer
.size
> 0) {
787 this.messageBuffer
.forEach((message
) => {
788 // TODO: evaluate the need to track performance
789 this.wsConnection
.send(message
);
790 this.messageBuffer
.delete(message
);
795 private getSupervisionUrlOcppConfiguration(): boolean {
796 return this.stationInfo
.supervisionUrlOcppConfiguration
?? false;
799 private getSupervisionUrlOcppKey(): string {
800 return this.stationInfo
.supervisionUrlOcppKey
?? VendorDefaultParametersKey
.ConnectionUrl
;
803 private getTemplateFromFile(): ChargingStationTemplate
| null {
804 let template
: ChargingStationTemplate
= null;
806 if (this.sharedLRUCache
.hasChargingStationTemplate(this.stationInfo
?.templateHash
)) {
807 template
= this.sharedLRUCache
.getChargingStationTemplate(this.stationInfo
.templateHash
);
809 const measureId
= `${FileType.ChargingStationTemplate} read`;
810 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
811 template
= JSON
.parse(
812 fs
.readFileSync(this.templateFile
, 'utf8')
813 ) as ChargingStationTemplate
;
814 PerformanceStatistics
.endMeasure(measureId
, beginId
);
815 template
.templateHash
= crypto
816 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
817 .update(JSON
.stringify(template
))
819 this.sharedLRUCache
.setChargingStationTemplate(template
);
822 FileUtils
.handleFileException(
824 FileType
.ChargingStationTemplate
,
826 error
as NodeJS
.ErrnoException
832 private getStationInfoFromTemplate(): ChargingStationInfo
{
833 const stationTemplate
: ChargingStationTemplate
= this.getTemplateFromFile();
834 if (Utils
.isNullOrUndefined(stationTemplate
)) {
835 const errorMsg
= 'Failed to read charging station template file';
836 logger
.error(`${this.logPrefix()} ${errorMsg}`);
837 throw new BaseError(errorMsg
);
839 if (Utils
.isEmptyObject(stationTemplate
)) {
840 const errorMsg
= `Empty charging station information from template file ${this.templateFile}`;
841 logger
.error(`${this.logPrefix()} ${errorMsg}`);
842 throw new BaseError(errorMsg
);
844 // Deprecation template keys section
845 ChargingStationUtils
.warnDeprecatedTemplateKey(
850 "Use 'supervisionUrls' instead"
852 ChargingStationUtils
.convertDeprecatedTemplateKey(
857 const stationInfo
: ChargingStationInfo
=
858 ChargingStationUtils
.stationTemplateToStationInfo(stationTemplate
);
859 stationInfo
.hashId
= ChargingStationUtils
.getHashId(this.index
, stationTemplate
);
860 stationInfo
.chargingStationId
= ChargingStationUtils
.getChargingStationId(
864 ChargingStationUtils
.createSerialNumber(stationTemplate
, stationInfo
);
865 if (!Utils
.isEmptyArray(stationTemplate
.power
)) {
866 stationTemplate
.power
= stationTemplate
.power
as number[];
867 const powerArrayRandomIndex
= Math.floor(Utils
.secureRandom() * stationTemplate
.power
.length
);
868 stationInfo
.maximumPower
=
869 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
870 ? stationTemplate
.power
[powerArrayRandomIndex
] * 1000
871 : stationTemplate
.power
[powerArrayRandomIndex
];
873 stationTemplate
.power
= stationTemplate
.power
as number;
874 stationInfo
.maximumPower
=
875 stationTemplate
.powerUnit
=== PowerUnits
.KILO_WATT
876 ? stationTemplate
.power
* 1000
877 : stationTemplate
.power
;
879 stationInfo
.resetTime
= stationTemplate
.resetTime
880 ? stationTemplate
.resetTime
* 1000
881 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
882 const configuredMaxConnectors
= ChargingStationUtils
.getConfiguredNumberOfConnectors(
886 ChargingStationUtils
.checkConfiguredMaxConnectors(
887 configuredMaxConnectors
,
891 const templateMaxConnectors
=
892 ChargingStationUtils
.getTemplateMaxNumberOfConnectors(stationTemplate
);
893 ChargingStationUtils
.checkTemplateMaxConnectors(
894 templateMaxConnectors
,
899 configuredMaxConnectors
>
900 (stationTemplate
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) &&
901 !stationTemplate
?.randomConnectors
904 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
906 }, forcing random connector configurations affectation`
908 stationInfo
.randomConnectors
= true;
910 // Build connectors if needed (FIXME: should be factored out)
911 this.initializeConnectors(stationInfo
, configuredMaxConnectors
, templateMaxConnectors
);
912 stationInfo
.maximumAmperage
= this.getMaximumAmperage(stationInfo
);
913 ChargingStationUtils
.createStationInfoHash(stationInfo
);
917 private getStationInfoFromFile(): ChargingStationInfo
| null {
918 let stationInfo
: ChargingStationInfo
= null;
919 this.getStationInfoPersistentConfiguration() &&
920 (stationInfo
= this.getConfigurationFromFile()?.stationInfo
?? null);
921 stationInfo
&& ChargingStationUtils
.createStationInfoHash(stationInfo
);
925 private getStationInfo(): ChargingStationInfo
{
926 const stationInfoFromTemplate
: ChargingStationInfo
= this.getStationInfoFromTemplate();
927 const stationInfoFromFile
: ChargingStationInfo
= this.getStationInfoFromFile();
928 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
929 if (stationInfoFromFile
?.templateHash
=== stationInfoFromTemplate
.templateHash
) {
930 if (this.stationInfo
?.infoHash
=== stationInfoFromFile
?.infoHash
) {
931 return this.stationInfo
;
933 return stationInfoFromFile
;
935 stationInfoFromFile
&&
936 ChargingStationUtils
.propagateSerialNumber(
937 this.getTemplateFromFile(),
939 stationInfoFromTemplate
941 return stationInfoFromTemplate
;
944 private saveStationInfo(): void {
945 if (this.getStationInfoPersistentConfiguration()) {
946 this.saveConfiguration();
950 private getOcppVersion(): OCPPVersion
{
951 return this.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
;
954 private getOcppPersistentConfiguration(): boolean {
955 return this.stationInfo
?.ocppPersistentConfiguration
?? true;
958 private getStationInfoPersistentConfiguration(): boolean {
959 return this.stationInfo
?.stationInfoPersistentConfiguration
?? true;
962 private handleUnsupportedVersion(version
: OCPPVersion
) {
963 const errMsg
= `Unsupported protocol version '${version}' configured in template file ${this.templateFile}`;
964 logger
.error(`${this.logPrefix()} ${errMsg}`);
965 throw new BaseError(errMsg
);
968 private initialize(): void {
969 this.configurationFile
= path
.join(
970 path
.dirname(this.templateFile
.replace('station-templates', 'configurations')),
971 ChargingStationUtils
.getHashId(this.index
, this.getTemplateFromFile()) + '.json'
973 this.stationInfo
= this.getStationInfo();
974 this.saveStationInfo();
975 logger
.info(`${this.logPrefix()} Charging station hashId '${this.stationInfo.hashId}'`);
976 // Avoid duplication of connectors related information in RAM
977 this.stationInfo
?.Connectors
&& delete this.stationInfo
.Connectors
;
978 this.configuredSupervisionUrl
= this.getConfiguredSupervisionUrl();
979 if (this.getEnableStatistics()) {
980 this.performanceStatistics
= PerformanceStatistics
.getInstance(
981 this.stationInfo
.hashId
,
982 this.stationInfo
.chargingStationId
,
983 this.configuredSupervisionUrl
986 this.bootNotificationRequest
= ChargingStationUtils
.createBootNotificationRequest(
989 this.powerDivider
= this.getPowerDivider();
990 // OCPP configuration
991 this.ocppConfiguration
= this.getOcppConfiguration();
992 this.initializeOcppConfiguration();
993 switch (this.getOcppVersion()) {
994 case OCPPVersion
.VERSION_16
:
995 this.ocppIncomingRequestService
=
996 OCPP16IncomingRequestService
.getInstance
<OCPP16IncomingRequestService
>();
997 this.ocppRequestService
= OCPP16RequestService
.getInstance
<OCPP16RequestService
>(
998 OCPP16ResponseService
.getInstance
<OCPP16ResponseService
>()
1002 this.handleUnsupportedVersion(this.getOcppVersion());
1005 if (this.stationInfo
?.autoRegister
) {
1006 this.bootNotificationResponse
= {
1007 currentTime
: new Date().toISOString(),
1008 interval
: this.getHeartbeatInterval() / 1000,
1009 status: RegistrationStatus
.ACCEPTED
,
1014 private initializeOcppConfiguration(): void {
1016 !ChargingStationConfigurationUtils
.getConfigurationKey(
1018 StandardParametersKey
.HeartbeatInterval
1021 ChargingStationConfigurationUtils
.addConfigurationKey(
1023 StandardParametersKey
.HeartbeatInterval
,
1028 !ChargingStationConfigurationUtils
.getConfigurationKey(
1030 StandardParametersKey
.HeartBeatInterval
1033 ChargingStationConfigurationUtils
.addConfigurationKey(
1035 StandardParametersKey
.HeartBeatInterval
,
1041 this.getSupervisionUrlOcppConfiguration() &&
1042 !ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1044 ChargingStationConfigurationUtils
.addConfigurationKey(
1046 this.getSupervisionUrlOcppKey(),
1047 this.configuredSupervisionUrl
.href
,
1051 !this.getSupervisionUrlOcppConfiguration() &&
1052 ChargingStationConfigurationUtils
.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
1054 ChargingStationConfigurationUtils
.deleteConfigurationKey(
1056 this.getSupervisionUrlOcppKey(),
1061 this.stationInfo
.amperageLimitationOcppKey
&&
1062 !ChargingStationConfigurationUtils
.getConfigurationKey(
1064 this.stationInfo
.amperageLimitationOcppKey
1067 ChargingStationConfigurationUtils
.addConfigurationKey(
1069 this.stationInfo
.amperageLimitationOcppKey
,
1071 this.stationInfo
.maximumAmperage
*
1072 ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1077 !ChargingStationConfigurationUtils
.getConfigurationKey(
1079 StandardParametersKey
.SupportedFeatureProfiles
1082 ChargingStationConfigurationUtils
.addConfigurationKey(
1084 StandardParametersKey
.SupportedFeatureProfiles
,
1085 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
1088 ChargingStationConfigurationUtils
.addConfigurationKey(
1090 StandardParametersKey
.NumberOfConnectors
,
1091 this.getNumberOfConnectors().toString(),
1096 !ChargingStationConfigurationUtils
.getConfigurationKey(
1098 StandardParametersKey
.MeterValuesSampledData
1101 ChargingStationConfigurationUtils
.addConfigurationKey(
1103 StandardParametersKey
.MeterValuesSampledData
,
1104 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
1108 !ChargingStationConfigurationUtils
.getConfigurationKey(
1110 StandardParametersKey
.ConnectorPhaseRotation
1113 const connectorPhaseRotation
= [];
1114 for (const connectorId
of this.connectors
.keys()) {
1116 if (connectorId
=== 0 && this.getNumberOfPhases() === 0) {
1117 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1118 } else if (connectorId
> 0 && this.getNumberOfPhases() === 0) {
1119 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1121 } else if (connectorId
> 0 && this.getNumberOfPhases() === 1) {
1122 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1123 } else if (connectorId
> 0 && this.getNumberOfPhases() === 3) {
1124 connectorPhaseRotation
.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1127 ChargingStationConfigurationUtils
.addConfigurationKey(
1129 StandardParametersKey
.ConnectorPhaseRotation
,
1130 connectorPhaseRotation
.toString()
1134 !ChargingStationConfigurationUtils
.getConfigurationKey(
1136 StandardParametersKey
.AuthorizeRemoteTxRequests
1139 ChargingStationConfigurationUtils
.addConfigurationKey(
1141 StandardParametersKey
.AuthorizeRemoteTxRequests
,
1146 !ChargingStationConfigurationUtils
.getConfigurationKey(
1148 StandardParametersKey
.LocalAuthListEnabled
1150 ChargingStationConfigurationUtils
.getConfigurationKey(
1152 StandardParametersKey
.SupportedFeatureProfiles
1153 )?.value
.includes(SupportedFeatureProfiles
.LocalAuthListManagement
)
1155 ChargingStationConfigurationUtils
.addConfigurationKey(
1157 StandardParametersKey
.LocalAuthListEnabled
,
1162 !ChargingStationConfigurationUtils
.getConfigurationKey(
1164 StandardParametersKey
.ConnectionTimeOut
1167 ChargingStationConfigurationUtils
.addConfigurationKey(
1169 StandardParametersKey
.ConnectionTimeOut
,
1170 Constants
.DEFAULT_CONNECTION_TIMEOUT
.toString()
1173 this.saveOcppConfiguration();
1176 private initializeConnectors(
1177 stationInfo
: ChargingStationInfo
,
1178 configuredMaxConnectors
: number,
1179 templateMaxConnectors
: number
1181 if (!stationInfo
?.Connectors
&& this.connectors
.size
=== 0) {
1182 const logMsg
= `No already defined connectors and charging station information from template ${this.templateFile} with no connectors configuration defined`;
1183 logger
.error(`${this.logPrefix()} ${logMsg}`);
1184 throw new BaseError(logMsg
);
1186 if (!stationInfo
?.Connectors
[0]) {
1188 `${this.logPrefix()} Charging station information from template ${
1190 } with no connector Id 0 configuration`
1193 if (stationInfo
?.Connectors
) {
1194 const connectorsConfigHash
= crypto
1195 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1196 .update(JSON
.stringify(stationInfo
?.Connectors
) + configuredMaxConnectors
.toString())
1198 const connectorsConfigChanged
=
1199 this.connectors
?.size
!== 0 && this.connectorsConfigurationHash
!== connectorsConfigHash
;
1200 if (this.connectors
?.size
=== 0 || connectorsConfigChanged
) {
1201 connectorsConfigChanged
&& this.connectors
.clear();
1202 this.connectorsConfigurationHash
= connectorsConfigHash
;
1203 // Add connector Id 0
1204 let lastConnector
= '0';
1205 for (lastConnector
in stationInfo
?.Connectors
) {
1206 const lastConnectorId
= Utils
.convertToInt(lastConnector
);
1208 lastConnectorId
=== 0 &&
1209 this.getUseConnectorId0(stationInfo
) === true &&
1210 stationInfo
?.Connectors
[lastConnector
]
1212 this.connectors
.set(
1214 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[lastConnector
])
1216 this.getConnectorStatus(lastConnectorId
).availability
= AvailabilityType
.OPERATIVE
;
1217 if (Utils
.isUndefined(this.getConnectorStatus(lastConnectorId
)?.chargingProfiles
)) {
1218 this.getConnectorStatus(lastConnectorId
).chargingProfiles
= [];
1222 // Generate all connectors
1223 if ((stationInfo
?.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
1224 for (let index
= 1; index
<= configuredMaxConnectors
; index
++) {
1225 const randConnectorId
= stationInfo
?.randomConnectors
1226 ? Utils
.getRandomInteger(Utils
.convertToInt(lastConnector
), 1)
1228 this.connectors
.set(
1230 Utils
.cloneObject
<ConnectorStatus
>(stationInfo
?.Connectors
[randConnectorId
])
1232 this.getConnectorStatus(index
).availability
= AvailabilityType
.OPERATIVE
;
1233 if (Utils
.isUndefined(this.getConnectorStatus(index
)?.chargingProfiles
)) {
1234 this.getConnectorStatus(index
).chargingProfiles
= [];
1241 `${this.logPrefix()} Charging station information from template ${
1243 } with no connectors configuration defined, using already defined connectors`
1246 // Initialize transaction attributes on connectors
1247 for (const connectorId
of this.connectors
.keys()) {
1250 (this.getConnectorStatus(connectorId
).transactionStarted
=== undefined ||
1251 this.getConnectorStatus(connectorId
).transactionStarted
=== false)
1253 this.initializeConnectorStatus(connectorId
);
1258 private getConfigurationFromFile(): ChargingStationConfiguration
| null {
1259 let configuration
: ChargingStationConfiguration
= null;
1260 if (this.configurationFile
&& fs
.existsSync(this.configurationFile
)) {
1262 if (this.sharedLRUCache
.hasChargingStationConfiguration(this.configurationFileHash
)) {
1263 configuration
= this.sharedLRUCache
.getChargingStationConfiguration(
1264 this.configurationFileHash
1267 const measureId
= `${FileType.ChargingStationConfiguration} read`;
1268 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1269 configuration
= JSON
.parse(
1270 fs
.readFileSync(this.configurationFile
, 'utf8')
1271 ) as ChargingStationConfiguration
;
1272 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1273 this.configurationFileHash
= configuration
.configurationHash
;
1274 this.sharedLRUCache
.setChargingStationConfiguration(configuration
);
1277 FileUtils
.handleFileException(
1279 FileType
.ChargingStationConfiguration
,
1280 this.configurationFile
,
1281 error
as NodeJS
.ErrnoException
1285 return configuration
;
1288 private saveConfiguration(): void {
1289 if (this.configurationFile
) {
1291 if (!fs
.existsSync(path
.dirname(this.configurationFile
))) {
1292 fs
.mkdirSync(path
.dirname(this.configurationFile
), { recursive
: true });
1294 const configurationData
: ChargingStationConfiguration
=
1295 this.getConfigurationFromFile() ?? {};
1296 this.ocppConfiguration
?.configurationKey
&&
1297 (configurationData
.configurationKey
= this.ocppConfiguration
.configurationKey
);
1298 this.stationInfo
&& (configurationData
.stationInfo
= this.stationInfo
);
1299 delete configurationData
.configurationHash
;
1300 const configurationHash
= crypto
1301 .createHash(Constants
.DEFAULT_HASH_ALGORITHM
)
1302 .update(JSON
.stringify(configurationData
))
1304 if (this.configurationFileHash
!== configurationHash
) {
1305 configurationData
.configurationHash
= configurationHash
;
1306 const measureId
= `${FileType.ChargingStationConfiguration} write`;
1307 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
1308 const fileDescriptor
= fs
.openSync(this.configurationFile
, 'w');
1309 fs
.writeFileSync(fileDescriptor
, JSON
.stringify(configurationData
, null, 2), 'utf8');
1310 fs
.closeSync(fileDescriptor
);
1311 PerformanceStatistics
.endMeasure(measureId
, beginId
);
1312 this.sharedLRUCache
.deleteChargingStationConfiguration(this.configurationFileHash
);
1313 this.configurationFileHash
= configurationHash
;
1314 this.sharedLRUCache
.setChargingStationConfiguration(configurationData
);
1317 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1318 this.configurationFile
1323 FileUtils
.handleFileException(
1325 FileType
.ChargingStationConfiguration
,
1326 this.configurationFile
,
1327 error
as NodeJS
.ErrnoException
1332 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
1337 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration
| null {
1338 return this.getTemplateFromFile()?.Configuration
?? null;
1341 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration
| null {
1342 let configuration
: ChargingStationConfiguration
= null;
1343 if (this.getOcppPersistentConfiguration()) {
1344 const configurationFromFile
= this.getConfigurationFromFile();
1345 configuration
= configurationFromFile
?.configurationKey
&& configurationFromFile
;
1347 configuration
&& delete configuration
.stationInfo
;
1348 return configuration
;
1351 private getOcppConfiguration(): ChargingStationOcppConfiguration
| null {
1352 let ocppConfiguration
: ChargingStationOcppConfiguration
= this.getOcppConfigurationFromFile();
1353 if (!ocppConfiguration
) {
1354 ocppConfiguration
= this.getOcppConfigurationFromTemplate();
1356 return ocppConfiguration
;
1359 private async onOpen(): Promise
<void> {
1360 if (this.isWebSocketConnectionOpened()) {
1362 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1364 if (!this.isRegistered()) {
1365 // Send BootNotification
1366 let registrationRetryCount
= 0;
1368 this.bootNotificationResponse
= await this.ocppRequestService
.requestHandler
<
1369 BootNotificationRequest
,
1370 BootNotificationResponse
1371 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1372 skipBufferingOnError
: true,
1374 if (!this.isRegistered()) {
1375 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount
++;
1377 this.bootNotificationResponse
?.interval
1378 ? this.bootNotificationResponse
.interval
* 1000
1379 : Constants
.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1383 !this.isRegistered() &&
1384 (registrationRetryCount
<= this.getRegistrationMaxRetries() ||
1385 this.getRegistrationMaxRetries() === -1)
1388 if (this.isRegistered()) {
1389 if (this.isInAcceptedState()) {
1390 await this.startMessageSequence();
1394 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1397 this.wsConnectionRestarted
= false;
1398 this.autoReconnectRetryCount
= 0;
1399 this.started
= true;
1400 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1403 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
1408 private async onClose(code
: number, reason
: string): Promise
<void> {
1411 case WebSocketCloseEventStatusCode
.CLOSE_NORMAL
:
1412 case WebSocketCloseEventStatusCode
.CLOSE_NO_STATUS
:
1414 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1416 )}' and reason '${reason}'`
1418 this.autoReconnectRetryCount
= 0;
1423 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1425 )}' and reason '${reason}'`
1427 await this.reconnect();
1430 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1433 private async onMessage(data
: Data
): Promise
<void> {
1434 let messageType
: number;
1435 let messageId
: string;
1436 let commandName
: IncomingRequestCommand
;
1437 let commandPayload
: JsonType
;
1438 let errorType
: ErrorType
;
1439 let errorMessage
: string;
1440 let errorDetails
: JsonType
;
1441 let responseCallback
: (payload
: JsonType
, requestPayload
: JsonType
) => void;
1442 let errorCallback
: (error
: OCPPError
, requestStatistic
?: boolean) => void;
1443 let requestCommandName
: RequestCommand
| IncomingRequestCommand
;
1444 let requestPayload
: JsonType
;
1445 let cachedRequest
: CachedRequest
;
1448 const request
= JSON
.parse(data
.toString()) as IncomingRequest
| Response
| ErrorResponse
;
1449 if (Array.isArray(request
) === true) {
1450 [messageType
, messageId
] = request
;
1451 // Check the type of message
1452 switch (messageType
) {
1454 case MessageType
.CALL_MESSAGE
:
1455 [, , commandName
, commandPayload
] = request
as IncomingRequest
;
1456 if (this.getEnableStatistics() === true) {
1457 this.performanceStatistics
.addRequestStatistic(commandName
, messageType
);
1460 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1464 // Process the message
1465 await this.ocppIncomingRequestService
.incomingRequestHandler(
1473 case MessageType
.CALL_RESULT_MESSAGE
:
1474 [, , commandPayload
] = request
as Response
;
1475 if (this.requests
.has(messageId
) === false) {
1477 throw new OCPPError(
1478 ErrorType
.INTERNAL_ERROR
,
1479 `Response for unknown message id ${messageId}`,
1485 cachedRequest
= this.requests
.get(messageId
);
1486 if (Array.isArray(cachedRequest
) === true) {
1487 [responseCallback
, , requestCommandName
, requestPayload
] = cachedRequest
;
1489 throw new OCPPError(
1490 ErrorType
.PROTOCOL_ERROR
,
1491 `Cached request for message id ${messageId} response is not an array`,
1493 cachedRequest
as unknown
as JsonType
1497 `${this.logPrefix()} << Command '${
1498 requestCommandName ?? 'unknown'
1499 }' received response payload: ${JSON.stringify(request)}`
1501 responseCallback(commandPayload
, requestPayload
);
1504 case MessageType
.CALL_ERROR_MESSAGE
:
1505 [, , errorType
, errorMessage
, errorDetails
] = request
as ErrorResponse
;
1506 if (this.requests
.has(messageId
) === false) {
1508 throw new OCPPError(
1509 ErrorType
.INTERNAL_ERROR
,
1510 `Error response for unknown message id ${messageId}`,
1512 { errorType
, errorMessage
, errorDetails
}
1515 cachedRequest
= this.requests
.get(messageId
);
1516 if (Array.isArray(cachedRequest
) === true) {
1517 [, errorCallback
, requestCommandName
] = cachedRequest
;
1519 throw new OCPPError(
1520 ErrorType
.PROTOCOL_ERROR
,
1521 `Cached request for message id ${messageId} error response is not an array`,
1523 cachedRequest
as unknown
as JsonType
1527 `${this.logPrefix()} << Command '${
1528 requestCommandName ?? 'unknown'
1529 }' received error payload: ${JSON.stringify(request)}`
1531 errorCallback(new OCPPError(errorType
, errorMessage
, requestCommandName
, errorDetails
));
1535 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1536 errMsg
= `Wrong message type ${messageType}`;
1537 logger
.error(`${this.logPrefix()} ${errMsg}`);
1538 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, errMsg
);
1540 parentPort
.postMessage(MessageChannelUtils
.buildUpdatedMessage(this));
1542 throw new OCPPError(ErrorType
.PROTOCOL_ERROR
, 'Incoming message is not an array', null, {
1549 `${this.logPrefix()} Incoming OCPP command '${
1550 commandName ?? requestCommandName ?? null
1551 }' message '${data.toString()}'${
1552 messageType !== MessageType.CALL_MESSAGE
1553 ? ` matching cached request
'${JSON.stringify(this.requests.get(messageId))}'`
1555 } processing error:`,
1558 if (error
instanceof OCPPError
=== false) {
1560 `${this.logPrefix()} Error thrown at incoming OCPP command '${
1561 commandName ?? requestCommandName ?? null
1562 }' message '${data.toString()}' handling is not an OCPPError:`,
1566 if (messageType
=== MessageType
.CALL_MESSAGE
) {
1568 await this.ocppRequestService
.sendError(
1572 commandName
?? requestCommandName
?? null
1575 [MessageType
.CALL_RESULT_MESSAGE
, MessageType
.CALL_ERROR_MESSAGE
].includes(messageType
) ===
1578 // Remove the request from the cache
1579 this.requests
.delete(messageId
);
1584 private onPing(): void {
1585 logger
.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1588 private onPong(): void {
1589 logger
.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1592 private onError(error
: WSError
): void {
1593 this.closeWSConnection();
1594 logger
.error(this.logPrefix() + ' WebSocket error:', error
);
1597 private getEnergyActiveImportRegister(
1598 connectorStatus
: ConnectorStatus
,
1601 if (this.getMeteringPerTransaction() === true) {
1604 ? Math.round(connectorStatus
?.transactionEnergyActiveImportRegisterValue
)
1605 : connectorStatus
?.transactionEnergyActiveImportRegisterValue
) ?? 0
1610 ? Math.round(connectorStatus
?.energyActiveImportRegisterValue
)
1611 : connectorStatus
?.energyActiveImportRegisterValue
) ?? 0
1615 private getUseConnectorId0(stationInfo
?: ChargingStationInfo
): boolean {
1616 const localStationInfo
= stationInfo
?? this.stationInfo
;
1617 return !Utils
.isUndefined(localStationInfo
.useConnectorId0
)
1618 ? localStationInfo
.useConnectorId0
1622 private getNumberOfRunningTransactions(): number {
1624 for (const connectorId
of this.connectors
.keys()) {
1625 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1632 private async stopRunningTransactions(reason
= StopTransactionReason
.NONE
): Promise
<void> {
1633 for (const connectorId
of this.connectors
.keys()) {
1634 if (connectorId
> 0 && this.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
1635 await this.stopTransactionOnConnector(connectorId
, reason
);
1641 private getConnectionTimeout(): number | undefined {
1643 ChargingStationConfigurationUtils
.getConfigurationKey(
1645 StandardParametersKey
.ConnectionTimeOut
1650 ChargingStationConfigurationUtils
.getConfigurationKey(
1652 StandardParametersKey
.ConnectionTimeOut
1654 ) ?? Constants
.DEFAULT_CONNECTION_TIMEOUT
1657 return Constants
.DEFAULT_CONNECTION_TIMEOUT
;
1660 // -1 for unlimited, 0 for disabling
1661 private getAutoReconnectMaxRetries(): number | undefined {
1662 if (!Utils
.isUndefined(this.stationInfo
.autoReconnectMaxRetries
)) {
1663 return this.stationInfo
.autoReconnectMaxRetries
;
1665 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
1666 return Configuration
.getAutoReconnectMaxRetries();
1672 private getRegistrationMaxRetries(): number | undefined {
1673 if (!Utils
.isUndefined(this.stationInfo
.registrationMaxRetries
)) {
1674 return this.stationInfo
.registrationMaxRetries
;
1679 private getPowerDivider(): number {
1680 let powerDivider
= this.getNumberOfConnectors();
1681 if (this.stationInfo
?.powerSharedByConnectors
) {
1682 powerDivider
= this.getNumberOfRunningTransactions();
1684 return powerDivider
;
1687 private getMaximumPower(stationInfo
?: ChargingStationInfo
): number {
1688 const localStationInfo
= stationInfo
?? this.stationInfo
;
1689 return (localStationInfo
['maxPower'] as number) ?? localStationInfo
.maximumPower
;
1692 private getMaximumAmperage(stationInfo
: ChargingStationInfo
): number | undefined {
1693 const maximumPower
= this.getMaximumPower(stationInfo
);
1694 switch (this.getCurrentOutType(stationInfo
)) {
1695 case CurrentType
.AC
:
1696 return ACElectricUtils
.amperagePerPhaseFromPower(
1697 this.getNumberOfPhases(stationInfo
),
1698 maximumPower
/ this.getNumberOfConnectors(),
1699 this.getVoltageOut(stationInfo
)
1701 case CurrentType
.DC
:
1702 return DCElectricUtils
.amperage(maximumPower
, this.getVoltageOut(stationInfo
));
1706 private getAmperageLimitation(): number | undefined {
1708 this.stationInfo
.amperageLimitationOcppKey
&&
1709 ChargingStationConfigurationUtils
.getConfigurationKey(
1711 this.stationInfo
.amperageLimitationOcppKey
1716 ChargingStationConfigurationUtils
.getConfigurationKey(
1718 this.stationInfo
.amperageLimitationOcppKey
1720 ) / ChargingStationUtils
.getAmperageLimitationUnitDivider(this.stationInfo
)
1725 private getChargingProfilePowerLimit(connectorId
: number): number | undefined {
1726 let limit
: number, matchingChargingProfile
: ChargingProfile
;
1727 let chargingProfiles
: ChargingProfile
[] = [];
1728 // Get charging profiles for connector and sort by stack level
1729 chargingProfiles
= this.getConnectorStatus(connectorId
).chargingProfiles
.sort(
1730 (a
, b
) => b
.stackLevel
- a
.stackLevel
1732 // Get profiles on connector 0
1733 if (this.getConnectorStatus(0).chargingProfiles
) {
1734 chargingProfiles
.push(
1735 ...this.getConnectorStatus(0).chargingProfiles
.sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)
1738 if (!Utils
.isEmptyArray(chargingProfiles
)) {
1739 const result
= ChargingStationUtils
.getLimitFromChargingProfiles(
1743 if (!Utils
.isNullOrUndefined(result
)) {
1744 limit
= result
.limit
;
1745 matchingChargingProfile
= result
.matchingChargingProfile
;
1746 switch (this.getCurrentOutType()) {
1747 case CurrentType
.AC
:
1749 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1750 ChargingRateUnitType
.WATT
1752 : ACElectricUtils
.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit
);
1754 case CurrentType
.DC
:
1756 matchingChargingProfile
.chargingSchedule
.chargingRateUnit
===
1757 ChargingRateUnitType
.WATT
1759 : DCElectricUtils
.power(this.getVoltageOut(), limit
);
1761 const connectorMaximumPower
= this.getMaximumPower() / this.powerDivider
;
1762 if (limit
> connectorMaximumPower
) {
1764 `${this.logPrefix()} Charging profile id ${
1765 matchingChargingProfile.chargingProfileId
1766 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
1767 this.getConnectorStatus(connectorId
).chargingProfiles
1769 limit
= connectorMaximumPower
;
1776 private async startMessageSequence(): Promise
<void> {
1777 if (this.stationInfo
?.autoRegister
) {
1778 await this.ocppRequestService
.requestHandler
<
1779 BootNotificationRequest
,
1780 BootNotificationResponse
1781 >(this, RequestCommand
.BOOT_NOTIFICATION
, this.bootNotificationRequest
, {
1782 skipBufferingOnError
: true,
1785 // Start WebSocket ping
1786 this.startWebSocketPing();
1788 this.startHeartbeat();
1789 // Initialize connectors status
1790 for (const connectorId
of this.connectors
.keys()) {
1791 if (connectorId
=== 0) {
1794 this.started
=== true &&
1795 !this.getConnectorStatus(connectorId
)?.status &&
1796 this.getConnectorStatus(connectorId
)?.bootStatus
1798 // Send status in template at startup
1799 await this.ocppRequestService
.requestHandler
<
1800 StatusNotificationRequest
,
1801 StatusNotificationResponse
1802 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1804 status: this.getConnectorStatus(connectorId
).bootStatus
,
1805 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1807 this.getConnectorStatus(connectorId
).status =
1808 this.getConnectorStatus(connectorId
).bootStatus
;
1810 this.started
=== false &&
1811 this.getConnectorStatus(connectorId
)?.status &&
1812 this.getConnectorStatus(connectorId
)?.bootStatus
1814 // Send status in template after reset
1815 await this.ocppRequestService
.requestHandler
<
1816 StatusNotificationRequest
,
1817 StatusNotificationResponse
1818 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1820 status: this.getConnectorStatus(connectorId
).bootStatus
,
1821 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1823 this.getConnectorStatus(connectorId
).status =
1824 this.getConnectorStatus(connectorId
).bootStatus
;
1825 } else if (this.started
=== true && this.getConnectorStatus(connectorId
)?.status) {
1826 // Send previous status at template reload
1827 await this.ocppRequestService
.requestHandler
<
1828 StatusNotificationRequest
,
1829 StatusNotificationResponse
1830 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1832 status: this.getConnectorStatus(connectorId
).status,
1833 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1836 // Send default status
1837 await this.ocppRequestService
.requestHandler
<
1838 StatusNotificationRequest
,
1839 StatusNotificationResponse
1840 >(this, RequestCommand
.STATUS_NOTIFICATION
, {
1842 status: ChargePointStatus
.AVAILABLE
,
1843 errorCode
: ChargePointErrorCode
.NO_ERROR
,
1845 this.getConnectorStatus(connectorId
).status = ChargePointStatus
.AVAILABLE
;
1849 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable
=== true) {
1850 this.startAutomaticTransactionGenerator();
1852 this.wsConnectionRestarted
=== true && this.flushMessageBuffer();
1855 private async stopMessageSequence(
1856 reason
: StopTransactionReason
= StopTransactionReason
.NONE
1858 // Stop WebSocket ping
1859 this.stopWebSocketPing();
1861 this.stopHeartbeat();
1862 // Stop ongoing transactions
1863 if (this.automaticTransactionGenerator
?.started
=== true) {
1864 this.stopAutomaticTransactionGenerator();
1866 await this.stopRunningTransactions(reason
);
1870 private startWebSocketPing(): void {
1871 const webSocketPingInterval
: number = ChargingStationConfigurationUtils
.getConfigurationKey(
1873 StandardParametersKey
.WebSocketPingInterval
1875 ? Utils
.convertToInt(
1876 ChargingStationConfigurationUtils
.getConfigurationKey(
1878 StandardParametersKey
.WebSocketPingInterval
1882 if (webSocketPingInterval
> 0 && !this.webSocketPingSetInterval
) {
1883 this.webSocketPingSetInterval
= setInterval(() => {
1884 if (this.isWebSocketConnectionOpened()) {
1885 this.wsConnection
.ping((): void => {
1886 /* This is intentional */
1889 }, webSocketPingInterval
* 1000);
1892 ' WebSocket ping started every ' +
1893 Utils
.formatDurationSeconds(webSocketPingInterval
)
1895 } else if (this.webSocketPingSetInterval
) {
1898 ' WebSocket ping every ' +
1899 Utils
.formatDurationSeconds(webSocketPingInterval
) +
1904 `${this.logPrefix()} WebSocket ping interval set to ${
1905 webSocketPingInterval
1906 ? Utils.formatDurationSeconds(webSocketPingInterval)
1907 : webSocketPingInterval
1908 }, not starting the WebSocket ping`
1913 private stopWebSocketPing(): void {
1914 if (this.webSocketPingSetInterval
) {
1915 clearInterval(this.webSocketPingSetInterval
);
1919 private getConfiguredSupervisionUrl(): URL
{
1920 const supervisionUrls
= Utils
.cloneObject
<string | string[]>(
1921 this.stationInfo
.supervisionUrls
?? Configuration
.getSupervisionUrls()
1923 if (!Utils
.isEmptyArray(supervisionUrls
)) {
1925 switch (Configuration
.getSupervisionUrlDistribution()) {
1926 case SupervisionUrlDistribution
.ROUND_ROBIN
:
1927 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1929 case SupervisionUrlDistribution
.RANDOM
:
1931 urlIndex
= Math.floor(Utils
.secureRandom() * supervisionUrls
.length
);
1933 case SupervisionUrlDistribution
.SEQUENTIAL
:
1934 if (this.index
<= supervisionUrls
.length
) {
1935 urlIndex
= this.index
- 1;
1938 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1944 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1945 SupervisionUrlDistribution.ROUND_ROBIN
1948 urlIndex
= (this.index
- 1) % supervisionUrls
.length
;
1951 return new URL(supervisionUrls
[urlIndex
]);
1953 return new URL(supervisionUrls
as string);
1956 private getHeartbeatInterval(): number | undefined {
1957 const HeartbeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1959 StandardParametersKey
.HeartbeatInterval
1961 if (HeartbeatInterval
) {
1962 return Utils
.convertToInt(HeartbeatInterval
.value
) * 1000;
1964 const HeartBeatInterval
= ChargingStationConfigurationUtils
.getConfigurationKey(
1966 StandardParametersKey
.HeartBeatInterval
1968 if (HeartBeatInterval
) {
1969 return Utils
.convertToInt(HeartBeatInterval
.value
) * 1000;
1971 !this.stationInfo
?.autoRegister
&&
1973 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1974 Constants.DEFAULT_HEARTBEAT_INTERVAL
1977 return Constants
.DEFAULT_HEARTBEAT_INTERVAL
;
1980 private stopHeartbeat(): void {
1981 if (this.heartbeatSetInterval
) {
1982 clearInterval(this.heartbeatSetInterval
);
1986 private terminateWSConnection(): void {
1987 if (this.isWebSocketConnectionOpened()) {
1988 this.wsConnection
.terminate();
1989 this.wsConnection
= null;
1993 private stopMeterValues(connectorId
: number) {
1994 if (this.getConnectorStatus(connectorId
)?.transactionSetInterval
) {
1995 clearInterval(this.getConnectorStatus(connectorId
).transactionSetInterval
);
1999 private getReconnectExponentialDelay(): boolean | undefined {
2000 return !Utils
.isUndefined(this.stationInfo
.reconnectExponentialDelay
)
2001 ? this.stationInfo
.reconnectExponentialDelay
2005 private async reconnect(): Promise
<void> {
2006 // Stop WebSocket ping
2007 this.stopWebSocketPing();
2009 this.stopHeartbeat();
2010 // Stop the ATG if needed
2011 if (this.automaticTransactionGenerator
?.configuration
?.stopOnConnectionFailure
=== true) {
2012 this.stopAutomaticTransactionGenerator();
2015 this.autoReconnectRetryCount
< this.getAutoReconnectMaxRetries() ||
2016 this.getAutoReconnectMaxRetries() === -1
2018 this.autoReconnectRetryCount
++;
2019 const reconnectDelay
= this.getReconnectExponentialDelay()
2020 ? Utils
.exponentialDelay(this.autoReconnectRetryCount
)
2021 : this.getConnectionTimeout() * 1000;
2022 const reconnectDelayWithdraw
= 1000;
2023 const reconnectTimeout
=
2024 reconnectDelay
&& reconnectDelay
- reconnectDelayWithdraw
> 0
2025 ? reconnectDelay
- reconnectDelayWithdraw
2028 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
2031 )}ms, timeout ${reconnectTimeout}ms`
2033 await Utils
.sleep(reconnectDelay
);
2036 ' WebSocket: reconnecting try #' +
2037 this.autoReconnectRetryCount
.toString()
2039 this.openWSConnection(
2040 { ...(this.stationInfo
?.wsOptions
?? {}), handshakeTimeout
: reconnectTimeout
},
2041 { closeOpened
: true }
2043 this.wsConnectionRestarted
= true;
2044 } else if (this.getAutoReconnectMaxRetries() !== -1) {
2046 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
2047 this.autoReconnectRetryCount
2048 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
2053 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration
| null {
2054 return this.getTemplateFromFile()?.AutomaticTransactionGenerator
?? null;
2057 private initializeConnectorStatus(connectorId
: number): void {
2058 this.getConnectorStatus(connectorId
).idTagLocalAuthorized
= false;
2059 this.getConnectorStatus(connectorId
).idTagAuthorized
= false;
2060 this.getConnectorStatus(connectorId
).transactionRemoteStarted
= false;
2061 this.getConnectorStatus(connectorId
).transactionStarted
= false;
2062 this.getConnectorStatus(connectorId
).energyActiveImportRegisterValue
= 0;
2063 this.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;