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> {
323 if (!this.chargingStation
?.ocppRequestService
) {
327 )} transaction loop waiting for charging station service to be initialized`,
330 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
331 } while (!this.chargingStation
?.ocppRequestService
);
335 private async waitChargingStationAvailable(connectorId
: number): Promise
<void> {
336 if (!this.chargingStation
.isChargingStationAvailable()) {
340 )} transaction loop waiting for charging station to be available`,
343 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
344 } while (!this.chargingStation
.isChargingStationAvailable());
348 private async waitConnectorAvailable(connectorId
: number): Promise
<void> {
349 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
353 )} transaction loop waiting for connector ${connectorId} to be available`,
356 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
357 } while (!this.chargingStation
.isConnectorAvailable(connectorId
));
361 private initializeConnectorsStatus(): void {
362 if (this.chargingStation
.hasEvses
) {
363 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
365 for (const connectorId
of evseStatus
.connectors
.keys()) {
366 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
371 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
372 if (connectorId
> 0) {
373 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
379 private getConnectorStatus(connectorId
: number): Status
{
380 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()?.[
383 ? cloneObject
<Status
>(
384 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()![connectorId
],
387 this.resetConnectorStatus(connectorStatus
);
391 authorizeRequests
: 0,
392 acceptedAuthorizeRequests
: 0,
393 rejectedAuthorizeRequests
: 0,
394 startTransactionRequests
: 0,
395 acceptedStartTransactionRequests
: 0,
396 rejectedStartTransactionRequests
: 0,
397 stopTransactionRequests
: 0,
398 acceptedStopTransactionRequests
: 0,
399 rejectedStopTransactionRequests
: 0,
400 skippedConsecutiveTransactions
: 0,
401 skippedTransactions
: 0,
406 private resetConnectorStatus(connectorStatus
: Status
| undefined): void {
407 delete connectorStatus
?.startDate
;
408 delete connectorStatus
?.lastRunDate
;
409 delete connectorStatus
?.stopDate
;
410 delete connectorStatus
?.stoppedDate
;
413 (connectorStatus
?.start
=== true ||
414 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().enable
=== false)
416 connectorStatus
!.start
= false;
420 private async startTransaction(
422 ): Promise
<StartTransactionResponse
| undefined> {
423 const measureId
= 'StartTransaction with ATG';
424 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
425 let startResponse
: StartTransactionResponse
| undefined;
426 if (this.chargingStation
.hasIdTags()) {
427 const idTag
= IdTagsCache
.getInstance().getIdTag(
428 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
429 this.chargingStation
,
432 const startTransactionLogMsg
= `${this.logPrefix(
434 )} start transaction with an idTag '${idTag}'`;
435 if (this.getRequireAuthorize()) {
436 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
437 if (await OCPPServiceUtils
.isIdTagAuthorized(this.chargingStation
, connectorId
, idTag
)) {
438 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
439 logger
.info(startTransactionLogMsg
);
441 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
442 StartTransactionRequest
,
443 StartTransactionResponse
444 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
448 this.handleStartTransactionResponse(connectorId
, startResponse
);
449 PerformanceStatistics
.endMeasure(measureId
, beginId
);
450 return startResponse
;
452 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
453 PerformanceStatistics
.endMeasure(measureId
, beginId
);
454 return startResponse
;
456 logger
.info(startTransactionLogMsg
);
458 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
459 StartTransactionRequest
,
460 StartTransactionResponse
461 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
465 this.handleStartTransactionResponse(connectorId
, startResponse
);
466 PerformanceStatistics
.endMeasure(measureId
, beginId
);
467 return startResponse
;
469 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
470 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
471 StartTransactionRequest
,
472 StartTransactionResponse
473 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
474 this.handleStartTransactionResponse(connectorId
, startResponse
);
475 PerformanceStatistics
.endMeasure(measureId
, beginId
);
476 return startResponse
;
479 private async stopTransaction(
481 reason
= StopTransactionReason
.LOCAL
,
482 ): Promise
<StopTransactionResponse
| undefined> {
483 const measureId
= 'StopTransaction with ATG';
484 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
485 let stopResponse
: StopTransactionResponse
| undefined;
486 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
490 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
493 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
494 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
495 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
496 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
498 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
501 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
503 `${this.logPrefix(connectorId)} stopping a not started transaction${
504 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}
` : ''
508 PerformanceStatistics
.endMeasure(measureId
, beginId
);
512 private getRequireAuthorize(): boolean {
514 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
518 private logPrefix
= (connectorId
?: number): string => {
520 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
521 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}
` : ''
526 private handleStartTransactionResponse(
528 startResponse
: StartTransactionResponse
,
530 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
531 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
532 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
534 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
535 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;