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';
16 type StartTransactionRequest
,
17 type StartTransactionResponse
,
19 StopTransactionReason
,
20 type StopTransactionResponse
,
25 formatDurationMilliSeconds
,
34 const moduleName
= 'AutomaticTransactionGenerator';
36 export class AutomaticTransactionGenerator
extends AsyncResource
{
37 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
39 AutomaticTransactionGenerator
42 public readonly connectorsStatus
: Map
<number, Status
>;
43 public started
: boolean;
44 private starting
: boolean;
45 private stopping
: boolean;
46 private readonly chargingStation
: ChargingStation
;
48 private constructor(chargingStation
: ChargingStation
) {
51 this.starting
= false;
52 this.stopping
= false;
53 this.chargingStation
= chargingStation
;
54 this.connectorsStatus
= new Map
<number, Status
>();
55 this.initializeConnectorsStatus();
58 public static getInstance(
59 chargingStation
: ChargingStation
,
60 ): AutomaticTransactionGenerator
| undefined {
61 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
62 AutomaticTransactionGenerator
.instances
.set(
63 chargingStation
.stationInfo
.hashId
,
64 new AutomaticTransactionGenerator(chargingStation
),
67 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
70 public start(): void {
71 if (checkChargingStation(this.chargingStation
, this.logPrefix()) === false) {
74 if (this.started
=== true) {
75 logger
.warn(`${this.logPrefix()} is already started`);
78 if (this.starting
=== true) {
79 logger
.warn(`${this.logPrefix()} is already starting`);
83 this.startConnectors();
85 this.starting
= false;
89 if (this.started
=== false) {
90 logger
.warn(`${this.logPrefix()} is already stopped`);
93 if (this.stopping
=== true) {
94 logger
.warn(`${this.logPrefix()} is already stopping`);
98 this.stopConnectors();
100 this.stopping
= false;
103 public startConnector(connectorId
: number): void {
104 if (checkChargingStation(this.chargingStation
, this.logPrefix(connectorId
)) === false) {
107 if (this.connectorsStatus
.has(connectorId
) === false) {
108 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
109 throw new BaseError(`Connector ${connectorId} does not exist`);
111 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
112 this.runInAsyncScope(
113 this.internalStartConnector
.bind(this) as (
114 this: AutomaticTransactionGenerator
,
119 ).catch(Constants
.EMPTY_FUNCTION
);
120 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
121 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
125 public stopConnector(connectorId
: number): void {
126 if (this.connectorsStatus
.has(connectorId
) === false) {
127 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
128 throw new BaseError(`Connector ${connectorId} does not exist`);
130 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
131 this.connectorsStatus
.get(connectorId
)!.start
= false;
132 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
133 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
137 private startConnectors(): void {
139 this.connectorsStatus
?.size
> 0 &&
140 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
142 this.connectorsStatus
.clear();
143 this.initializeConnectorsStatus();
145 if (this.chargingStation
.hasEvses
) {
146 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
148 for (const connectorId
of evseStatus
.connectors
.keys()) {
149 this.startConnector(connectorId
);
154 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
155 if (connectorId
> 0) {
156 this.startConnector(connectorId
);
162 private stopConnectors(): void {
163 if (this.chargingStation
.hasEvses
) {
164 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
166 for (const connectorId
of evseStatus
.connectors
.keys()) {
167 this.stopConnector(connectorId
);
172 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
173 if (connectorId
> 0) {
174 this.stopConnector(connectorId
);
180 private async internalStartConnector(connectorId
: number): Promise
<void> {
181 this.setStartConnectorStatus(connectorId
);
185 )} started on connector and will run for ${formatDurationMilliSeconds(
186 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
187 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
190 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
191 await this.waitChargingStationServiceInitialization(connectorId
);
192 await this.waitChargingStationAvailable(connectorId
);
193 await this.waitConnectorAvailable(connectorId
);
194 if (!this.canStartConnector(connectorId
)) {
195 this.stopConnector(connectorId
);
198 const wait
= secondsToMilliseconds(
200 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
201 .maxDelayBetweenTwoTransactions
,
202 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
203 .minDelayBetweenTwoTransactions
,
206 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
208 const start
= secureRandom();
211 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
213 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
215 const startResponse
= await this.startTransaction(connectorId
);
216 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
217 // Wait until end of transaction
218 const waitTrxEnd
= secondsToMilliseconds(
220 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
221 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
,
227 )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId)
228 ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`,
230 await sleep(waitTrxEnd
);
231 await this.stopTransaction(connectorId
);
234 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
235 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
237 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
239 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
240 ?.skippedTransactions} transaction(s)`,
243 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
245 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
249 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
250 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
251 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
255 `${this.logPrefix(connectorId)} connector status: %j`,
256 this.connectorsStatus
.get(connectorId
),
260 private setStartConnectorStatus(connectorId
: number): void {
261 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
262 const previousRunDuration
=
263 this.connectorsStatus
.get(connectorId
)?.startDate
&&
264 this.connectorsStatus
.get(connectorId
)?.lastRunDate
265 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
266 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
268 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
269 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
270 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
272 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
276 this.connectorsStatus
.get(connectorId
)!.start
= true;
279 private canStartConnector(connectorId
: number): boolean {
280 if (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
283 if (this.chargingStation
.inAcceptedState() === false) {
287 )} entered in transaction loop while the charging station is not in accepted state`,
291 if (this.chargingStation
.isChargingStationAvailable() === false) {
295 )} entered in transaction loop while the charging station is unavailable`,
299 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
303 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
310 private async waitChargingStationServiceInitialization(connectorId
: number): Promise
<void> {
312 while (!this.chargingStation
?.ocppRequestService
) {
317 )} transaction loop waiting for charging station service to be initialized`,
321 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
325 private async waitChargingStationAvailable(connectorId
: number): Promise
<void> {
327 while (!this.chargingStation
.isChargingStationAvailable()) {
332 )} transaction loop waiting for charging station to be available`,
336 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
340 private async waitConnectorAvailable(connectorId
: number): Promise
<void> {
342 while (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
347 )} transaction loop waiting for connector ${connectorId} to be available`,
351 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
355 private initializeConnectorsStatus(): void {
356 if (this.chargingStation
.hasEvses
) {
357 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
359 for (const connectorId
of evseStatus
.connectors
.keys()) {
360 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
365 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
366 if (connectorId
> 0) {
367 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
373 private getConnectorStatus(connectorId
: number): Status
{
374 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()?.[
377 ? cloneObject
<Status
>(
378 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()![connectorId
],
381 this.resetConnectorStatus(connectorStatus
);
385 authorizeRequests
: 0,
386 acceptedAuthorizeRequests
: 0,
387 rejectedAuthorizeRequests
: 0,
388 startTransactionRequests
: 0,
389 acceptedStartTransactionRequests
: 0,
390 rejectedStartTransactionRequests
: 0,
391 stopTransactionRequests
: 0,
392 acceptedStopTransactionRequests
: 0,
393 rejectedStopTransactionRequests
: 0,
394 skippedConsecutiveTransactions
: 0,
395 skippedTransactions
: 0,
400 private resetConnectorStatus(connectorStatus
: Status
| undefined): void {
401 if (connectorStatus
=== undefined) {
404 delete connectorStatus
?.startDate
;
405 delete connectorStatus
?.lastRunDate
;
406 delete connectorStatus
?.stopDate
;
407 delete connectorStatus
?.stoppedDate
;
410 (connectorStatus
.start
=== true ||
411 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().enable
=== false)
413 connectorStatus
.start
= false;
417 private async startTransaction(
419 ): Promise
<StartTransactionResponse
| undefined> {
420 const measureId
= 'StartTransaction with ATG';
421 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
422 let startResponse
: StartTransactionResponse
| undefined;
423 if (this.chargingStation
.hasIdTags()) {
424 const idTag
= IdTagsCache
.getInstance().getIdTag(
425 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
426 this.chargingStation
,
429 const startTransactionLogMsg
= `${this.logPrefix(
431 )} start transaction with an idTag '${idTag}'`;
432 if (this.getRequireAuthorize()) {
433 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
434 if (await OCPPServiceUtils
.isIdTagAuthorized(this.chargingStation
, connectorId
, idTag
)) {
435 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
436 logger
.info(startTransactionLogMsg
);
438 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
439 StartTransactionRequest
,
440 StartTransactionResponse
441 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
445 this.handleStartTransactionResponse(connectorId
, startResponse
);
446 PerformanceStatistics
.endMeasure(measureId
, beginId
);
447 return startResponse
;
449 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
450 PerformanceStatistics
.endMeasure(measureId
, beginId
);
451 return startResponse
;
453 logger
.info(startTransactionLogMsg
);
455 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
456 StartTransactionRequest
,
457 StartTransactionResponse
458 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
462 this.handleStartTransactionResponse(connectorId
, startResponse
);
463 PerformanceStatistics
.endMeasure(measureId
, beginId
);
464 return startResponse
;
466 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
467 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
468 StartTransactionRequest
,
469 StartTransactionResponse
470 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
471 this.handleStartTransactionResponse(connectorId
, startResponse
);
472 PerformanceStatistics
.endMeasure(measureId
, beginId
);
473 return startResponse
;
476 private async stopTransaction(
478 reason
= StopTransactionReason
.LOCAL
,
479 ): Promise
<StopTransactionResponse
| undefined> {
480 const measureId
= 'StopTransaction with ATG';
481 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
482 let stopResponse
: StopTransactionResponse
| undefined;
483 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
487 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
490 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
491 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
492 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
493 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
495 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
498 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
500 `${this.logPrefix(connectorId)} stopping a not started transaction${
501 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}
` : ''
505 PerformanceStatistics
.endMeasure(measureId
, beginId
);
509 private getRequireAuthorize(): boolean {
511 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
515 private logPrefix
= (connectorId
?: number): string => {
517 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
518 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}
` : ''
523 private handleStartTransactionResponse(
525 startResponse
: StartTransactionResponse
,
527 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
528 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
529 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
531 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
532 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;