1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { hoursToMilliseconds
, secondsToMilliseconds
} from
'date-fns';
5 import type { ChargingStation
} from
'./ChargingStation';
6 import { checkChargingStation
} from
'./Helpers';
7 import { IdTagsCache
} from
'./IdTagsCache';
8 import { isIdTagAuthorized
} from
'./ocpp';
9 import { BaseError
} from
'../exception';
10 import { PerformanceStatistics
} from
'../performance';
14 type StartTransactionRequest
,
15 type StartTransactionResponse
,
17 StopTransactionReason
,
18 type StopTransactionResponse
,
23 formatDurationMilliSeconds
,
32 export class AutomaticTransactionGenerator
{
33 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
35 AutomaticTransactionGenerator
38 public readonly connectorsStatus
: Map
<number, Status
>;
39 public started
: boolean;
40 private starting
: boolean;
41 private stopping
: boolean;
42 private readonly chargingStation
: ChargingStation
;
44 private constructor(chargingStation
: ChargingStation
) {
46 this.starting
= false;
47 this.stopping
= false;
48 this.chargingStation
= chargingStation
;
49 this.connectorsStatus
= new Map
<number, Status
>();
50 this.initializeConnectorsStatus();
53 public static getInstance(
54 chargingStation
: ChargingStation
,
55 ): AutomaticTransactionGenerator
| undefined {
56 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
57 AutomaticTransactionGenerator
.instances
.set(
58 chargingStation
.stationInfo
.hashId
,
59 new AutomaticTransactionGenerator(chargingStation
),
62 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
65 public start(): void {
66 if (checkChargingStation(this.chargingStation
, this.logPrefix()) === false) {
69 if (this.started
=== true) {
70 logger
.warn(`${this.logPrefix()} is already started`);
73 if (this.starting
=== true) {
74 logger
.warn(`${this.logPrefix()} is already starting`);
78 this.startConnectors();
80 this.starting
= false;
84 if (this.started
=== false) {
85 logger
.warn(`${this.logPrefix()} is already stopped`);
88 if (this.stopping
=== true) {
89 logger
.warn(`${this.logPrefix()} is already stopping`);
93 this.stopConnectors();
95 this.stopping
= false;
98 public startConnector(connectorId
: number): void {
99 if (checkChargingStation(this.chargingStation
, this.logPrefix(connectorId
)) === false) {
102 if (this.connectorsStatus
.has(connectorId
) === false) {
103 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
104 throw new BaseError(`Connector ${connectorId} does not exist`);
106 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
107 this.internalStartConnector(connectorId
).catch(Constants
.EMPTY_FUNCTION
);
108 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
109 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
113 public stopConnector(connectorId
: number): void {
114 if (this.connectorsStatus
.has(connectorId
) === false) {
115 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
116 throw new BaseError(`Connector ${connectorId} does not exist`);
118 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
119 this.connectorsStatus
.get(connectorId
)!.start
= false;
120 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
121 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
125 private startConnectors(): void {
127 this.connectorsStatus
?.size
> 0 &&
128 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
130 this.connectorsStatus
.clear();
131 this.initializeConnectorsStatus();
133 if (this.chargingStation
.hasEvses
) {
134 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
136 for (const connectorId
of evseStatus
.connectors
.keys()) {
137 this.startConnector(connectorId
);
142 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
143 if (connectorId
> 0) {
144 this.startConnector(connectorId
);
150 private stopConnectors(): void {
151 if (this.chargingStation
.hasEvses
) {
152 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
154 for (const connectorId
of evseStatus
.connectors
.keys()) {
155 this.stopConnector(connectorId
);
160 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
161 if (connectorId
> 0) {
162 this.stopConnector(connectorId
);
168 private async internalStartConnector(connectorId
: number): Promise
<void> {
169 this.setStartConnectorStatus(connectorId
);
173 )} started on connector and will run for ${formatDurationMilliSeconds(
174 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
175 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
178 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
179 await this.waitChargingStationServiceInitialization(connectorId
);
180 await this.waitChargingStationAvailable(connectorId
);
181 await this.waitConnectorAvailable(connectorId
);
182 if (!this.canStartConnector(connectorId
)) {
183 this.stopConnector(connectorId
);
186 const wait
= secondsToMilliseconds(
188 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
189 .maxDelayBetweenTwoTransactions
,
190 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
191 .minDelayBetweenTwoTransactions
,
194 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
196 const start
= secureRandom();
199 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
201 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
203 const startResponse
= await this.startTransaction(connectorId
);
204 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
205 // Wait until end of transaction
206 const waitTrxEnd
= secondsToMilliseconds(
208 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
209 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
,
215 )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId)
216 ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`,
218 await sleep(waitTrxEnd
);
219 await this.stopTransaction(connectorId
);
222 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
223 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
225 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
227 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
228 ?.skippedTransactions} transaction(s)`,
231 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
233 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
237 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
238 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
239 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
243 `${this.logPrefix(connectorId)} connector status: %j`,
244 this.connectorsStatus
.get(connectorId
),
248 private setStartConnectorStatus(connectorId
: number): void {
249 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
250 const previousRunDuration
=
251 this.connectorsStatus
.get(connectorId
)?.startDate
&&
252 this.connectorsStatus
.get(connectorId
)?.lastRunDate
253 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
254 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
256 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
257 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
258 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
260 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
264 this.connectorsStatus
.get(connectorId
)!.start
= true;
267 private canStartConnector(connectorId
: number): boolean {
268 if (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
271 if (this.chargingStation
.inAcceptedState() === false) {
275 )} entered in transaction loop while the charging station is not in accepted state`,
279 if (this.chargingStation
.isChargingStationAvailable() === false) {
283 )} entered in transaction loop while the charging station is unavailable`,
287 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
291 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
298 private async waitChargingStationServiceInitialization(connectorId
: number): Promise
<void> {
300 while (!this.chargingStation
?.ocppRequestService
) {
305 )} transaction loop waiting for charging station service to be initialized`,
309 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
313 private async waitChargingStationAvailable(connectorId
: number): Promise
<void> {
315 while (!this.chargingStation
.isChargingStationAvailable()) {
320 )} transaction loop waiting for charging station to be available`,
324 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
328 private async waitConnectorAvailable(connectorId
: number): Promise
<void> {
330 while (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
335 )} transaction loop waiting for connector ${connectorId} to be available`,
339 await sleep(Constants
.CHARGING_STATION_ATG_AVAILABILITY_TIME
);
343 private initializeConnectorsStatus(): void {
344 if (this.chargingStation
.hasEvses
) {
345 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
347 for (const connectorId
of evseStatus
.connectors
.keys()) {
348 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
353 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
354 if (connectorId
> 0) {
355 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
361 private getConnectorStatus(connectorId
: number): Status
{
362 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()?.[
365 ? cloneObject
<Status
>(
366 this.chargingStation
.getAutomaticTransactionGeneratorStatuses()![connectorId
],
369 this.resetConnectorStatus(connectorStatus
);
373 authorizeRequests
: 0,
374 acceptedAuthorizeRequests
: 0,
375 rejectedAuthorizeRequests
: 0,
376 startTransactionRequests
: 0,
377 acceptedStartTransactionRequests
: 0,
378 rejectedStartTransactionRequests
: 0,
379 stopTransactionRequests
: 0,
380 acceptedStopTransactionRequests
: 0,
381 rejectedStopTransactionRequests
: 0,
382 skippedConsecutiveTransactions
: 0,
383 skippedTransactions
: 0,
388 private resetConnectorStatus(connectorStatus
: Status
| undefined): void {
389 if (connectorStatus
=== undefined) {
392 delete connectorStatus
?.startDate
;
393 delete connectorStatus
?.lastRunDate
;
394 delete connectorStatus
?.stopDate
;
395 delete connectorStatus
?.stoppedDate
;
398 (connectorStatus
.start
=== true ||
399 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().enable
=== false)
401 connectorStatus
.start
= false;
405 private async startTransaction(
407 ): Promise
<StartTransactionResponse
| undefined> {
408 const measureId
= 'StartTransaction with ATG';
409 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
410 let startResponse
: StartTransactionResponse
| undefined;
411 if (this.chargingStation
.hasIdTags()) {
412 const idTag
= IdTagsCache
.getInstance().getIdTag(
413 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
414 this.chargingStation
,
417 const startTransactionLogMsg
= `${this.logPrefix(
419 )} start transaction with an idTag '${idTag}'`;
420 if (this.getRequireAuthorize()) {
421 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
422 if (await isIdTagAuthorized(this.chargingStation
, connectorId
, idTag
)) {
423 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
424 logger
.info(startTransactionLogMsg
);
426 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
427 StartTransactionRequest
,
428 StartTransactionResponse
429 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
433 this.handleStartTransactionResponse(connectorId
, startResponse
);
434 PerformanceStatistics
.endMeasure(measureId
, beginId
);
435 return startResponse
;
437 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
438 PerformanceStatistics
.endMeasure(measureId
, beginId
);
439 return startResponse
;
441 logger
.info(startTransactionLogMsg
);
443 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
444 StartTransactionRequest
,
445 StartTransactionResponse
446 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
450 this.handleStartTransactionResponse(connectorId
, startResponse
);
451 PerformanceStatistics
.endMeasure(measureId
, beginId
);
452 return startResponse
;
454 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
455 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
456 StartTransactionRequest
,
457 StartTransactionResponse
458 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
459 this.handleStartTransactionResponse(connectorId
, startResponse
);
460 PerformanceStatistics
.endMeasure(measureId
, beginId
);
461 return startResponse
;
464 private async stopTransaction(
466 reason
= StopTransactionReason
.LOCAL
,
467 ): Promise
<StopTransactionResponse
| undefined> {
468 const measureId
= 'StopTransaction with ATG';
469 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
470 let stopResponse
: StopTransactionResponse
| undefined;
471 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
475 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
478 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
479 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
480 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
481 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
483 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
486 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
488 `${this.logPrefix(connectorId)} stopping a not started transaction${
489 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}
` : ''
493 PerformanceStatistics
.endMeasure(measureId
, beginId
);
497 private getRequireAuthorize(): boolean {
499 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
503 private logPrefix
= (connectorId
?: number): string => {
505 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
506 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}
` : ''
511 private handleStartTransactionResponse(
513 startResponse
: StartTransactionResponse
,
515 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
516 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
517 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
519 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
520 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;