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;
89 public async stop(): Promise
<void> {
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 await 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 async stopConnector(connectorId
: number): Promise
<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 await this.stopTransaction(connectorId
);
134 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
135 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
139 private startConnectors(): void {
141 this.connectorsStatus
?.size
> 0 &&
142 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
144 this.connectorsStatus
.clear();
145 this.initializeConnectorsStatus();
147 if (this.chargingStation
.hasEvses
) {
148 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
150 for (const connectorId
of evseStatus
.connectors
.keys()) {
151 this.startConnector(connectorId
);
156 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
157 if (connectorId
> 0) {
158 this.startConnector(connectorId
);
164 private async stopConnectors(): Promise
<void> {
165 if (this.chargingStation
.hasEvses
) {
166 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
168 for (const connectorId
of evseStatus
.connectors
.keys()) {
169 await this.stopConnector(connectorId
);
174 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
175 if (connectorId
> 0) {
176 await this.stopConnector(connectorId
);
182 private async internalStartConnector(connectorId
: number): Promise
<void> {
183 this.setStartConnectorStatus(connectorId
);
187 )} started on connector and will run for ${formatDurationMilliSeconds(
188 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
189 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
192 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
193 if (!this.canStartConnector(connectorId
)) {
194 await this.stopConnector(connectorId
);
197 if (!this.chargingStation
?.ocppRequestService
) {
201 )} transaction loop waiting for charging station service to be initialized`,
204 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
205 } while (!this.chargingStation
?.ocppRequestService
);
207 const wait
= secondsToMilliseconds(
209 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
210 .maxDelayBetweenTwoTransactions
,
211 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
212 .minDelayBetweenTwoTransactions
,
215 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
217 const start
= secureRandom();
220 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
222 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
224 const startResponse
= await this.startTransaction(connectorId
);
225 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
226 // Wait until end of transaction
227 const waitTrxEnd
= secondsToMilliseconds(
229 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
230 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
,
236 )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId)
237 ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`,
239 await sleep(waitTrxEnd
);
240 await this.stopTransaction(connectorId
);
243 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
244 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
246 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
248 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
249 ?.skippedTransactions} transaction(s)`,
252 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
254 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
258 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
259 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
260 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
264 `${this.logPrefix(connectorId)} connector status: %j`,
265 this.connectorsStatus
.get(connectorId
),
269 private setStartConnectorStatus(connectorId
: number): void {
270 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
271 const previousRunDuration
=
272 this.connectorsStatus
.get(connectorId
)?.startDate
&&
273 this.connectorsStatus
.get(connectorId
)?.lastRunDate
274 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
275 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
277 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
278 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
279 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
281 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
285 this.connectorsStatus
.get(connectorId
)!.start
= true;
288 private canStartConnector(connectorId
: number): boolean {
289 if (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
292 if (this.chargingStation
.inAcceptedState() === false) {
296 )} entered in transaction loop while the charging station is not in accepted state`,
300 if (this.chargingStation
.isChargingStationAvailable() === false) {
304 )} entered in transaction loop while the charging station is unavailable`,
308 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
312 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
317 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
318 ConnectorStatusEnum
.Unavailable
323 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
330 private initializeConnectorsStatus(): void {
331 if (this.chargingStation
.hasEvses
) {
332 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
334 for (const connectorId
of evseStatus
.connectors
.keys()) {
335 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
340 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
341 if (connectorId
> 0) {
342 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
348 private getConnectorStatus(connectorId
: number): Status
{
349 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()?.[
352 ? cloneObject
<Status
>(
353 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()![connectorId
],
356 delete connectorStatus
?.startDate
;
357 delete connectorStatus
?.lastRunDate
;
358 delete connectorStatus
?.stopDate
;
359 delete connectorStatus
?.stoppedDate
;
360 if (!this.started
&& connectorStatus
?.start
=== true) {
361 connectorStatus
.start
= false;
366 authorizeRequests
: 0,
367 acceptedAuthorizeRequests
: 0,
368 rejectedAuthorizeRequests
: 0,
369 startTransactionRequests
: 0,
370 acceptedStartTransactionRequests
: 0,
371 rejectedStartTransactionRequests
: 0,
372 stopTransactionRequests
: 0,
373 acceptedStopTransactionRequests
: 0,
374 rejectedStopTransactionRequests
: 0,
375 skippedConsecutiveTransactions
: 0,
376 skippedTransactions
: 0,
381 private async startTransaction(
383 ): Promise
<StartTransactionResponse
| undefined> {
384 const measureId
= 'StartTransaction with ATG';
385 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
386 let startResponse
: StartTransactionResponse
| undefined;
387 if (this.chargingStation
.hasIdTags()) {
388 const idTag
= IdTagsCache
.getInstance().getIdTag(
389 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
390 this.chargingStation
,
393 const startTransactionLogMsg
= `${this.logPrefix(
395 )} start transaction with an idTag '${idTag}'`;
396 if (this.getRequireAuthorize()) {
397 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
398 if (await OCPPServiceUtils
.isIdTagAuthorized(this.chargingStation
, connectorId
, idTag
)) {
399 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
400 logger
.info(startTransactionLogMsg
);
402 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
403 StartTransactionRequest
,
404 StartTransactionResponse
405 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
409 this.handleStartTransactionResponse(connectorId
, startResponse
);
410 PerformanceStatistics
.endMeasure(measureId
, beginId
);
411 return startResponse
;
413 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
414 PerformanceStatistics
.endMeasure(measureId
, beginId
);
415 return startResponse
;
417 logger
.info(startTransactionLogMsg
);
419 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
420 StartTransactionRequest
,
421 StartTransactionResponse
422 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
426 this.handleStartTransactionResponse(connectorId
, startResponse
);
427 PerformanceStatistics
.endMeasure(measureId
, beginId
);
428 return startResponse
;
430 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
431 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
432 StartTransactionRequest
,
433 StartTransactionResponse
434 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
435 this.handleStartTransactionResponse(connectorId
, startResponse
);
436 PerformanceStatistics
.endMeasure(measureId
, beginId
);
437 return startResponse
;
440 private async stopTransaction(
442 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
,
443 ): Promise
<StopTransactionResponse
| undefined> {
444 const measureId
= 'StopTransaction with ATG';
445 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
446 let stopResponse
: StopTransactionResponse
| undefined;
447 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
451 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
454 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
455 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
456 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
457 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
459 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
462 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
464 `${this.logPrefix(connectorId)} stopping a not started transaction${
465 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}
` : ''
469 PerformanceStatistics
.endMeasure(measureId
, beginId
);
473 private getRequireAuthorize(): boolean {
475 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
479 private logPrefix
= (connectorId
?: number): string => {
481 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
482 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}
` : ''
487 private handleStartTransactionResponse(
489 startResponse
: StartTransactionResponse
,
491 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
492 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
493 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
495 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
496 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;