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
,
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 {
72 ChargingStationUtils
.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 {
107 ChargingStationUtils
.checkChargingStation(
108 this.chargingStation
,
109 this.logPrefix(connectorId
)
114 if (this.connectorsStatus
.has(connectorId
) === false) {
115 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
116 throw new BaseError(`Connector ${connectorId} does not exist`);
118 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
119 this.runInAsyncScope(
120 this.internalStartConnector
.bind(this) as (
121 this: AutomaticTransactionGenerator
,
126 ).catch(Constants
.EMPTY_FUNCTION
);
127 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
128 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
132 public stopConnector(connectorId
: number): void {
133 if (this.connectorsStatus
.has(connectorId
) === false) {
134 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
135 throw new BaseError(`Connector ${connectorId} does not exist`);
137 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
138 this.connectorsStatus
.get(connectorId
).start
= false;
139 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
140 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
144 private startConnectors(): void {
146 this.connectorsStatus
?.size
> 0 &&
147 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
149 this.connectorsStatus
.clear();
150 this.initializeConnectorsStatus();
152 if (this.chargingStation
.hasEvses
) {
153 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
155 for (const connectorId
of evseStatus
.connectors
.keys()) {
156 this.startConnector(connectorId
);
161 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
162 if (connectorId
> 0) {
163 this.startConnector(connectorId
);
169 private stopConnectors(): void {
170 if (this.chargingStation
.hasEvses
) {
171 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
173 for (const connectorId
of evseStatus
.connectors
.keys()) {
174 this.stopConnector(connectorId
);
179 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
180 if (connectorId
> 0) {
181 this.stopConnector(connectorId
);
187 private async internalStartConnector(connectorId
: number): Promise
<void> {
188 this.setStartConnectorStatus(connectorId
);
192 )} started on connector and will run for ${formatDurationMilliSeconds(
193 this.connectorsStatus.get(connectorId).stopDate.getTime() -
194 this.connectorsStatus.get(connectorId).startDate.getTime()
197 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
198 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
199 this.stopConnector(connectorId
);
202 if (this.chargingStation
.inAcceptedState() === false) {
206 )} entered in transaction loop while the charging station is not in accepted state`
208 this.stopConnector(connectorId
);
211 if (this.chargingStation
.isChargingStationAvailable() === false) {
215 )} entered in transaction loop while the charging station is unavailable`
217 this.stopConnector(connectorId
);
220 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
224 )} entered in transaction loop while the connector ${connectorId} is unavailable`
226 this.stopConnector(connectorId
);
230 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
231 ConnectorStatusEnum
.Unavailable
236 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
238 this.stopConnector(connectorId
);
241 if (!this.chargingStation
?.ocppRequestService
) {
245 )} transaction loop waiting for charging station service to be initialized`
248 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
249 } while (!this.chargingStation
?.ocppRequestService
);
253 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
254 .maxDelayBetweenTwoTransactions
,
255 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
256 .minDelayBetweenTwoTransactions
258 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
260 const start
= secureRandom();
263 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
265 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
267 const startResponse
= await this.startTransaction(connectorId
);
268 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
269 // Wait until end of transaction
272 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
273 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
276 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
277 .getConnectorStatus(connectorId)
278 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
282 await sleep(waitTrxEnd
);
285 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
286 .getConnectorStatus(connectorId)
287 ?.transactionId?.toString()}`
289 await this.stopTransaction(connectorId
);
292 ++this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
;
293 ++this.connectorsStatus
.get(connectorId
).skippedTransactions
;
295 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
297 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
299 ?.skippedTransactions?.toString()} transaction(s)`
302 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
304 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
308 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
309 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
310 this.connectorsStatus.get(connectorId).startDate.getTime()
314 `${this.logPrefix(connectorId)} connector status: %j`,
315 this.connectorsStatus
.get(connectorId
)
319 private setStartConnectorStatus(connectorId
: number): void {
320 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
321 const previousRunDuration
=
322 this.connectorsStatus
.get(connectorId
)?.startDate
&&
323 this.connectorsStatus
.get(connectorId
)?.lastRunDate
324 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
325 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
327 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
328 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
329 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
330 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
*
335 this.connectorsStatus
.get(connectorId
).start
= true;
338 private initializeConnectorsStatus(): void {
339 if (this.chargingStation
.hasEvses
) {
340 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
342 for (const connectorId
of evseStatus
.connectors
.keys()) {
343 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
348 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
349 if (connectorId
> 0) {
350 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
356 private getConnectorStatus(connectorId
: number): Status
{
357 const connectorStatus
= cloneObject(
358 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()
360 delete connectorStatus
?.startDate
;
361 delete connectorStatus
?.lastRunDate
;
362 delete connectorStatus
?.stopDate
;
363 delete connectorStatus
?.stoppedDate
;
367 authorizeRequests
: 0,
368 acceptedAuthorizeRequests
: 0,
369 rejectedAuthorizeRequests
: 0,
370 startTransactionRequests
: 0,
371 acceptedStartTransactionRequests
: 0,
372 rejectedStartTransactionRequests
: 0,
373 stopTransactionRequests
: 0,
374 acceptedStopTransactionRequests
: 0,
375 rejectedStopTransactionRequests
: 0,
376 skippedConsecutiveTransactions
: 0,
377 skippedTransactions
: 0,
382 private async startTransaction(
384 ): Promise
<StartTransactionResponse
| undefined> {
385 const measureId
= 'StartTransaction with ATG';
386 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
387 let startResponse
: StartTransactionResponse
;
388 if (this.chargingStation
.hasIdTags()) {
389 const idTag
= IdTagsCache
.getInstance().getIdTag(
390 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution
,
391 this.chargingStation
,
394 const startTransactionLogMsg
= `${this.logPrefix(
396 )} start transaction with an idTag '${idTag}'`;
397 if (this.getRequireAuthorize()) {
398 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
400 const authorizeResponse
: AuthorizeResponse
=
401 await this.chargingStation
.ocppRequestService
.requestHandler
<
404 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
407 ++this.connectorsStatus
.get(connectorId
).authorizeRequests
;
408 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
409 ++this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
;
410 logger
.info(startTransactionLogMsg
);
412 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
413 StartTransactionRequest
,
414 StartTransactionResponse
415 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
419 this.handleStartTransactionResponse(connectorId
, startResponse
);
420 PerformanceStatistics
.endMeasure(measureId
, beginId
);
421 return startResponse
;
423 ++this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
;
424 PerformanceStatistics
.endMeasure(measureId
, beginId
);
425 return startResponse
;
427 logger
.info(startTransactionLogMsg
);
429 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
430 StartTransactionRequest
,
431 StartTransactionResponse
432 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
436 this.handleStartTransactionResponse(connectorId
, startResponse
);
437 PerformanceStatistics
.endMeasure(measureId
, beginId
);
438 return startResponse
;
440 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
441 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
442 StartTransactionRequest
,
443 StartTransactionResponse
444 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
445 this.handleStartTransactionResponse(connectorId
, startResponse
);
446 PerformanceStatistics
.endMeasure(measureId
, beginId
);
447 return startResponse
;
450 private async stopTransaction(
452 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
453 ): Promise
<StopTransactionResponse
> {
454 const measureId
= 'StopTransaction with ATG';
455 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
456 let stopResponse
: StopTransactionResponse
;
457 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
458 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
459 ++this.connectorsStatus
.get(connectorId
).stopTransactionRequests
;
460 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
461 ++this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
;
463 ++this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
;
466 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
468 `${this.logPrefix(connectorId)} stopping a not started transaction${
469 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
473 PerformanceStatistics
.endMeasure(measureId
, beginId
);
477 private getRequireAuthorize(): boolean {
479 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
483 private logPrefix
= (connectorId
?: number): string => {
485 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
486 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}
` : ''
491 private handleStartTransactionResponse(
493 startResponse
: StartTransactionResponse
495 ++this.connectorsStatus
.get(connectorId
).startTransactionRequests
;
496 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
497 ++this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
;
499 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
500 ++this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
;