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 { BaseError
} from
'../exception';
11 import { PerformanceStatistics
} from
'../performance';
14 type AuthorizeRequest
,
15 type AuthorizeResponse
,
18 type StartTransactionRequest
,
19 type StartTransactionResponse
,
21 StopTransactionReason
,
22 type StopTransactionResponse
,
27 formatDurationMilliSeconds
,
36 const moduleName
= 'AutomaticTransactionGenerator';
38 export class AutomaticTransactionGenerator
extends AsyncResource
{
39 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
41 AutomaticTransactionGenerator
44 public readonly connectorsStatus
: Map
<number, Status
>;
45 public started
: boolean;
46 private starting
: boolean;
47 private stopping
: boolean;
48 private readonly chargingStation
: ChargingStation
;
50 private constructor(chargingStation
: ChargingStation
) {
53 this.starting
= false;
54 this.stopping
= false;
55 this.chargingStation
= chargingStation
;
56 this.connectorsStatus
= new Map
<number, Status
>();
57 this.initializeConnectorsStatus();
60 public static getInstance(
61 chargingStation
: ChargingStation
,
62 ): AutomaticTransactionGenerator
| undefined {
63 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
64 AutomaticTransactionGenerator
.instances
.set(
65 chargingStation
.stationInfo
.hashId
,
66 new AutomaticTransactionGenerator(chargingStation
),
69 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
72 public start(): void {
73 if (checkChargingStation(this.chargingStation
, this.logPrefix()) === false) {
76 if (this.started
=== true) {
77 logger
.warn(`${this.logPrefix()} is already started`);
80 if (this.starting
=== true) {
81 logger
.warn(`${this.logPrefix()} is already starting`);
85 this.startConnectors();
87 this.starting
= false;
91 if (this.started
=== false) {
92 logger
.warn(`${this.logPrefix()} is already stopped`);
95 if (this.stopping
=== true) {
96 logger
.warn(`${this.logPrefix()} is already stopping`);
100 this.stopConnectors();
101 this.started
= false;
102 this.stopping
= false;
105 public startConnector(connectorId
: number): void {
106 if (checkChargingStation(this.chargingStation
, this.logPrefix(connectorId
)) === false) {
109 if (this.connectorsStatus
.has(connectorId
) === false) {
110 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
111 throw new BaseError(`Connector ${connectorId} does not exist`);
113 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
114 this.runInAsyncScope(
115 this.internalStartConnector
.bind(this) as (
116 this: AutomaticTransactionGenerator
,
121 ).catch(Constants
.EMPTY_FUNCTION
);
122 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
123 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
127 public stopConnector(connectorId
: number): void {
128 if (this.connectorsStatus
.has(connectorId
) === false) {
129 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
130 throw new BaseError(`Connector ${connectorId} does not exist`);
132 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
133 this.connectorsStatus
.get(connectorId
)!.start
= false;
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 stopConnectors(): void {
165 if (this.chargingStation
.hasEvses
) {
166 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
168 for (const connectorId
of evseStatus
.connectors
.keys()) {
169 this.stopConnector(connectorId
);
174 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
175 if (connectorId
> 0) {
176 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 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
,
234 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
235 .getConnectorStatus(connectorId)
236 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
240 await sleep(waitTrxEnd
);
243 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
244 .getConnectorStatus(connectorId)
245 ?.transactionId?.toString()}`,
247 await this.stopTransaction(connectorId
);
250 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
251 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
253 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
255 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
257 ?.skippedTransactions?.toString()} transaction(s)`,
260 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
262 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
266 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
267 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
268 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
272 `${this.logPrefix(connectorId)} connector status: %j`,
273 this.connectorsStatus
.get(connectorId
),
277 private setStartConnectorStatus(connectorId
: number): void {
278 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
279 const previousRunDuration
=
280 this.connectorsStatus
.get(connectorId
)?.startDate
&&
281 this.connectorsStatus
.get(connectorId
)?.lastRunDate
282 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
283 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
285 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
286 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
287 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
289 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
293 this.connectorsStatus
.get(connectorId
)!.start
= true;
296 private canStartConnector(connectorId
: number): boolean {
297 if (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
300 if (this.chargingStation
.inAcceptedState() === false) {
304 )} entered in transaction loop while the charging station is not in accepted state`,
308 if (this.chargingStation
.isChargingStationAvailable() === false) {
312 )} entered in transaction loop while the charging station is unavailable`,
316 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
320 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
325 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
326 ConnectorStatusEnum
.Unavailable
331 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
338 private initializeConnectorsStatus(): void {
339 if (this.chargingStation
.hasEvses
) {
340 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
342 for (const connectorId
of evseStatus
.connectors
.keys()) {
343 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
348 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
349 if (connectorId
> 0) {
350 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
356 private getConnectorStatus(connectorId
: number): Status
{
357 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()
358 ? cloneObject
<Status
[]>(this.chargingStation
.getAutomaticTransactionGeneratorStatuses()!)[
362 delete connectorStatus
?.startDate
;
363 delete connectorStatus
?.lastRunDate
;
364 delete connectorStatus
?.stopDate
;
365 delete connectorStatus
?.stoppedDate
;
369 authorizeRequests
: 0,
370 acceptedAuthorizeRequests
: 0,
371 rejectedAuthorizeRequests
: 0,
372 startTransactionRequests
: 0,
373 acceptedStartTransactionRequests
: 0,
374 rejectedStartTransactionRequests
: 0,
375 stopTransactionRequests
: 0,
376 acceptedStopTransactionRequests
: 0,
377 rejectedStopTransactionRequests
: 0,
378 skippedConsecutiveTransactions
: 0,
379 skippedTransactions
: 0,
384 private async startTransaction(
386 ): Promise
<StartTransactionResponse
| undefined> {
387 const measureId
= 'StartTransaction with ATG';
388 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
389 let startResponse
: StartTransactionResponse
| undefined;
390 if (this.chargingStation
.hasIdTags()) {
391 const idTag
= IdTagsCache
.getInstance().getIdTag(
392 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
393 this.chargingStation
,
396 const startTransactionLogMsg
= `${this.logPrefix(
398 )} start transaction with an idTag '${idTag}'`;
399 if (this.getRequireAuthorize()) {
401 const authorizeResponse
: AuthorizeResponse
=
402 await this.chargingStation
.ocppRequestService
.requestHandler
<
405 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
408 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
409 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
411 isNullOrUndefined(this.chargingStation
.getConnectorStatus(connectorId
)!.authorizeIdTag
)
414 `${this.chargingStation.logPrefix()} IdTag ${idTag} is not set as authorized remotely, applying deferred initialization`,
416 this.chargingStation
.getConnectorStatus(connectorId
)!.authorizeIdTag
= idTag
;
418 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
419 logger
.info(startTransactionLogMsg
);
421 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
422 StartTransactionRequest
,
423 StartTransactionResponse
424 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
428 this.handleStartTransactionResponse(connectorId
, startResponse
);
429 PerformanceStatistics
.endMeasure(measureId
, beginId
);
430 return startResponse
;
432 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
433 PerformanceStatistics
.endMeasure(measureId
, beginId
);
434 return startResponse
;
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 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
450 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
451 StartTransactionRequest
,
452 StartTransactionResponse
453 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
454 this.handleStartTransactionResponse(connectorId
, startResponse
);
455 PerformanceStatistics
.endMeasure(measureId
, beginId
);
456 return startResponse
;
459 private async stopTransaction(
461 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
,
462 ): Promise
<StopTransactionResponse
| undefined> {
463 const measureId
= 'StopTransaction with ATG';
464 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
465 let stopResponse
: StopTransactionResponse
| undefined;
466 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
467 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
468 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
469 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
470 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
472 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
475 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
477 `${this.logPrefix(connectorId)} stopping a not started transaction${
478 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
482 PerformanceStatistics
.endMeasure(measureId
, beginId
);
486 private getRequireAuthorize(): boolean {
488 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
492 private logPrefix
= (connectorId
?: number): string => {
494 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
495 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId!.toString()}
` : ''
500 private handleStartTransactionResponse(
502 startResponse
: StartTransactionResponse
,
504 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
505 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
506 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
508 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
509 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;