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
'./ChargingStationUtils';
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 (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
194 this.stopConnector(connectorId
);
197 if (this.chargingStation
.inAcceptedState() === false) {
201 )} entered in transaction loop while the charging station is not in accepted state`,
203 this.stopConnector(connectorId
);
206 if (this.chargingStation
.isChargingStationAvailable() === false) {
210 )} entered in transaction loop while the charging station is unavailable`,
212 this.stopConnector(connectorId
);
215 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
219 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
221 this.stopConnector(connectorId
);
225 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
226 ConnectorStatusEnum
.Unavailable
231 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
233 this.stopConnector(connectorId
);
236 if (!this.chargingStation
?.ocppRequestService
) {
240 )} transaction loop waiting for charging station service to be initialized`,
243 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
244 } while (!this.chargingStation
?.ocppRequestService
);
246 const wait
= secondsToMilliseconds(
248 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
249 .maxDelayBetweenTwoTransactions
,
250 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
251 .minDelayBetweenTwoTransactions
,
254 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
256 const start
= secureRandom();
259 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
261 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
263 const startResponse
= await this.startTransaction(connectorId
);
264 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
265 // Wait until end of transaction
266 const waitTrxEnd
= secondsToMilliseconds(
268 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
269 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
,
273 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
274 .getConnectorStatus(connectorId)
275 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
279 await sleep(waitTrxEnd
);
282 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
283 .getConnectorStatus(connectorId)
284 ?.transactionId?.toString()}`,
286 await this.stopTransaction(connectorId
);
289 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
290 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
292 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
294 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
296 ?.skippedTransactions?.toString()} transaction(s)`,
299 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
301 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
305 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
306 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
307 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
311 `${this.logPrefix(connectorId)} connector status: %j`,
312 this.connectorsStatus
.get(connectorId
),
316 private setStartConnectorStatus(connectorId
: number): void {
317 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
318 const previousRunDuration
=
319 this.connectorsStatus
.get(connectorId
)?.startDate
&&
320 this.connectorsStatus
.get(connectorId
)?.lastRunDate
321 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
322 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
324 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
325 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
326 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
328 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
332 this.connectorsStatus
.get(connectorId
)!.start
= true;
335 private initializeConnectorsStatus(): void {
336 if (this.chargingStation
.hasEvses
) {
337 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
339 for (const connectorId
of evseStatus
.connectors
.keys()) {
340 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
345 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
346 if (connectorId
> 0) {
347 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
353 private getConnectorStatus(connectorId
: number): Status
{
354 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()
355 ? cloneObject(this.chargingStation
.getAutomaticTransactionGeneratorStatuses()!)[connectorId
]
357 delete connectorStatus
?.startDate
;
358 delete connectorStatus
?.lastRunDate
;
359 delete connectorStatus
?.stopDate
;
360 delete connectorStatus
?.stoppedDate
;
364 authorizeRequests
: 0,
365 acceptedAuthorizeRequests
: 0,
366 rejectedAuthorizeRequests
: 0,
367 startTransactionRequests
: 0,
368 acceptedStartTransactionRequests
: 0,
369 rejectedStartTransactionRequests
: 0,
370 stopTransactionRequests
: 0,
371 acceptedStopTransactionRequests
: 0,
372 rejectedStopTransactionRequests
: 0,
373 skippedConsecutiveTransactions
: 0,
374 skippedTransactions
: 0,
379 private async startTransaction(
381 ): Promise
<StartTransactionResponse
| undefined> {
382 const measureId
= 'StartTransaction with ATG';
383 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
384 let startResponse
: StartTransactionResponse
| undefined;
385 if (this.chargingStation
.hasIdTags()) {
386 const idTag
= IdTagsCache
.getInstance().getIdTag(
387 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
388 this.chargingStation
,
391 const startTransactionLogMsg
= `${this.logPrefix(
393 )} start transaction with an idTag '${idTag}'`;
394 if (this.getRequireAuthorize()) {
395 this.chargingStation
.getConnectorStatus(connectorId
)!.authorizeIdTag
= idTag
;
397 const authorizeResponse
: AuthorizeResponse
=
398 await this.chargingStation
.ocppRequestService
.requestHandler
<
401 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
404 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
405 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
406 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
407 logger
.info(startTransactionLogMsg
);
409 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
410 StartTransactionRequest
,
411 StartTransactionResponse
412 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
416 this.handleStartTransactionResponse(connectorId
, startResponse
);
417 PerformanceStatistics
.endMeasure(measureId
, beginId
);
418 return startResponse
;
420 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
421 PerformanceStatistics
.endMeasure(measureId
, beginId
);
422 return startResponse
;
424 logger
.info(startTransactionLogMsg
);
426 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
427 StartTransactionRequest
,
428 StartTransactionResponse
429 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
433 this.handleStartTransactionResponse(connectorId
, startResponse
);
434 PerformanceStatistics
.endMeasure(measureId
, beginId
);
435 return startResponse
;
437 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
438 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
439 StartTransactionRequest
,
440 StartTransactionResponse
441 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
442 this.handleStartTransactionResponse(connectorId
, startResponse
);
443 PerformanceStatistics
.endMeasure(measureId
, beginId
);
444 return startResponse
;
447 private async stopTransaction(
449 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
,
450 ): Promise
<StopTransactionResponse
| undefined> {
451 const measureId
= 'StopTransaction with ATG';
452 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
453 let stopResponse
: StopTransactionResponse
| undefined;
454 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
455 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
456 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
457 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
458 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
460 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
463 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
465 `${this.logPrefix(connectorId)} stopping a not started transaction${
466 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
470 PerformanceStatistics
.endMeasure(measureId
, beginId
);
474 private getRequireAuthorize(): boolean {
476 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
480 private logPrefix
= (connectorId
?: number): string => {
482 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
483 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId!.toString()}
` : ''
488 private handleStartTransactionResponse(
490 startResponse
: StartTransactionResponse
,
492 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
493 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
494 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
496 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
497 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;