1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'async_hooks';
5 import type { ChargingStation
} from
'./ChargingStation';
6 import { ChargingStationUtils
} from
'./ChargingStationUtils';
7 import { BaseError
} from
'../exception';
8 import { PerformanceStatistics
} from
'../performance';
11 type AuthorizeRequest
,
12 type AuthorizeResponse
,
13 type AutomaticTransactionGeneratorConfiguration
,
16 type StartTransactionRequest
,
17 type StartTransactionResponse
,
19 StopTransactionReason
,
20 type StopTransactionResponse
,
22 import { Constants
} from
'../utils/Constants';
23 import { logger
} from
'../utils/Logger';
24 import { Utils
} from
'../utils/Utils';
26 const moduleName
= 'AutomaticTransactionGenerator';
28 export class AutomaticTransactionGenerator
extends AsyncResource
{
29 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
31 AutomaticTransactionGenerator
34 public readonly connectorsStatus
: Map
<number, Status
>;
35 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
36 public started
: boolean;
37 private readonly chargingStation
: ChargingStation
;
38 private idTagIndex
: number;
41 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
42 chargingStation
: ChargingStation
46 this.configuration
= automaticTransactionGeneratorConfiguration
;
47 this.chargingStation
= chargingStation
;
49 this.connectorsStatus
= new Map
<number, Status
>();
50 this.initializeConnectorsStatus();
53 public static getInstance(
54 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
55 chargingStation
: ChargingStation
56 ): AutomaticTransactionGenerator
| undefined {
57 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
58 AutomaticTransactionGenerator
.instances
.set(
59 chargingStation
.stationInfo
.hashId
,
60 new AutomaticTransactionGenerator(
61 automaticTransactionGeneratorConfiguration
,
66 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
69 public start(): void {
70 if (this.checkChargingStation() === false) {
73 if (this.started
=== true) {
74 logger
.warn(`${this.logPrefix()} is already started`);
77 this.startConnectors();
82 if (this.started
=== false) {
83 logger
.warn(`${this.logPrefix()} is already stopped`);
86 this.stopConnectors();
90 public startConnector(connectorId
: number): void {
91 if (this.checkChargingStation(connectorId
) === false) {
94 if (this.connectorsStatus
.has(connectorId
) === false) {
95 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
96 throw new BaseError(`Connector ${connectorId} does not exist`);
98 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
100 this.internalStartConnector
.bind(this) as (
101 this: AutomaticTransactionGenerator
,
107 /* This is intentional */
109 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
110 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
114 public stopConnector(connectorId
: number): void {
115 if (this.connectorsStatus
.has(connectorId
) === false) {
116 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
117 throw new BaseError(`Connector ${connectorId} does not exist`);
119 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
120 this.connectorsStatus
.get(connectorId
).start
= false;
121 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
122 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
126 private startConnectors(): void {
128 this.connectorsStatus
?.size
> 0 &&
129 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
131 this.connectorsStatus
.clear();
132 this.initializeConnectorsStatus();
134 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
135 if (connectorId
> 0) {
136 this.startConnector(connectorId
);
141 private stopConnectors(): void {
142 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
143 if (connectorId
> 0) {
144 this.stopConnector(connectorId
);
149 private async internalStartConnector(connectorId
: number): Promise
<void> {
150 this.setStartConnectorStatus(connectorId
);
154 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
155 this.connectorsStatus.get(connectorId).stopDate.getTime() -
156 this.connectorsStatus.get(connectorId).startDate.getTime()
159 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
160 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
161 this.stopConnector(connectorId
);
164 if (this.chargingStation
.isInAcceptedState() === false) {
168 )} entered in transaction loop while the charging station is not in accepted state`
170 this.stopConnector(connectorId
);
173 if (this.chargingStation
.isChargingStationAvailable() === false) {
177 )} entered in transaction loop while the charging station is unavailable`
179 this.stopConnector(connectorId
);
182 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
186 )} entered in transaction loop while the connector ${connectorId} is unavailable`
188 this.stopConnector(connectorId
);
191 if (!this.chargingStation
?.ocppRequestService
) {
195 )} transaction loop waiting for charging station service to be initialized`
198 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
199 } while (!this.chargingStation
?.ocppRequestService
);
202 Utils
.getRandomInteger(
203 this.configuration
.maxDelayBetweenTwoTransactions
,
204 this.configuration
.minDelayBetweenTwoTransactions
207 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
209 await Utils
.sleep(wait
);
210 const start
= Utils
.secureRandom();
211 if (start
< this.configuration
.probabilityOfStart
) {
212 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
214 const startResponse
= await this.startTransaction(connectorId
);
215 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
216 // Wait until end of transaction
218 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
221 `${this.logPrefix(connectorId)} transaction ${this.chargingStation
222 .getConnectorStatus(connectorId)
223 ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
227 await Utils
.sleep(waitTrxEnd
);
230 `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation
231 .getConnectorStatus(connectorId)
232 ?.transactionId?.toString()}`
234 await this.stopTransaction(connectorId
);
237 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
238 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
240 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
242 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
244 ?.skippedTransactions?.toString()} transaction(s)`
247 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
249 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
253 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
254 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
255 this.connectorsStatus.get(connectorId).startDate.getTime()
259 `${this.logPrefix(connectorId)} connector status: %j`,
260 this.connectorsStatus
.get(connectorId
)
264 private setStartConnectorStatus(connectorId
: number): void {
265 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
266 const previousRunDuration
=
267 this.connectorsStatus
.get(connectorId
)?.startDate
&&
268 this.connectorsStatus
.get(connectorId
)?.lastRunDate
269 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
270 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
272 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
273 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
274 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
275 (this.configuration
.stopAfterHours
??
276 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
281 this.connectorsStatus
.get(connectorId
).start
= true;
284 private initializeConnectorsStatus(): void {
285 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
286 if (connectorId
> 0) {
287 this.connectorsStatus
.set(connectorId
, {
289 authorizeRequests
: 0,
290 acceptedAuthorizeRequests
: 0,
291 rejectedAuthorizeRequests
: 0,
292 startTransactionRequests
: 0,
293 acceptedStartTransactionRequests
: 0,
294 rejectedStartTransactionRequests
: 0,
295 stopTransactionRequests
: 0,
296 acceptedStopTransactionRequests
: 0,
297 rejectedStopTransactionRequests
: 0,
298 skippedConsecutiveTransactions
: 0,
299 skippedTransactions
: 0,
305 private async startTransaction(
307 ): Promise
<StartTransactionResponse
| undefined> {
308 const measureId
= 'StartTransaction with ATG';
309 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
310 let startResponse
: StartTransactionResponse
;
311 if (this.chargingStation
.hasAuthorizedTags()) {
312 const idTag
= this.getIdTag(connectorId
);
313 const startTransactionLogMsg
= `${this.logPrefix(
315 )} start transaction with an idTag '${idTag}'`;
316 if (this.getRequireAuthorize()) {
317 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
319 const authorizeResponse
: AuthorizeResponse
=
320 await this.chargingStation
.ocppRequestService
.requestHandler
<
323 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
326 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
327 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
328 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
329 logger
.info(startTransactionLogMsg
);
331 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
332 StartTransactionRequest
,
333 StartTransactionResponse
334 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
338 this.handleStartTransactionResponse(connectorId
, startResponse
);
339 PerformanceStatistics
.endMeasure(measureId
, beginId
);
340 return startResponse
;
342 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
343 PerformanceStatistics
.endMeasure(measureId
, beginId
);
344 return startResponse
;
346 logger
.info(startTransactionLogMsg
);
348 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
349 StartTransactionRequest
,
350 StartTransactionResponse
351 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
355 this.handleStartTransactionResponse(connectorId
, startResponse
);
356 PerformanceStatistics
.endMeasure(measureId
, beginId
);
357 return startResponse
;
359 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
360 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
361 StartTransactionRequest
,
362 StartTransactionResponse
363 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
364 this.handleStartTransactionResponse(connectorId
, startResponse
);
365 PerformanceStatistics
.endMeasure(measureId
, beginId
);
366 return startResponse
;
369 private async stopTransaction(
371 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
372 ): Promise
<StopTransactionResponse
> {
373 const measureId
= 'StopTransaction with ATG';
374 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
375 let stopResponse
: StopTransactionResponse
;
376 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
377 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
378 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
379 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
380 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
382 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
385 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
387 `${this.logPrefix(connectorId)} stopping a not started transaction${
388 !Utils.isNullOrUndefined(transactionId) ? ` ${transactionId?.toString()}
` : ''
392 PerformanceStatistics
.endMeasure(measureId
, beginId
);
396 private getRequireAuthorize(): boolean {
397 return this.configuration
?.requireAuthorize
?? true;
400 private getRandomIdTag(authorizationFile
: string): string {
401 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
402 this.idTagIndex
= Math.floor(Utils
.secureRandom() * tags
.length
);
403 return tags
[this.idTagIndex
];
406 private getRoundRobinIdTag(authorizationFile
: string): string {
407 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
408 const idTag
= tags
[this.idTagIndex
];
409 this.idTagIndex
= this.idTagIndex
=== tags
.length
- 1 ? 0 : this.idTagIndex
+ 1;
413 private getConnectorAffinityIdTag(authorizationFile
: string, connectorId
: number): string {
414 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
415 this.idTagIndex
= (this.chargingStation
.index
- 1 + (connectorId
- 1)) % tags
.length
;
416 return tags
[this.idTagIndex
];
419 private getIdTag(connectorId
: number): string {
420 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(
421 this.chargingStation
.stationInfo
423 switch (this.configuration
?.idTagDistribution
) {
424 case IdTagDistribution
.RANDOM
:
425 return this.getRandomIdTag(authorizationFile
);
426 case IdTagDistribution
.ROUND_ROBIN
:
427 return this.getRoundRobinIdTag(authorizationFile
);
428 case IdTagDistribution
.CONNECTOR_AFFINITY
:
429 return this.getConnectorAffinityIdTag(authorizationFile
, connectorId
);
431 return this.getRoundRobinIdTag(authorizationFile
);
435 private logPrefix
= (connectorId
?: number): string => {
436 return Utils
.logPrefix(
437 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
438 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
443 private handleStartTransactionResponse(
445 startResponse
: StartTransactionResponse
447 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
448 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
449 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
451 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
452 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
456 private checkChargingStation(connectorId
?: number): boolean {
457 if (this.chargingStation
.started
=== false && this.chargingStation
.starting
=== false) {
458 logger
.warn(`${this.logPrefix(connectorId)} charging station is stopped, cannot proceed`);