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';
10 import { PerformanceStatistics
} from
'../performance/PerformanceStatistics';
13 type AuthorizeRequest
,
14 type AuthorizeResponse
,
17 type StartTransactionRequest
,
18 type StartTransactionResponse
,
20 StopTransactionReason
,
21 type StopTransactionResponse
,
23 import { Constants
, Utils
, logger
} from
'../utils';
25 const moduleName
= 'AutomaticTransactionGenerator';
27 export class AutomaticTransactionGenerator
extends AsyncResource
{
28 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
30 AutomaticTransactionGenerator
33 public readonly connectorsStatus
: Map
<number, Status
>;
34 public started
: boolean;
35 private readonly chargingStation
: ChargingStation
;
37 private constructor(chargingStation
: ChargingStation
) {
40 this.chargingStation
= chargingStation
;
41 this.connectorsStatus
= new Map
<number, Status
>();
42 this.initializeConnectorsStatus();
45 public static getInstance(
46 chargingStation
: ChargingStation
47 ): AutomaticTransactionGenerator
| undefined {
48 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
49 AutomaticTransactionGenerator
.instances
.set(
50 chargingStation
.stationInfo
.hashId
,
51 new AutomaticTransactionGenerator(chargingStation
)
54 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
57 public start(): void {
59 ChargingStationUtils
.checkChargingStation(this.chargingStation
, this.logPrefix()) === false
63 if (this.started
=== true) {
64 logger
.warn(`${this.logPrefix()} is already started`);
67 this.startConnectors();
72 if (this.started
=== false) {
73 logger
.warn(`${this.logPrefix()} is already stopped`);
76 this.stopConnectors();
80 public startConnector(connectorId
: number): void {
82 ChargingStationUtils
.checkChargingStation(
84 this.logPrefix(connectorId
)
89 if (this.connectorsStatus
.has(connectorId
) === false) {
90 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
91 throw new BaseError(`Connector ${connectorId} does not exist`);
93 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
95 this.internalStartConnector
.bind(this) as (
96 this: AutomaticTransactionGenerator
,
101 ).catch(Constants
.EMPTY_FUNCTION
);
102 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
103 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
107 public stopConnector(connectorId
: number): void {
108 if (this.connectorsStatus
.has(connectorId
) === false) {
109 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
110 throw new BaseError(`Connector ${connectorId} does not exist`);
112 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
113 this.connectorsStatus
.get(connectorId
).start
= false;
114 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
115 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
119 private startConnectors(): void {
121 this.connectorsStatus
?.size
> 0 &&
122 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
124 this.connectorsStatus
.clear();
125 this.initializeConnectorsStatus();
127 if (this.chargingStation
.hasEvses
) {
128 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
130 for (const connectorId
of evseStatus
.connectors
.keys()) {
131 this.startConnector(connectorId
);
136 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
137 if (connectorId
> 0) {
138 this.startConnector(connectorId
);
144 private stopConnectors(): void {
145 if (this.chargingStation
.hasEvses
) {
146 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
148 for (const connectorId
of evseStatus
.connectors
.keys()) {
149 this.stopConnector(connectorId
);
154 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
155 if (connectorId
> 0) {
156 this.stopConnector(connectorId
);
162 private async internalStartConnector(connectorId
: number): Promise
<void> {
163 this.setStartConnectorStatus(connectorId
);
167 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
168 this.connectorsStatus.get(connectorId).stopDate.getTime() -
169 this.connectorsStatus.get(connectorId).startDate.getTime()
172 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
173 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
174 this.stopConnector(connectorId
);
177 if (this.chargingStation
.inAcceptedState() === false) {
181 )} entered in transaction loop while the charging station is not in accepted state`
183 this.stopConnector(connectorId
);
186 if (this.chargingStation
.isChargingStationAvailable() === false) {
190 )} entered in transaction loop while the charging station is unavailable`
192 this.stopConnector(connectorId
);
195 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
199 )} entered in transaction loop while the connector ${connectorId} is unavailable`
201 this.stopConnector(connectorId
);
205 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
206 ConnectorStatusEnum
.Unavailable
211 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
213 this.stopConnector(connectorId
);
216 if (!this.chargingStation
?.ocppRequestService
) {
220 )} transaction loop waiting for charging station service to be initialized`
223 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
224 } while (!this.chargingStation
?.ocppRequestService
);
227 Utils
.getRandomInteger(
228 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
229 .maxDelayBetweenTwoTransactions
,
230 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
231 .minDelayBetweenTwoTransactions
234 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
236 await Utils
.sleep(wait
);
237 const start
= Utils
.secureRandom();
240 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
242 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
244 const startResponse
= await this.startTransaction(connectorId
);
245 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
246 // Wait until end of transaction
248 Utils
.getRandomInteger(
249 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
250 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
253 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
254 .getConnectorStatus(connectorId)
255 ?.transactionId?.toString()} and will stop in ${Utils.formatDurationMilliSeconds(
259 await Utils
.sleep(waitTrxEnd
);
262 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
263 .getConnectorStatus(connectorId)
264 ?.transactionId?.toString()}`
266 await this.stopTransaction(connectorId
);
269 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
270 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
272 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
274 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
276 ?.skippedTransactions?.toString()} transaction(s)`
279 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
281 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
285 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
286 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
287 this.connectorsStatus.get(connectorId).startDate.getTime()
291 `${this.logPrefix(connectorId)} connector status: %j`,
292 this.connectorsStatus
.get(connectorId
)
296 private setStartConnectorStatus(connectorId
: number): void {
297 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
298 const previousRunDuration
=
299 this.connectorsStatus
.get(connectorId
)?.startDate
&&
300 this.connectorsStatus
.get(connectorId
)?.lastRunDate
301 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
302 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
304 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
305 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
306 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
307 (this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
??
308 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
313 this.connectorsStatus
.get(connectorId
).start
= true;
316 private initializeConnectorsStatus(): void {
317 if (this.chargingStation
.hasEvses
) {
318 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
320 for (const connectorId
of evseStatus
.connectors
.keys()) {
321 this.connectorsStatus
.set(connectorId
, {
323 authorizeRequests
: 0,
324 acceptedAuthorizeRequests
: 0,
325 rejectedAuthorizeRequests
: 0,
326 startTransactionRequests
: 0,
327 acceptedStartTransactionRequests
: 0,
328 rejectedStartTransactionRequests
: 0,
329 stopTransactionRequests
: 0,
330 acceptedStopTransactionRequests
: 0,
331 rejectedStopTransactionRequests
: 0,
332 skippedConsecutiveTransactions
: 0,
333 skippedTransactions
: 0,
339 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
340 if (connectorId
> 0) {
341 this.connectorsStatus
.set(connectorId
, {
343 authorizeRequests
: 0,
344 acceptedAuthorizeRequests
: 0,
345 rejectedAuthorizeRequests
: 0,
346 startTransactionRequests
: 0,
347 acceptedStartTransactionRequests
: 0,
348 rejectedStartTransactionRequests
: 0,
349 stopTransactionRequests
: 0,
350 acceptedStopTransactionRequests
: 0,
351 rejectedStopTransactionRequests
: 0,
352 skippedConsecutiveTransactions
: 0,
353 skippedTransactions
: 0,
360 private async startTransaction(
362 ): Promise
<StartTransactionResponse
| undefined> {
363 const measureId
= 'StartTransaction with ATG';
364 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
365 let startResponse
: StartTransactionResponse
;
366 if (this.chargingStation
.hasIdTags()) {
367 const idTag
= IdTagsCache
.getInstance().getIdTag(
368 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution
,
369 this.chargingStation
,
372 const startTransactionLogMsg
= `${this.logPrefix(
374 )} start transaction with an idTag '${idTag}'`;
375 if (this.getRequireAuthorize()) {
376 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
378 const authorizeResponse
: AuthorizeResponse
=
379 await this.chargingStation
.ocppRequestService
.requestHandler
<
382 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
385 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
386 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
387 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
388 logger
.info(startTransactionLogMsg
);
390 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
391 StartTransactionRequest
,
392 StartTransactionResponse
393 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
397 this.handleStartTransactionResponse(connectorId
, startResponse
);
398 PerformanceStatistics
.endMeasure(measureId
, beginId
);
399 return startResponse
;
401 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
402 PerformanceStatistics
.endMeasure(measureId
, beginId
);
403 return startResponse
;
405 logger
.info(startTransactionLogMsg
);
407 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
408 StartTransactionRequest
,
409 StartTransactionResponse
410 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
414 this.handleStartTransactionResponse(connectorId
, startResponse
);
415 PerformanceStatistics
.endMeasure(measureId
, beginId
);
416 return startResponse
;
418 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
419 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
420 StartTransactionRequest
,
421 StartTransactionResponse
422 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
423 this.handleStartTransactionResponse(connectorId
, startResponse
);
424 PerformanceStatistics
.endMeasure(measureId
, beginId
);
425 return startResponse
;
428 private async stopTransaction(
430 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
431 ): Promise
<StopTransactionResponse
> {
432 const measureId
= 'StopTransaction with ATG';
433 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
434 let stopResponse
: StopTransactionResponse
;
435 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
436 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
437 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
438 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
439 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
441 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
444 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
446 `${this.logPrefix(connectorId)} stopping a not started transaction${
447 !Utils.isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
451 PerformanceStatistics
.endMeasure(measureId
, beginId
);
455 private getRequireAuthorize(): boolean {
457 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
461 private logPrefix
= (connectorId
?: number): string => {
462 return Utils
.logPrefix(
463 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
464 !Utils.isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}
` : ''
469 private handleStartTransactionResponse(
471 startResponse
: StartTransactionResponse
473 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
474 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
475 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
477 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
478 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;