1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
5 import { AuthorizedTagsCache
, 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
,
16 type StartTransactionRequest
,
17 type StartTransactionResponse
,
19 StopTransactionReason
,
20 type StopTransactionResponse
,
22 import { Constants
, Utils
, logger
} from
'../utils';
24 const moduleName
= 'AutomaticTransactionGenerator';
26 export class AutomaticTransactionGenerator
extends AsyncResource
{
27 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
29 AutomaticTransactionGenerator
32 public readonly connectorsStatus
: Map
<number, Status
>;
33 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
34 public started
: boolean;
35 private readonly chargingStation
: ChargingStation
;
36 private idTagIndex
: number;
39 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
40 chargingStation
: ChargingStation
44 this.configuration
= automaticTransactionGeneratorConfiguration
;
45 this.chargingStation
= chargingStation
;
47 this.connectorsStatus
= new Map
<number, Status
>();
48 this.initializeConnectorsStatus();
51 public static getInstance(
52 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
53 chargingStation
: ChargingStation
54 ): AutomaticTransactionGenerator
| undefined {
55 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
56 AutomaticTransactionGenerator
.instances
.set(
57 chargingStation
.stationInfo
.hashId
,
58 new AutomaticTransactionGenerator(
59 automaticTransactionGeneratorConfiguration
,
64 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
67 public start(): void {
69 ChargingStationUtils
.checkChargingStation(this.chargingStation
, this.logPrefix()) === 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 {
92 ChargingStationUtils
.checkChargingStation(
94 this.logPrefix(connectorId
)
99 if (this.connectorsStatus
.has(connectorId
) === false) {
100 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
101 throw new BaseError(`Connector ${connectorId} does not exist`);
103 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
104 this.runInAsyncScope(
105 this.internalStartConnector
.bind(this) as (
106 this: AutomaticTransactionGenerator
,
111 ).catch(Constants
.EMPTY_FUNCTION
);
112 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
113 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
117 public stopConnector(connectorId
: number): void {
118 if (this.connectorsStatus
.has(connectorId
) === false) {
119 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
120 throw new BaseError(`Connector ${connectorId} does not exist`);
122 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
123 this.connectorsStatus
.get(connectorId
).start
= false;
124 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
125 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
129 private startConnectors(): void {
131 this.connectorsStatus
?.size
> 0 &&
132 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
134 this.connectorsStatus
.clear();
135 this.initializeConnectorsStatus();
137 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
138 if (connectorId
> 0) {
139 this.startConnector(connectorId
);
144 private stopConnectors(): void {
145 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
146 if (connectorId
> 0) {
147 this.stopConnector(connectorId
);
152 private async internalStartConnector(connectorId
: number): Promise
<void> {
153 this.setStartConnectorStatus(connectorId
);
157 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
158 this.connectorsStatus.get(connectorId).stopDate.getTime() -
159 this.connectorsStatus.get(connectorId).startDate.getTime()
162 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
163 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
164 this.stopConnector(connectorId
);
167 if (this.chargingStation
.isInAcceptedState() === false) {
171 )} entered in transaction loop while the charging station is not in accepted state`
173 this.stopConnector(connectorId
);
176 if (this.chargingStation
.isChargingStationAvailable() === false) {
180 )} entered in transaction loop while the charging station is unavailable`
182 this.stopConnector(connectorId
);
185 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
189 )} entered in transaction loop while the connector ${connectorId} is unavailable`
191 this.stopConnector(connectorId
);
195 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
196 ConnectorStatusEnum
.Unavailable
201 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
203 this.stopConnector(connectorId
);
206 if (!this.chargingStation
?.ocppRequestService
) {
210 )} transaction loop waiting for charging station service to be initialized`
213 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
214 } while (!this.chargingStation
?.ocppRequestService
);
217 Utils
.getRandomInteger(
218 this.configuration
.maxDelayBetweenTwoTransactions
,
219 this.configuration
.minDelayBetweenTwoTransactions
222 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
224 await Utils
.sleep(wait
);
225 const start
= Utils
.secureRandom();
226 if (start
< this.configuration
.probabilityOfStart
) {
227 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
229 const startResponse
= await this.startTransaction(connectorId
);
230 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
231 // Wait until end of transaction
233 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
236 `${this.logPrefix(connectorId)} transaction ${this.chargingStation
237 .getConnectorStatus(connectorId)
238 ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
242 await Utils
.sleep(waitTrxEnd
);
245 `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation
246 .getConnectorStatus(connectorId)
247 ?.transactionId?.toString()}`
249 await this.stopTransaction(connectorId
);
252 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
253 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
255 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
257 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
259 ?.skippedTransactions?.toString()} transaction(s)`
262 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
264 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
268 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
269 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
270 this.connectorsStatus.get(connectorId).startDate.getTime()
274 `${this.logPrefix(connectorId)} connector status: %j`,
275 this.connectorsStatus
.get(connectorId
)
279 private setStartConnectorStatus(connectorId
: number): void {
280 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
281 const previousRunDuration
=
282 this.connectorsStatus
.get(connectorId
)?.startDate
&&
283 this.connectorsStatus
.get(connectorId
)?.lastRunDate
284 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
285 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
287 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
288 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
289 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
290 (this.configuration
.stopAfterHours
??
291 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
296 this.connectorsStatus
.get(connectorId
).start
= true;
299 private initializeConnectorsStatus(): void {
300 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
301 if (connectorId
> 0) {
302 this.connectorsStatus
.set(connectorId
, {
304 authorizeRequests
: 0,
305 acceptedAuthorizeRequests
: 0,
306 rejectedAuthorizeRequests
: 0,
307 startTransactionRequests
: 0,
308 acceptedStartTransactionRequests
: 0,
309 rejectedStartTransactionRequests
: 0,
310 stopTransactionRequests
: 0,
311 acceptedStopTransactionRequests
: 0,
312 rejectedStopTransactionRequests
: 0,
313 skippedConsecutiveTransactions
: 0,
314 skippedTransactions
: 0,
320 private async startTransaction(
322 ): Promise
<StartTransactionResponse
| undefined> {
323 const measureId
= 'StartTransaction with ATG';
324 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
325 let startResponse
: StartTransactionResponse
;
326 if (this.chargingStation
.hasAuthorizedTags()) {
327 const idTag
= AuthorizedTagsCache
.getInstance().getIdTag(
328 this.configuration
?.idTagDistribution
,
329 this.chargingStation
,
332 const startTransactionLogMsg
= `${this.logPrefix(
334 )} start transaction with an idTag '${idTag}'`;
335 if (this.getRequireAuthorize()) {
336 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
338 const authorizeResponse
: AuthorizeResponse
=
339 await this.chargingStation
.ocppRequestService
.requestHandler
<
342 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
345 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
346 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
347 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
348 logger
.info(startTransactionLogMsg
);
350 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
351 StartTransactionRequest
,
352 StartTransactionResponse
353 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
357 this.handleStartTransactionResponse(connectorId
, startResponse
);
358 PerformanceStatistics
.endMeasure(measureId
, beginId
);
359 return startResponse
;
361 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
362 PerformanceStatistics
.endMeasure(measureId
, beginId
);
363 return startResponse
;
365 logger
.info(startTransactionLogMsg
);
367 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
368 StartTransactionRequest
,
369 StartTransactionResponse
370 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
374 this.handleStartTransactionResponse(connectorId
, startResponse
);
375 PerformanceStatistics
.endMeasure(measureId
, beginId
);
376 return startResponse
;
378 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
379 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
380 StartTransactionRequest
,
381 StartTransactionResponse
382 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
383 this.handleStartTransactionResponse(connectorId
, startResponse
);
384 PerformanceStatistics
.endMeasure(measureId
, beginId
);
385 return startResponse
;
388 private async stopTransaction(
390 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
391 ): Promise
<StopTransactionResponse
> {
392 const measureId
= 'StopTransaction with ATG';
393 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
394 let stopResponse
: StopTransactionResponse
;
395 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
396 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
397 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
398 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
399 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
401 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
404 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
406 `${this.logPrefix(connectorId)} stopping a not started transaction${
407 !Utils.isNullOrUndefined(transactionId) ? ` ${transactionId?.toString()}
` : ''
411 PerformanceStatistics
.endMeasure(measureId
, beginId
);
415 private getRequireAuthorize(): boolean {
416 return this.configuration
?.requireAuthorize
?? true;
419 private logPrefix
= (connectorId
?: number): string => {
420 return Utils
.logPrefix(
421 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
422 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
427 private handleStartTransactionResponse(
429 startResponse
: StartTransactionResponse
431 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
432 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
433 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
435 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
436 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;