1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
5 import { hoursToMilliseconds
, secondsToMilliseconds
} from
'date-fns';
7 import type { ChargingStation
} from
'./ChargingStation';
8 import { checkChargingStation
} from
'./Helpers';
9 import { IdTagsCache
} from
'./IdTagsCache';
10 import { OCPPServiceUtils
} from
'./ocpp';
11 import { BaseError
} from
'../exception';
12 import { PerformanceStatistics
} from
'../performance';
17 type StartTransactionRequest
,
18 type StartTransactionResponse
,
20 StopTransactionReason
,
21 type StopTransactionResponse
,
26 formatDurationMilliSeconds
,
35 const moduleName
= 'AutomaticTransactionGenerator';
37 export class AutomaticTransactionGenerator
extends AsyncResource
{
38 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
40 AutomaticTransactionGenerator
43 public readonly connectorsStatus
: Map
<number, Status
>;
44 public started
: boolean;
45 private starting
: boolean;
46 private stopping
: boolean;
47 private readonly chargingStation
: ChargingStation
;
49 private constructor(chargingStation
: ChargingStation
) {
52 this.starting
= false;
53 this.stopping
= false;
54 this.chargingStation
= chargingStation
;
55 this.connectorsStatus
= new Map
<number, Status
>();
56 this.initializeConnectorsStatus();
59 public static getInstance(
60 chargingStation
: ChargingStation
,
61 ): AutomaticTransactionGenerator
| undefined {
62 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
63 AutomaticTransactionGenerator
.instances
.set(
64 chargingStation
.stationInfo
.hashId
,
65 new AutomaticTransactionGenerator(chargingStation
),
68 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
71 public start(): void {
72 if (checkChargingStation(this.chargingStation
, this.logPrefix()) === false) {
75 if (this.started
=== true) {
76 logger
.warn(`${this.logPrefix()} is already started`);
79 if (this.starting
=== true) {
80 logger
.warn(`${this.logPrefix()} is already starting`);
84 this.startConnectors();
86 this.starting
= false;
90 if (this.started
=== false) {
91 logger
.warn(`${this.logPrefix()} is already stopped`);
94 if (this.stopping
=== true) {
95 logger
.warn(`${this.logPrefix()} is already stopping`);
99 this.stopConnectors();
100 this.started
= false;
101 this.stopping
= false;
104 public startConnector(connectorId
: number): void {
105 if (checkChargingStation(this.chargingStation
, this.logPrefix(connectorId
)) === false) {
108 if (this.connectorsStatus
.has(connectorId
) === false) {
109 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
110 throw new BaseError(`Connector ${connectorId} does not exist`);
112 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
113 this.runInAsyncScope(
114 this.internalStartConnector
.bind(this) as (
115 this: AutomaticTransactionGenerator
,
120 ).catch(Constants
.EMPTY_FUNCTION
);
121 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
122 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
126 public stopConnector(connectorId
: number): void {
127 if (this.connectorsStatus
.has(connectorId
) === false) {
128 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
129 throw new BaseError(`Connector ${connectorId} does not exist`);
131 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
132 this.connectorsStatus
.get(connectorId
)!.start
= false;
133 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
134 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
138 private startConnectors(): void {
140 this.connectorsStatus
?.size
> 0 &&
141 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
143 this.connectorsStatus
.clear();
144 this.initializeConnectorsStatus();
146 if (this.chargingStation
.hasEvses
) {
147 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
149 for (const connectorId
of evseStatus
.connectors
.keys()) {
150 this.startConnector(connectorId
);
155 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
156 if (connectorId
> 0) {
157 this.startConnector(connectorId
);
163 private stopConnectors(): void {
164 if (this.chargingStation
.hasEvses
) {
165 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
167 for (const connectorId
of evseStatus
.connectors
.keys()) {
168 this.stopConnector(connectorId
);
173 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
174 if (connectorId
> 0) {
175 this.stopConnector(connectorId
);
181 private async internalStartConnector(connectorId
: number): Promise
<void> {
182 this.setStartConnectorStatus(connectorId
);
186 )} started on connector and will run for ${formatDurationMilliSeconds(
187 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
188 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
191 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
192 if (!this.canStartConnector(connectorId
)) {
193 this.stopConnector(connectorId
);
196 if (!this.chargingStation
?.ocppRequestService
) {
200 )} transaction loop waiting for charging station service to be initialized`,
203 await sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
204 } while (!this.chargingStation
?.ocppRequestService
);
206 const wait
= secondsToMilliseconds(
208 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
209 .maxDelayBetweenTwoTransactions
,
210 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()
211 .minDelayBetweenTwoTransactions
,
214 logger
.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
216 const start
= secureRandom();
219 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
221 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
223 const startResponse
= await this.startTransaction(connectorId
);
224 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
225 // Wait until end of transaction
226 const waitTrxEnd
= secondsToMilliseconds(
228 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().maxDuration
,
229 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().minDuration
,
233 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
234 .getConnectorStatus(connectorId)
235 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
239 await sleep(waitTrxEnd
);
242 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
243 .getConnectorStatus(connectorId)
244 ?.transactionId?.toString()}`,
246 await this.stopTransaction(connectorId
);
249 ++this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
!;
250 ++this.connectorsStatus
.get(connectorId
)!.skippedTransactions
!;
252 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
254 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
256 ?.skippedTransactions?.toString()} transaction(s)`,
259 this.connectorsStatus
.get(connectorId
)!.lastRunDate
= new Date();
261 this.connectorsStatus
.get(connectorId
)!.stoppedDate
= new Date();
265 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
266 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
267 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
271 `${this.logPrefix(connectorId)} connector status: %j`,
272 this.connectorsStatus
.get(connectorId
),
276 private setStartConnectorStatus(connectorId
: number): void {
277 this.connectorsStatus
.get(connectorId
)!.skippedConsecutiveTransactions
= 0;
278 const previousRunDuration
=
279 this.connectorsStatus
.get(connectorId
)?.startDate
&&
280 this.connectorsStatus
.get(connectorId
)?.lastRunDate
281 ? this.connectorsStatus
.get(connectorId
)!.lastRunDate
!.getTime() -
282 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime()
284 this.connectorsStatus
.get(connectorId
)!.startDate
= new Date();
285 this.connectorsStatus
.get(connectorId
)!.stopDate
= new Date(
286 this.connectorsStatus
.get(connectorId
)!.startDate
!.getTime() +
288 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().stopAfterHours
,
292 this.connectorsStatus
.get(connectorId
)!.start
= true;
295 private canStartConnector(connectorId
: number): boolean {
296 if (new Date() > this.connectorsStatus
.get(connectorId
)!.stopDate
!) {
299 if (this.chargingStation
.inAcceptedState() === false) {
303 )} entered in transaction loop while the charging station is not in accepted state`,
307 if (this.chargingStation
.isChargingStationAvailable() === false) {
311 )} entered in transaction loop while the charging station is unavailable`,
315 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
319 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
324 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
325 ConnectorStatusEnum
.Unavailable
330 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
337 private initializeConnectorsStatus(): void {
338 if (this.chargingStation
.hasEvses
) {
339 for (const [evseId
, evseStatus
] of this.chargingStation
.evses
) {
341 for (const connectorId
of evseStatus
.connectors
.keys()) {
342 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
347 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
348 if (connectorId
> 0) {
349 this.connectorsStatus
.set(connectorId
, this.getConnectorStatus(connectorId
));
355 private getConnectorStatus(connectorId
: number): Status
{
356 const connectorStatus
= this.chargingStation
.getAutomaticTransactionGeneratorStatuses()
357 ? cloneObject
<Status
[]>(this.chargingStation
.getAutomaticTransactionGeneratorStatuses()!)[
361 delete connectorStatus
?.startDate
;
362 delete connectorStatus
?.lastRunDate
;
363 delete connectorStatus
?.stopDate
;
364 delete connectorStatus
?.stoppedDate
;
368 authorizeRequests
: 0,
369 acceptedAuthorizeRequests
: 0,
370 rejectedAuthorizeRequests
: 0,
371 startTransactionRequests
: 0,
372 acceptedStartTransactionRequests
: 0,
373 rejectedStartTransactionRequests
: 0,
374 stopTransactionRequests
: 0,
375 acceptedStopTransactionRequests
: 0,
376 rejectedStopTransactionRequests
: 0,
377 skippedConsecutiveTransactions
: 0,
378 skippedTransactions
: 0,
383 private async startTransaction(
385 ): Promise
<StartTransactionResponse
| undefined> {
386 const measureId
= 'StartTransaction with ATG';
387 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
388 let startResponse
: StartTransactionResponse
| undefined;
389 if (this.chargingStation
.hasIdTags()) {
390 const idTag
= IdTagsCache
.getInstance().getIdTag(
391 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration().idTagDistribution
!,
392 this.chargingStation
,
395 const startTransactionLogMsg
= `${this.logPrefix(
397 )} start transaction with an idTag '${idTag}'`;
398 if (this.getRequireAuthorize()) {
399 ++this.connectorsStatus
.get(connectorId
)!.authorizeRequests
!;
400 if (await OCPPServiceUtils
.isIdTagAuthorized(this.chargingStation
, connectorId
, idTag
)) {
401 ++this.connectorsStatus
.get(connectorId
)!.acceptedAuthorizeRequests
!;
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 ++this.connectorsStatus
.get(connectorId
)!.rejectedAuthorizeRequests
!;
416 PerformanceStatistics
.endMeasure(measureId
, beginId
);
417 return startResponse
;
419 logger
.info(startTransactionLogMsg
);
421 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
422 StartTransactionRequest
,
423 StartTransactionResponse
424 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
428 this.handleStartTransactionResponse(connectorId
, startResponse
);
429 PerformanceStatistics
.endMeasure(measureId
, beginId
);
430 return startResponse
;
432 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
433 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
434 StartTransactionRequest
,
435 StartTransactionResponse
436 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
437 this.handleStartTransactionResponse(connectorId
, startResponse
);
438 PerformanceStatistics
.endMeasure(measureId
, beginId
);
439 return startResponse
;
442 private async stopTransaction(
444 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
,
445 ): Promise
<StopTransactionResponse
| undefined> {
446 const measureId
= 'StopTransaction with ATG';
447 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
448 let stopResponse
: StopTransactionResponse
| undefined;
449 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
450 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
451 ++this.connectorsStatus
.get(connectorId
)!.stopTransactionRequests
!;
452 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
453 ++this.connectorsStatus
.get(connectorId
)!.acceptedStopTransactionRequests
!;
455 ++this.connectorsStatus
.get(connectorId
)!.rejectedStopTransactionRequests
!;
458 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
460 `${this.logPrefix(connectorId)} stopping a not started transaction${
461 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}
` : ''
465 PerformanceStatistics
.endMeasure(measureId
, beginId
);
469 private getRequireAuthorize(): boolean {
471 this.chargingStation
.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize
?? true
475 private logPrefix
= (connectorId
?: number): string => {
477 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
478 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId!.toString()}
` : ''
483 private handleStartTransactionResponse(
485 startResponse
: StartTransactionResponse
,
487 ++this.connectorsStatus
.get(connectorId
)!.startTransactionRequests
!;
488 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
489 ++this.connectorsStatus
.get(connectorId
)!.acceptedStartTransactionRequests
!;
491 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
492 ++this.connectorsStatus
.get(connectorId
)!.rejectedStartTransactionRequests
!;