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 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
230 .minDelayBetweenTwoTransactions
233 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
235 await Utils
.sleep(wait
);
236 const start
= Utils
.secureRandom();
239 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
241 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
243 const startResponse
= await this.startTransaction(connectorId
);
244 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
245 // Wait until end of transaction
247 Utils
.getRandomInteger(
248 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
249 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
252 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
253 .getConnectorStatus(connectorId)
254 ?.transactionId?.toString()} and will stop in ${Utils.formatDurationMilliSeconds(
258 await Utils
.sleep(waitTrxEnd
);
261 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
262 .getConnectorStatus(connectorId)
263 ?.transactionId?.toString()}`
265 await this.stopTransaction(connectorId
);
268 ++this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
;
269 ++this.connectorsStatus
.get(connectorId
).skippedTransactions
;
271 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
273 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
275 ?.skippedTransactions?.toString()} transaction(s)`
278 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
280 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
284 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
285 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
286 this.connectorsStatus.get(connectorId).startDate.getTime()
290 `${this.logPrefix(connectorId)} connector status: %j`,
291 this.connectorsStatus
.get(connectorId
)
295 private setStartConnectorStatus(connectorId
: number): void {
296 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
297 const previousRunDuration
=
298 this.connectorsStatus
.get(connectorId
)?.startDate
&&
299 this.connectorsStatus
.get(connectorId
)?.lastRunDate
300 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
301 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
303 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
304 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
305 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
306 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
*
311 this.connectorsStatus
.get(connectorId
).start
= true;
314 private initializeConnectorsStatus(): void {
315 if (this.chargingStation
.hasEvses
) {
316 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
318 for (const connectorId
of evseStatus
.connectors
.keys()) {
319 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
324 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
325 if (connectorId
> 0) {
326 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
332 private getConnectorStatus(connectorId
: number): Status
{
333 const connectorStatus
=
334 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()[connectorId
];
335 delete connectorStatus
?.startDate
;
336 delete connectorStatus
?.lastRunDate
;
337 delete connectorStatus
?.stopDate
;
338 delete connectorStatus
?.stoppedDate
;
342 authorizeRequests
: 0,
343 acceptedAuthorizeRequests
: 0,
344 rejectedAuthorizeRequests
: 0,
345 startTransactionRequests
: 0,
346 acceptedStartTransactionRequests
: 0,
347 rejectedStartTransactionRequests
: 0,
348 stopTransactionRequests
: 0,
349 acceptedStopTransactionRequests
: 0,
350 rejectedStopTransactionRequests
: 0,
351 skippedConsecutiveTransactions
: 0,
352 skippedTransactions
: 0,
357 private async startTransaction(
359 ): Promise
<StartTransactionResponse
| undefined> {
360 const measureId
= 'StartTransaction with ATG';
361 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
362 let startResponse
: StartTransactionResponse
;
363 if (this.chargingStation
.hasIdTags()) {
364 const idTag
= IdTagsCache
.getInstance().getIdTag(
365 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution
,
366 this.chargingStation
,
369 const startTransactionLogMsg
= `${this.logPrefix(
371 )} start transaction with an idTag '${idTag}'`;
372 if (this.getRequireAuthorize()) {
373 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
375 const authorizeResponse
: AuthorizeResponse
=
376 await this.chargingStation
.ocppRequestService
.requestHandler
<
379 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
382 ++this.connectorsStatus
.get(connectorId
).authorizeRequests
;
383 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
384 ++this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
;
385 logger
.info(startTransactionLogMsg
);
387 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
388 StartTransactionRequest
,
389 StartTransactionResponse
390 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
394 this.handleStartTransactionResponse(connectorId
, startResponse
);
395 PerformanceStatistics
.endMeasure(measureId
, beginId
);
396 return startResponse
;
398 ++this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
;
399 PerformanceStatistics
.endMeasure(measureId
, beginId
);
400 return startResponse
;
402 logger
.info(startTransactionLogMsg
);
404 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
405 StartTransactionRequest
,
406 StartTransactionResponse
407 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
411 this.handleStartTransactionResponse(connectorId
, startResponse
);
412 PerformanceStatistics
.endMeasure(measureId
, beginId
);
413 return startResponse
;
415 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
416 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
417 StartTransactionRequest
,
418 StartTransactionResponse
419 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
420 this.handleStartTransactionResponse(connectorId
, startResponse
);
421 PerformanceStatistics
.endMeasure(measureId
, beginId
);
422 return startResponse
;
425 private async stopTransaction(
427 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
428 ): Promise
<StopTransactionResponse
> {
429 const measureId
= 'StopTransaction with ATG';
430 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
431 let stopResponse
: StopTransactionResponse
;
432 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
433 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
434 ++this.connectorsStatus
.get(connectorId
).stopTransactionRequests
;
435 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
436 ++this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
;
438 ++this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
;
441 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
443 `${this.logPrefix(connectorId)} stopping a not started transaction${
444 !Utils.isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
448 PerformanceStatistics
.endMeasure(measureId
, beginId
);
452 private getRequireAuthorize(): boolean {
454 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
458 private logPrefix
= (connectorId
?: number): string => {
459 return Utils
.logPrefix(
460 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
461 !Utils.isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}
` : ''
466 private handleStartTransactionResponse(
468 startResponse
: StartTransactionResponse
470 ++this.connectorsStatus
.get(connectorId
).startTransactionRequests
;
471 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
472 ++this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
;
474 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
475 ++this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
;