1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
5 import { hoursToMilliseconds
, secondsToMilliseconds
} from
'date-fns';
7 import type { ChargingStation
} from
'./ChargingStation';
8 import { checkChargingStation
} from
'./Helpers';
9 import { IdTagsCache
} from
'./IdTagsCache';
10 import { OCPPServiceUtils
} from
'./ocpp';
11 import { BaseError
} from
'../exception';
12 import { PerformanceStatistics
} from
'../performance';
17 type StartTransactionRequest
,
18 type StartTransactionResponse
,
20 StopTransactionReason
,
21 type StopTransactionResponse
,
26 formatDurationMilliSeconds
,
35 const moduleName
= 'AutomaticTransactionGenerator';
37 export class AutomaticTransactionGenerator
extends AsyncResource
{
38 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
40 AutomaticTransactionGenerator
43 public readonly connectorsStatus
: Map
<number, Status
>;
44 public started
: boolean;
45 private starting
: boolean;
46 private stopping
: boolean;
47 private readonly chargingStation
: ChargingStation
;
49 private constructor(chargingStation
: ChargingStation
) {
52 this.starting
= false;
53 this.stopping
= false;
54 this.chargingStation
= chargingStation
;
55 this.connectorsStatus
= new Map
<number, Status
>();
56 this.initializeConnectorsStatus();
59 public static getInstance(
60 chargingStation
: ChargingStation
,
61 ): AutomaticTransactionGenerator
| undefined {
62 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
63 AutomaticTransactionGenerator
.instances
.set(
64 chargingStation
.stationInfo
.hashId
,
65 new AutomaticTransactionGenerator(chargingStation
),
68 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
71 public start(): void {
72 if (checkChargingStation(this.chargingStation
, this.logPrefix()) === false) {
75 if (this.started
=== true) {
76 logger
.warn(`${this.logPrefix()} is already started`);
79 if (this.starting
=== true) {
80 logger
.warn(`${this.logPrefix()} is already starting`);
84 this.startConnectors();
86 this.starting
= false;
90 if (this.started
=== false) {
91 logger
.warn(`${this.logPrefix()} is already stopped`);
94 if (this.stopping
=== true) {
95 logger
.warn(`${this.logPrefix()} is already stopping`);
99 this.stopConnectors();
100 this.started
= false;
101 this.stopping
= false;
104 public startConnector(connectorId
: number): void {
105 if (checkChargingStation(this.chargingStation
, this.logPrefix(connectorId
)) === false) {
108 if (this.connectorsStatus
.has(connectorId
) === false) {
109 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
110 throw new BaseError(`Connector ${connectorId} does not exist`);
112 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
113 this.runInAsyncScope(
114 this.internalStartConnector
.bind(this) as (
115 this: AutomaticTransactionGenerator
,
120 ).catch(Constants
.EMPTY_FUNCTION
);
121 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
122 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
126 public stopConnector(connectorId
: number): void {
127 if (this.connectorsStatus
.has(connectorId
) === false) {
128 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
129 throw new BaseError(`Connector ${connectorId} does not exist`);
131 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
132 this.connectorsStatus
.get(connectorId
)!.start
= false;
133 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
134 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
138 private startConnectors(): void {
140 this.connectorsStatus
?.size
> 0 &&
141 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
143 this.connectorsStatus
.clear();
144 this.initializeConnectorsStatus();
146 if (this.chargingStation
.hasEvses
) {
147 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
149 for (const connectorId
of evseStatus
.connectors
.keys()) {
150 this.startConnector(connectorId
);
155 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
156 if (connectorId
> 0) {
157 this.startConnector(connectorId
);
163 private stopConnectors(): void {
164 if (this.chargingStation
.hasEvses
) {
165 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
167 for (const connectorId
of evseStatus
.connectors
.keys()) {
168 this.stopConnector(connectorId
);
173 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
174 if (connectorId
> 0) {
175 this.stopConnector(connectorId
);
181 private async internalStartConnector(connectorId
: number): Promise
<void> {
182 this.setStartConnectorStatus(connectorId
);
186 )} started on connector and will run for ${formatDurationMilliSeconds(
187 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
188 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
191 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
192 await this.waitChargingStationServiceInitialization(connectorId
);
193 await this.waitChargingStationAvailable(connectorId
);
194 await this.waitConnectorAvailable(connectorId
);
195 if (!this.canStartConnector(connectorId
)) {
196 this.stopConnector(connectorId
);
199 const wait
= secondsToMilliseconds(
201 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
202 .maxDelayBetweenTwoTransactions
,
203 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
204 .minDelayBetweenTwoTransactions
,
207 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
209 const start
= secureRandom();
212 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
214 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
216 const startResponse
= await this.startTransaction(connectorId
);
217 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
218 // Wait until end of transaction
219 const waitTrxEnd
= secondsToMilliseconds(
221 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
222 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
,
228 )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId)
229 ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`,
231 await sleep(waitTrxEnd
);
232 await this.stopTransaction(connectorId
);
235 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
236 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
238 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
240 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
241 ?.skippedTransactions} transaction(s)`,
244 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
246 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
250 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
251 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
252 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
256 `${this.logPrefix(connectorId)} connector status: %j`,
257 this.connectorsStatus
.get(connectorId
),
261 private setStartConnectorStatus(connectorId
: number): void {
262 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
263 const previousRunDuration
=
264 this.connectorsStatus
.get(connectorId
)?.startDate
&&
265 this.connectorsStatus
.get(connectorId
)?.lastRunDate
266 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
267 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
269 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
270 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
271 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
273 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
277 this.connectorsStatus
.get(connectorId
)!.start
= true;
280 private canStartConnector(connectorId
: number): boolean {
281 if (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
284 if (this.chargingStation
.inAcceptedState() === false) {
288 )} entered in transaction loop while the charging station is not in accepted state`,
292 if (this.chargingStation
.isChargingStationAvailable() === false) {
296 )} entered in transaction loop while the charging station is unavailable`,
300 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
304 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
309 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
310 ConnectorStatusEnum
.Unavailable
315 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
322 private async waitChargingStationServiceInitialization(connectorId
: number): Promise
<void> {
324 while (!this.chargingStation
?.ocppRequestService
) {
329 )} transaction loop waiting for charging station service to be initialized`,
333 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
337 private async waitChargingStationAvailable(connectorId
: number): Promise
<void> {
339 while (!this.chargingStation
.isChargingStationAvailable()) {
344 )} transaction loop waiting for charging station to be available`,
348 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
352 private async waitConnectorAvailable(connectorId
: number): Promise
<void> {
354 while (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
359 )} transaction loop waiting for connector ${connectorId} to be available`,
363 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
367 private initializeConnectorsStatus(): void {
368 if (this.chargingStation
.hasEvses
) {
369 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
371 for (const connectorId
of evseStatus
.connectors
.keys()) {
372 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
377 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
378 if (connectorId
> 0) {
379 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
385 private getConnectorStatus(connectorId
: number): Status
{
386 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()?.[
389 ? cloneObject
<Status
>(
390 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()![connectorId
],
393 this.resetConnectorStatus(connectorStatus
);
397 authorizeRequests
: 0,
398 acceptedAuthorizeRequests
: 0,
399 rejectedAuthorizeRequests
: 0,
400 startTransactionRequests
: 0,
401 acceptedStartTransactionRequests
: 0,
402 rejectedStartTransactionRequests
: 0,
403 stopTransactionRequests
: 0,
404 acceptedStopTransactionRequests
: 0,
405 rejectedStopTransactionRequests
: 0,
406 skippedConsecutiveTransactions
: 0,
407 skippedTransactions
: 0,
412 private resetConnectorStatus(connectorStatus
: Status
| undefined): void {
413 delete connectorStatus
?.startDate
;
414 delete connectorStatus
?.lastRunDate
;
415 delete connectorStatus
?.stopDate
;
416 delete connectorStatus
?.stoppedDate
;
419 (connectorStatus
?.start
=== true ||
420 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().enable
=== false)
422 connectorStatus
!.start
= false;
426 private async startTransaction(
428 ): Promise
<StartTransactionResponse
| undefined> {
429 const measureId
= 'StartTransaction with ATG';
430 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
431 let startResponse
: StartTransactionResponse
| undefined;
432 if (this.chargingStation
.hasIdTags()) {
433 const idTag
= IdTagsCache
.getInstance().getIdTag(
434 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
435 this.chargingStation
,
438 const startTransactionLogMsg
= `${this.logPrefix(
440 )} start transaction with an idTag '${idTag}'`;
441 if (this.getRequireAuthorize()) {
442 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
443 if (await OCPPServiceUtils
.isIdTagAuthorized(this.chargingStation
, connectorId
, idTag
)) {
444 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
445 logger
.info(startTransactionLogMsg
);
447 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
448 StartTransactionRequest
,
449 StartTransactionResponse
450 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
454 this.handleStartTransactionResponse(connectorId
, startResponse
);
455 PerformanceStatistics
.endMeasure(measureId
, beginId
);
456 return startResponse
;
458 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
459 PerformanceStatistics
.endMeasure(measureId
, beginId
);
460 return startResponse
;
462 logger
.info(startTransactionLogMsg
);
464 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
465 StartTransactionRequest
,
466 StartTransactionResponse
467 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
471 this.handleStartTransactionResponse(connectorId
, startResponse
);
472 PerformanceStatistics
.endMeasure(measureId
, beginId
);
473 return startResponse
;
475 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
476 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
477 StartTransactionRequest
,
478 StartTransactionResponse
479 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
480 this.handleStartTransactionResponse(connectorId
, startResponse
);
481 PerformanceStatistics
.endMeasure(measureId
, beginId
);
482 return startResponse
;
485 private async stopTransaction(
487 reason
= StopTransactionReason
.LOCAL
,
488 ): Promise
<StopTransactionResponse
| undefined> {
489 const measureId
= 'StopTransaction with ATG';
490 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
491 let stopResponse
: StopTransactionResponse
| undefined;
492 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
496 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
499 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
500 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
501 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
502 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
504 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
507 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
509 `${this.logPrefix(connectorId)} stopping a not started transaction${
510 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}
` : ''
514 PerformanceStatistics
.endMeasure(measureId
, beginId
);
518 private getRequireAuthorize(): boolean {
520 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
524 private logPrefix
= (connectorId
?: number): string => {
526 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
527 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}
` : ''
532 private handleStartTransactionResponse(
534 startResponse
: StartTransactionResponse
,
536 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
537 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
538 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
540 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
541 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;