1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
5 import { type ChargingStation
, ChargingStationUtils
} from
'./internal';
6 import { BaseError
} from
'../exception';
7 // import { PerformanceStatistics } from '../performance';
8 import { PerformanceStatistics
} from
'../performance/PerformanceStatistics';
11 type AuthorizeRequest
,
12 type AuthorizeResponse
,
13 type AutomaticTransactionGeneratorConfiguration
,
17 type StartTransactionRequest
,
18 type StartTransactionResponse
,
20 StopTransactionReason
,
21 type StopTransactionResponse
,
23 import { Constants
, Utils
, logger
} from
'../utils';
25 const moduleName
= 'AutomaticTransactionGenerator';
27 export class AutomaticTransactionGenerator
extends AsyncResource
{
28 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
30 AutomaticTransactionGenerator
33 public readonly connectorsStatus
: Map
<number, Status
>;
34 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
35 public started
: boolean;
36 private readonly chargingStation
: ChargingStation
;
37 private idTagIndex
: number;
40 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
41 chargingStation
: ChargingStation
45 this.configuration
= automaticTransactionGeneratorConfiguration
;
46 this.chargingStation
= chargingStation
;
48 this.connectorsStatus
= new Map
<number, Status
>();
49 this.initializeConnectorsStatus();
52 public static getInstance(
53 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
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(
60 automaticTransactionGeneratorConfiguration
,
65 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
68 public start(): void {
69 if (this.checkChargingStation() === false) {
72 if (this.started
=== true) {
73 logger
.warn(`${this.logPrefix()} is already started`);
76 this.startConnectors();
81 if (this.started
=== false) {
82 logger
.warn(`${this.logPrefix()} is already stopped`);
85 this.stopConnectors();
89 public startConnector(connectorId
: number): void {
90 if (this.checkChargingStation(connectorId
) === false) {
93 if (this.connectorsStatus
.has(connectorId
) === false) {
94 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
95 throw new BaseError(`Connector ${connectorId} does not exist`);
97 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
99 this.internalStartConnector
.bind(this) as (
100 this: AutomaticTransactionGenerator
,
105 ).catch(Constants
.EMPTY_FUNCTION
);
106 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
107 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
111 public stopConnector(connectorId
: number): void {
112 if (this.connectorsStatus
.has(connectorId
) === false) {
113 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
114 throw new BaseError(`Connector ${connectorId} does not exist`);
116 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
117 this.connectorsStatus
.get(connectorId
).start
= false;
118 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
119 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
123 private startConnectors(): void {
125 this.connectorsStatus
?.size
> 0 &&
126 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
128 this.connectorsStatus
.clear();
129 this.initializeConnectorsStatus();
131 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
132 if (connectorId
> 0) {
133 this.startConnector(connectorId
);
138 private stopConnectors(): void {
139 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
140 if (connectorId
> 0) {
141 this.stopConnector(connectorId
);
146 private async internalStartConnector(connectorId
: number): Promise
<void> {
147 this.setStartConnectorStatus(connectorId
);
151 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
152 this.connectorsStatus.get(connectorId).stopDate.getTime() -
153 this.connectorsStatus.get(connectorId).startDate.getTime()
156 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
157 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
158 this.stopConnector(connectorId
);
161 if (this.chargingStation
.isInAcceptedState() === false) {
165 )} entered in transaction loop while the charging station is not in accepted state`
167 this.stopConnector(connectorId
);
170 if (this.chargingStation
.isChargingStationAvailable() === false) {
174 )} entered in transaction loop while the charging station is unavailable`
176 this.stopConnector(connectorId
);
179 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
183 )} entered in transaction loop while the connector ${connectorId} is unavailable`
185 this.stopConnector(connectorId
);
189 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
190 ConnectorStatusEnum
.Unavailable
195 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
197 this.stopConnector(connectorId
);
200 if (!this.chargingStation
?.ocppRequestService
) {
204 )} transaction loop waiting for charging station service to be initialized`
207 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
208 } while (!this.chargingStation
?.ocppRequestService
);
211 Utils
.getRandomInteger(
212 this.configuration
.maxDelayBetweenTwoTransactions
,
213 this.configuration
.minDelayBetweenTwoTransactions
216 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
218 await Utils
.sleep(wait
);
219 const start
= Utils
.secureRandom();
220 if (start
< this.configuration
.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
227 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
230 `${this.logPrefix(connectorId)} transaction ${this.chargingStation
231 .getConnectorStatus(connectorId)
232 ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
236 await Utils
.sleep(waitTrxEnd
);
239 `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation
240 .getConnectorStatus(connectorId)
241 ?.transactionId?.toString()}`
243 await this.stopTransaction(connectorId
);
246 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
247 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
249 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
251 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
253 ?.skippedTransactions?.toString()} transaction(s)`
256 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
258 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
262 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
263 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
264 this.connectorsStatus.get(connectorId).startDate.getTime()
268 `${this.logPrefix(connectorId)} connector status: %j`,
269 this.connectorsStatus
.get(connectorId
)
273 private setStartConnectorStatus(connectorId
: number): void {
274 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
275 const previousRunDuration
=
276 this.connectorsStatus
.get(connectorId
)?.startDate
&&
277 this.connectorsStatus
.get(connectorId
)?.lastRunDate
278 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
279 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
281 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
282 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
283 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
284 (this.configuration
.stopAfterHours
??
285 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
290 this.connectorsStatus
.get(connectorId
).start
= true;
293 private initializeConnectorsStatus(): void {
294 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
295 if (connectorId
> 0) {
296 this.connectorsStatus
.set(connectorId
, {
298 authorizeRequests
: 0,
299 acceptedAuthorizeRequests
: 0,
300 rejectedAuthorizeRequests
: 0,
301 startTransactionRequests
: 0,
302 acceptedStartTransactionRequests
: 0,
303 rejectedStartTransactionRequests
: 0,
304 stopTransactionRequests
: 0,
305 acceptedStopTransactionRequests
: 0,
306 rejectedStopTransactionRequests
: 0,
307 skippedConsecutiveTransactions
: 0,
308 skippedTransactions
: 0,
314 private async startTransaction(
316 ): Promise
<StartTransactionResponse
| undefined> {
317 const measureId
= 'StartTransaction with ATG';
318 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
319 let startResponse
: StartTransactionResponse
;
320 if (this.chargingStation
.hasAuthorizedTags()) {
321 const idTag
= this.getIdTag(connectorId
);
322 const startTransactionLogMsg
= `${this.logPrefix(
324 )} start transaction with an idTag '${idTag}'`;
325 if (this.getRequireAuthorize()) {
326 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
328 const authorizeResponse
: AuthorizeResponse
=
329 await this.chargingStation
.ocppRequestService
.requestHandler
<
332 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
335 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
336 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
337 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
338 logger
.info(startTransactionLogMsg
);
340 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
341 StartTransactionRequest
,
342 StartTransactionResponse
343 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
347 this.handleStartTransactionResponse(connectorId
, startResponse
);
348 PerformanceStatistics
.endMeasure(measureId
, beginId
);
349 return startResponse
;
351 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
352 PerformanceStatistics
.endMeasure(measureId
, beginId
);
353 return startResponse
;
355 logger
.info(startTransactionLogMsg
);
357 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
358 StartTransactionRequest
,
359 StartTransactionResponse
360 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
364 this.handleStartTransactionResponse(connectorId
, startResponse
);
365 PerformanceStatistics
.endMeasure(measureId
, beginId
);
366 return startResponse
;
368 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
369 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
370 StartTransactionRequest
,
371 StartTransactionResponse
372 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
373 this.handleStartTransactionResponse(connectorId
, startResponse
);
374 PerformanceStatistics
.endMeasure(measureId
, beginId
);
375 return startResponse
;
378 private async stopTransaction(
380 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
381 ): Promise
<StopTransactionResponse
> {
382 const measureId
= 'StopTransaction with ATG';
383 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
384 let stopResponse
: StopTransactionResponse
;
385 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
386 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
387 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
388 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
389 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
391 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
394 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
396 `${this.logPrefix(connectorId)} stopping a not started transaction${
397 !Utils.isNullOrUndefined(transactionId) ? ` ${transactionId?.toString()}
` : ''
401 PerformanceStatistics
.endMeasure(measureId
, beginId
);
405 private getRequireAuthorize(): boolean {
406 return this.configuration
?.requireAuthorize
?? true;
409 private getRandomIdTag(authorizationFile
: string): string {
410 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
411 this.idTagIndex
= Math.floor(Utils
.secureRandom() * tags
.length
);
412 return tags
[this.idTagIndex
];
415 private getRoundRobinIdTag(authorizationFile
: string): string {
416 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
417 const idTag
= tags
[this.idTagIndex
];
418 this.idTagIndex
= this.idTagIndex
=== tags
.length
- 1 ? 0 : this.idTagIndex
+ 1;
422 private getConnectorAffinityIdTag(authorizationFile
: string, connectorId
: number): string {
423 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
424 this.idTagIndex
= (this.chargingStation
.index
- 1 + (connectorId
- 1)) % tags
.length
;
425 return tags
[this.idTagIndex
];
428 private getIdTag(connectorId
: number): string {
429 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(
430 this.chargingStation
.stationInfo
432 switch (this.configuration
?.idTagDistribution
) {
433 case IdTagDistribution
.RANDOM
:
434 return this.getRandomIdTag(authorizationFile
);
435 case IdTagDistribution
.ROUND_ROBIN
:
436 return this.getRoundRobinIdTag(authorizationFile
);
437 case IdTagDistribution
.CONNECTOR_AFFINITY
:
438 return this.getConnectorAffinityIdTag(authorizationFile
, connectorId
);
440 return this.getRoundRobinIdTag(authorizationFile
);
444 private logPrefix
= (connectorId
?: number): string => {
445 return Utils
.logPrefix(
446 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
447 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
452 private handleStartTransactionResponse(
454 startResponse
: StartTransactionResponse
456 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
457 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
458 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
460 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
461 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
465 private checkChargingStation(connectorId
?: number): boolean {
466 if (this.chargingStation
.started
=== false && this.chargingStation
.starting
=== false) {
467 logger
.warn(`${this.logPrefix(connectorId)} charging station is stopped, cannot proceed`);