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 { ChargingStationUtils
} 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
,
22 import { Constants
, Utils
, logger
} from
'../utils';
24 const moduleName
= 'AutomaticTransactionGenerator';
26 export class AutomaticTransactionGenerator
extends AsyncResource
{
27 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
29 AutomaticTransactionGenerator
32 public readonly connectorsStatus
: Map
<number, Status
>;
33 public started
: boolean;
34 private readonly chargingStation
: ChargingStation
;
36 private constructor(chargingStation
: ChargingStation
) {
39 this.chargingStation
= chargingStation
;
40 this.connectorsStatus
= new Map
<number, Status
>();
41 this.initializeConnectorsStatus();
44 public static getInstance(
45 chargingStation
: ChargingStation
46 ): AutomaticTransactionGenerator
| undefined {
47 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
48 AutomaticTransactionGenerator
.instances
.set(
49 chargingStation
.stationInfo
.hashId
,
50 new AutomaticTransactionGenerator(chargingStation
)
53 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
56 public start(): void {
58 ChargingStationUtils
.checkChargingStation(this.chargingStation
, this.logPrefix()) === false
62 if (this.started
=== true) {
63 logger
.warn(`${this.logPrefix()} is already started`);
66 this.startConnectors();
71 if (this.started
=== false) {
72 logger
.warn(`${this.logPrefix()} is already stopped`);
75 this.stopConnectors();
79 public startConnector(connectorId
: number): void {
81 ChargingStationUtils
.checkChargingStation(
83 this.logPrefix(connectorId
)
88 if (this.connectorsStatus
.has(connectorId
) === false) {
89 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
90 throw new BaseError(`Connector ${connectorId} does not exist`);
92 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
94 this.internalStartConnector
.bind(this) as (
95 this: AutomaticTransactionGenerator
,
100 ).catch(Constants
.EMPTY_FUNCTION
);
101 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
102 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
106 public stopConnector(connectorId
: number): void {
107 if (this.connectorsStatus
.has(connectorId
) === false) {
108 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
109 throw new BaseError(`Connector ${connectorId} does not exist`);
111 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
112 this.connectorsStatus
.get(connectorId
).start
= false;
113 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
114 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
118 private startConnectors(): void {
120 this.connectorsStatus
?.size
> 0 &&
121 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
123 this.connectorsStatus
.clear();
124 this.initializeConnectorsStatus();
126 if (this.chargingStation
.hasEvses
) {
127 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
129 for (const connectorId
of evseStatus
.connectors
.keys()) {
130 this.startConnector(connectorId
);
135 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
136 if (connectorId
> 0) {
137 this.startConnector(connectorId
);
143 private stopConnectors(): void {
144 if (this.chargingStation
.hasEvses
) {
145 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
147 for (const connectorId
of evseStatus
.connectors
.keys()) {
148 this.stopConnector(connectorId
);
153 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
154 if (connectorId
> 0) {
155 this.stopConnector(connectorId
);
161 private async internalStartConnector(connectorId
: number): Promise
<void> {
162 this.setStartConnectorStatus(connectorId
);
166 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
167 this.connectorsStatus.get(connectorId).stopDate.getTime() -
168 this.connectorsStatus.get(connectorId).startDate.getTime()
171 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
172 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
173 this.stopConnector(connectorId
);
176 if (this.chargingStation
.inAcceptedState() === false) {
180 )} entered in transaction loop while the charging station is not in accepted state`
182 this.stopConnector(connectorId
);
185 if (this.chargingStation
.isChargingStationAvailable() === false) {
189 )} entered in transaction loop while the charging station is unavailable`
191 this.stopConnector(connectorId
);
194 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
198 )} entered in transaction loop while the connector ${connectorId} is unavailable`
200 this.stopConnector(connectorId
);
204 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
205 ConnectorStatusEnum
.Unavailable
210 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
212 this.stopConnector(connectorId
);
215 if (!this.chargingStation
?.ocppRequestService
) {
219 )} transaction loop waiting for charging station service to be initialized`
222 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
223 } while (!this.chargingStation
?.ocppRequestService
);
226 Utils
.getRandomInteger(
227 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
228 .maxDelayBetweenTwoTransactions
??
229 Constants
.DEFAULT_ATG_MAX_DELAY_BETWEEN_TWO_TRANSACTIONS
,
230 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
231 .minDelayBetweenTwoTransactions
??
232 Constants
.DEFAULT_ATG_MIN_DELAY_BETWEEN_TWO_TRANSACTIONS
235 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
237 await Utils
.sleep(wait
);
238 const start
= Utils
.secureRandom();
241 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
243 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
245 const startResponse
= await this.startTransaction(connectorId
);
246 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
247 // Wait until end of transaction
249 Utils
.getRandomInteger(
250 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
??
251 Constants
.DEFAULT_ATG_MAX_DURATION
,
252 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
??
253 Constants
.DEFAULT_ATG_MIN_DURATION
256 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
257 .getConnectorStatus(connectorId)
258 ?.transactionId?.toString()} and will stop in ${Utils.formatDurationMilliSeconds(
262 await Utils
.sleep(waitTrxEnd
);
265 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
266 .getConnectorStatus(connectorId)
267 ?.transactionId?.toString()}`
269 await this.stopTransaction(connectorId
);
272 ++this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
;
273 ++this.connectorsStatus
.get(connectorId
).skippedTransactions
;
275 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
277 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
279 ?.skippedTransactions?.toString()} transaction(s)`
282 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
284 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
288 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
289 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
290 this.connectorsStatus.get(connectorId).startDate.getTime()
294 `${this.logPrefix(connectorId)} connector status: %j`,
295 this.connectorsStatus
.get(connectorId
)
299 private setStartConnectorStatus(connectorId
: number): void {
300 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
301 const previousRunDuration
=
302 this.connectorsStatus
.get(connectorId
)?.startDate
&&
303 this.connectorsStatus
.get(connectorId
)?.lastRunDate
304 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
305 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
307 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
308 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
309 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
310 (this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
??
311 Constants
.DEFAULT_ATG_STOP_AFTER_HOURS
) *
316 this.connectorsStatus
.get(connectorId
).start
= true;
319 private initializeConnectorsStatus(): void {
320 if (this.chargingStation
.hasEvses
) {
321 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
323 for (const connectorId
of evseStatus
.connectors
.keys()) {
324 this.connectorsStatus
.set(connectorId
, {
326 authorizeRequests
: 0,
327 acceptedAuthorizeRequests
: 0,
328 rejectedAuthorizeRequests
: 0,
329 startTransactionRequests
: 0,
330 acceptedStartTransactionRequests
: 0,
331 rejectedStartTransactionRequests
: 0,
332 stopTransactionRequests
: 0,
333 acceptedStopTransactionRequests
: 0,
334 rejectedStopTransactionRequests
: 0,
335 skippedConsecutiveTransactions
: 0,
336 skippedTransactions
: 0,
342 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
343 if (connectorId
> 0) {
344 this.connectorsStatus
.set(connectorId
, {
346 authorizeRequests
: 0,
347 acceptedAuthorizeRequests
: 0,
348 rejectedAuthorizeRequests
: 0,
349 startTransactionRequests
: 0,
350 acceptedStartTransactionRequests
: 0,
351 rejectedStartTransactionRequests
: 0,
352 stopTransactionRequests
: 0,
353 acceptedStopTransactionRequests
: 0,
354 rejectedStopTransactionRequests
: 0,
355 skippedConsecutiveTransactions
: 0,
356 skippedTransactions
: 0,
363 private async startTransaction(
365 ): Promise
<StartTransactionResponse
| undefined> {
366 const measureId
= 'StartTransaction with ATG';
367 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
368 let startResponse
: StartTransactionResponse
;
369 if (this.chargingStation
.hasIdTags()) {
370 const idTag
= IdTagsCache
.getInstance().getIdTag(
371 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution
,
372 this.chargingStation
,
375 const startTransactionLogMsg
= `${this.logPrefix(
377 )} start transaction with an idTag '${idTag}'`;
378 if (this.getRequireAuthorize()) {
379 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
381 const authorizeResponse
: AuthorizeResponse
=
382 await this.chargingStation
.ocppRequestService
.requestHandler
<
385 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
388 ++this.connectorsStatus
.get(connectorId
).authorizeRequests
;
389 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
390 ++this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
;
391 logger
.info(startTransactionLogMsg
);
393 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
394 StartTransactionRequest
,
395 StartTransactionResponse
396 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
400 this.handleStartTransactionResponse(connectorId
, startResponse
);
401 PerformanceStatistics
.endMeasure(measureId
, beginId
);
402 return startResponse
;
404 ++this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
;
405 PerformanceStatistics
.endMeasure(measureId
, beginId
);
406 return startResponse
;
408 logger
.info(startTransactionLogMsg
);
410 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
411 StartTransactionRequest
,
412 StartTransactionResponse
413 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
417 this.handleStartTransactionResponse(connectorId
, startResponse
);
418 PerformanceStatistics
.endMeasure(measureId
, beginId
);
419 return startResponse
;
421 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
422 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
423 StartTransactionRequest
,
424 StartTransactionResponse
425 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
426 this.handleStartTransactionResponse(connectorId
, startResponse
);
427 PerformanceStatistics
.endMeasure(measureId
, beginId
);
428 return startResponse
;
431 private async stopTransaction(
433 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
434 ): Promise
<StopTransactionResponse
> {
435 const measureId
= 'StopTransaction with ATG';
436 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
437 let stopResponse
: StopTransactionResponse
;
438 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
439 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
440 ++this.connectorsStatus
.get(connectorId
).stopTransactionRequests
;
441 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
442 ++this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
;
444 ++this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
;
447 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
449 `${this.logPrefix(connectorId)} stopping a not started transaction${
450 !Utils.isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
454 PerformanceStatistics
.endMeasure(measureId
, beginId
);
458 private getRequireAuthorize(): boolean {
460 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
464 private logPrefix
= (connectorId
?: number): string => {
465 return Utils
.logPrefix(
466 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
467 !Utils.isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}
` : ''
472 private handleStartTransactionResponse(
474 startResponse
: StartTransactionResponse
476 ++this.connectorsStatus
.get(connectorId
).startTransactionRequests
;
477 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
478 ++this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
;
480 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
481 ++this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
;