1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
5 import type { ChargingStation
} from
'./ChargingStation';
6 import { checkChargingStation
} from
'./ChargingStationUtils';
7 import { IdTagsCache
} from
'./IdTagsCache';
8 import { BaseError
} from
'../exception';
9 import { PerformanceStatistics
} from
'../performance';
12 type AuthorizeRequest
,
13 type AuthorizeResponse
,
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 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
192 this.stopConnector(connectorId
);
195 if (this.chargingStation
.inAcceptedState() === false) {
199 )} entered in transaction loop while the charging station is not in accepted state`
201 this.stopConnector(connectorId
);
204 if (this.chargingStation
.isChargingStationAvailable() === false) {
208 )} entered in transaction loop while the charging station is unavailable`
210 this.stopConnector(connectorId
);
213 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
217 )} entered in transaction loop while the connector ${connectorId} is unavailable`
219 this.stopConnector(connectorId
);
223 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
224 ConnectorStatusEnum
.Unavailable
229 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
231 this.stopConnector(connectorId
);
234 if (!this.chargingStation
?.ocppRequestService
) {
238 )} transaction loop waiting for charging station service to be initialized`
241 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
242 } while (!this.chargingStation
?.ocppRequestService
);
246 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
247 .maxDelayBetweenTwoTransactions
,
248 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
249 .minDelayBetweenTwoTransactions
251 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
253 const start
= secureRandom();
256 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
258 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
260 const startResponse
= await this.startTransaction(connectorId
);
261 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
262 // Wait until end of transaction
265 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
266 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
269 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
270 .getConnectorStatus(connectorId)
271 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
275 await sleep(waitTrxEnd
);
278 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
279 .getConnectorStatus(connectorId)
280 ?.transactionId?.toString()}`
282 await this.stopTransaction(connectorId
);
285 ++this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
;
286 ++this.connectorsStatus
.get(connectorId
).skippedTransactions
;
288 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
290 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
292 ?.skippedTransactions?.toString()} transaction(s)`
295 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
297 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
301 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
302 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
303 this.connectorsStatus.get(connectorId).startDate.getTime()
307 `${this.logPrefix(connectorId)} connector status: %j`,
308 this.connectorsStatus
.get(connectorId
)
312 private setStartConnectorStatus(connectorId
: number): void {
313 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
314 const previousRunDuration
=
315 this.connectorsStatus
.get(connectorId
)?.startDate
&&
316 this.connectorsStatus
.get(connectorId
)?.lastRunDate
317 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
318 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
320 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
321 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
322 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
323 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
*
328 this.connectorsStatus
.get(connectorId
).start
= true;
331 private initializeConnectorsStatus(): void {
332 if (this.chargingStation
.hasEvses
) {
333 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
335 for (const connectorId
of evseStatus
.connectors
.keys()) {
336 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
341 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
342 if (connectorId
> 0) {
343 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
349 private getConnectorStatus(connectorId
: number): Status
{
350 const connectorStatus
= cloneObject(
351 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()
353 delete connectorStatus
?.startDate
;
354 delete connectorStatus
?.lastRunDate
;
355 delete connectorStatus
?.stopDate
;
356 delete connectorStatus
?.stoppedDate
;
360 authorizeRequests
: 0,
361 acceptedAuthorizeRequests
: 0,
362 rejectedAuthorizeRequests
: 0,
363 startTransactionRequests
: 0,
364 acceptedStartTransactionRequests
: 0,
365 rejectedStartTransactionRequests
: 0,
366 stopTransactionRequests
: 0,
367 acceptedStopTransactionRequests
: 0,
368 rejectedStopTransactionRequests
: 0,
369 skippedConsecutiveTransactions
: 0,
370 skippedTransactions
: 0,
375 private async startTransaction(
377 ): Promise
<StartTransactionResponse
| undefined> {
378 const measureId
= 'StartTransaction with ATG';
379 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
380 let startResponse
: StartTransactionResponse
;
381 if (this.chargingStation
.hasIdTags()) {
382 const idTag
= IdTagsCache
.getInstance().getIdTag(
383 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution
,
384 this.chargingStation
,
387 const startTransactionLogMsg
= `${this.logPrefix(
389 )} start transaction with an idTag '${idTag}'`;
390 if (this.getRequireAuthorize()) {
391 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
393 const authorizeResponse
: AuthorizeResponse
=
394 await this.chargingStation
.ocppRequestService
.requestHandler
<
397 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
400 ++this.connectorsStatus
.get(connectorId
).authorizeRequests
;
401 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
402 ++this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
;
403 logger
.info(startTransactionLogMsg
);
405 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
406 StartTransactionRequest
,
407 StartTransactionResponse
408 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
412 this.handleStartTransactionResponse(connectorId
, startResponse
);
413 PerformanceStatistics
.endMeasure(measureId
, beginId
);
414 return startResponse
;
416 ++this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
;
417 PerformanceStatistics
.endMeasure(measureId
, beginId
);
418 return startResponse
;
420 logger
.info(startTransactionLogMsg
);
422 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
423 StartTransactionRequest
,
424 StartTransactionResponse
425 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
429 this.handleStartTransactionResponse(connectorId
, startResponse
);
430 PerformanceStatistics
.endMeasure(measureId
, beginId
);
431 return startResponse
;
433 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
434 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
435 StartTransactionRequest
,
436 StartTransactionResponse
437 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
438 this.handleStartTransactionResponse(connectorId
, startResponse
);
439 PerformanceStatistics
.endMeasure(measureId
, beginId
);
440 return startResponse
;
443 private async stopTransaction(
445 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
446 ): Promise
<StopTransactionResponse
> {
447 const measureId
= 'StopTransaction with ATG';
448 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
449 let stopResponse
: StopTransactionResponse
;
450 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
451 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
452 ++this.connectorsStatus
.get(connectorId
).stopTransactionRequests
;
453 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
454 ++this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
;
456 ++this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
;
459 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
461 `${this.logPrefix(connectorId)} stopping a not started transaction${
462 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
466 PerformanceStatistics
.endMeasure(measureId
, beginId
);
470 private getRequireAuthorize(): boolean {
472 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
476 private logPrefix
= (connectorId
?: number): string => {
478 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
479 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}
` : ''
484 private handleStartTransactionResponse(
486 startResponse
: StartTransactionResponse
488 ++this.connectorsStatus
.get(connectorId
).startTransactionRequests
;
489 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
490 ++this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
;
492 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
493 ++this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
;