1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
5 import { type ChargingStation
, ChargingStationUtils
, IdTagsCache
} 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
;
38 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
39 chargingStation
: ChargingStation
43 this.configuration
= automaticTransactionGeneratorConfiguration
;
44 this.chargingStation
= chargingStation
;
45 this.connectorsStatus
= new Map
<number, Status
>();
46 this.initializeConnectorsStatus();
49 public static getInstance(
50 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
51 chargingStation
: ChargingStation
52 ): AutomaticTransactionGenerator
| undefined {
53 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
54 AutomaticTransactionGenerator
.instances
.set(
55 chargingStation
.stationInfo
.hashId
,
56 new AutomaticTransactionGenerator(
57 automaticTransactionGeneratorConfiguration
,
62 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
65 public start(): void {
67 ChargingStationUtils
.checkChargingStation(this.chargingStation
, this.logPrefix()) === false
71 if (this.started
=== true) {
72 logger
.warn(`${this.logPrefix()} is already started`);
75 this.startConnectors();
80 if (this.started
=== false) {
81 logger
.warn(`${this.logPrefix()} is already stopped`);
84 this.stopConnectors();
88 public startConnector(connectorId
: number): void {
90 ChargingStationUtils
.checkChargingStation(
92 this.logPrefix(connectorId
)
97 if (this.connectorsStatus
.has(connectorId
) === false) {
98 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
99 throw new BaseError(`Connector ${connectorId} does not exist`);
101 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
102 this.runInAsyncScope(
103 this.internalStartConnector
.bind(this) as (
104 this: AutomaticTransactionGenerator
,
109 ).catch(Constants
.EMPTY_FUNCTION
);
110 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
111 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
115 public stopConnector(connectorId
: number): void {
116 if (this.connectorsStatus
.has(connectorId
) === false) {
117 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
118 throw new BaseError(`Connector ${connectorId} does not exist`);
120 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
121 this.connectorsStatus
.get(connectorId
).start
= false;
122 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
123 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
127 private startConnectors(): void {
129 this.connectorsStatus
?.size
> 0 &&
130 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
132 this.connectorsStatus
.clear();
133 this.initializeConnectorsStatus();
135 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
136 if (connectorId
> 0) {
137 this.startConnector(connectorId
);
142 private stopConnectors(): void {
143 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
144 if (connectorId
> 0) {
145 this.stopConnector(connectorId
);
150 private async internalStartConnector(connectorId
: number): Promise
<void> {
151 this.setStartConnectorStatus(connectorId
);
155 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
156 this.connectorsStatus.get(connectorId).stopDate.getTime() -
157 this.connectorsStatus.get(connectorId).startDate.getTime()
160 while (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
161 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
162 this.stopConnector(connectorId
);
165 if (this.chargingStation
.isInAcceptedState() === false) {
169 )} entered in transaction loop while the charging station is not in accepted state`
171 this.stopConnector(connectorId
);
174 if (this.chargingStation
.isChargingStationAvailable() === false) {
178 )} entered in transaction loop while the charging station is unavailable`
180 this.stopConnector(connectorId
);
183 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
187 )} entered in transaction loop while the connector ${connectorId} is unavailable`
189 this.stopConnector(connectorId
);
193 this.chargingStation
.getConnectorStatus(connectorId
)?.status ===
194 ConnectorStatusEnum
.Unavailable
199 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
201 this.stopConnector(connectorId
);
204 if (!this.chargingStation
?.ocppRequestService
) {
208 )} transaction loop waiting for charging station service to be initialized`
211 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
212 } while (!this.chargingStation
?.ocppRequestService
);
215 Utils
.getRandomInteger(
216 this.configuration
.maxDelayBetweenTwoTransactions
,
217 this.configuration
.minDelayBetweenTwoTransactions
220 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
222 await Utils
.sleep(wait
);
223 const start
= Utils
.secureRandom();
224 if (start
< this.configuration
.probabilityOfStart
) {
225 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
227 const startResponse
= await this.startTransaction(connectorId
);
228 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
229 // Wait until end of transaction
231 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
234 `${this.logPrefix(connectorId)} transaction ${this.chargingStation
235 .getConnectorStatus(connectorId)
236 ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
240 await Utils
.sleep(waitTrxEnd
);
243 `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation
244 .getConnectorStatus(connectorId)
245 ?.transactionId?.toString()}`
247 await this.stopTransaction(connectorId
);
250 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
251 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
253 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
255 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
257 ?.skippedTransactions?.toString()} transaction(s)`
260 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
262 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
266 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
267 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
268 this.connectorsStatus.get(connectorId).startDate.getTime()
272 `${this.logPrefix(connectorId)} connector status: %j`,
273 this.connectorsStatus
.get(connectorId
)
277 private setStartConnectorStatus(connectorId
: number): void {
278 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
279 const previousRunDuration
=
280 this.connectorsStatus
.get(connectorId
)?.startDate
&&
281 this.connectorsStatus
.get(connectorId
)?.lastRunDate
282 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
283 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
285 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
286 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
287 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
288 (this.configuration
.stopAfterHours
??
289 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
294 this.connectorsStatus
.get(connectorId
).start
= true;
297 private initializeConnectorsStatus(): void {
298 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
299 if (connectorId
> 0) {
300 this.connectorsStatus
.set(connectorId
, {
302 authorizeRequests
: 0,
303 acceptedAuthorizeRequests
: 0,
304 rejectedAuthorizeRequests
: 0,
305 startTransactionRequests
: 0,
306 acceptedStartTransactionRequests
: 0,
307 rejectedStartTransactionRequests
: 0,
308 stopTransactionRequests
: 0,
309 acceptedStopTransactionRequests
: 0,
310 rejectedStopTransactionRequests
: 0,
311 skippedConsecutiveTransactions
: 0,
312 skippedTransactions
: 0,
318 private async startTransaction(
320 ): Promise
<StartTransactionResponse
| undefined> {
321 const measureId
= 'StartTransaction with ATG';
322 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
323 let startResponse
: StartTransactionResponse
;
324 if (this.chargingStation
.hasIdTags()) {
325 const idTag
= IdTagsCache
.getInstance().getIdTag(
326 this.configuration
?.idTagDistribution
,
327 this.chargingStation
,
330 const startTransactionLogMsg
= `${this.logPrefix(
332 )} start transaction with an idTag '${idTag}'`;
333 if (this.getRequireAuthorize()) {
334 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
336 const authorizeResponse
: AuthorizeResponse
=
337 await this.chargingStation
.ocppRequestService
.requestHandler
<
340 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
343 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
344 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
345 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
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 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
360 PerformanceStatistics
.endMeasure(measureId
, beginId
);
361 return startResponse
;
363 logger
.info(startTransactionLogMsg
);
365 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
366 StartTransactionRequest
,
367 StartTransactionResponse
368 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
372 this.handleStartTransactionResponse(connectorId
, startResponse
);
373 PerformanceStatistics
.endMeasure(measureId
, beginId
);
374 return startResponse
;
376 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
377 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
378 StartTransactionRequest
,
379 StartTransactionResponse
380 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
381 this.handleStartTransactionResponse(connectorId
, startResponse
);
382 PerformanceStatistics
.endMeasure(measureId
, beginId
);
383 return startResponse
;
386 private async stopTransaction(
388 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
389 ): Promise
<StopTransactionResponse
> {
390 const measureId
= 'StopTransaction with ATG';
391 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
392 let stopResponse
: StopTransactionResponse
;
393 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
394 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
395 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
396 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
397 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
399 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
402 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
;
404 `${this.logPrefix(connectorId)} stopping a not started transaction${
405 !Utils.isNullOrUndefined(transactionId) ? ` ${transactionId?.toString()}
` : ''
409 PerformanceStatistics
.endMeasure(measureId
, beginId
);
413 private getRequireAuthorize(): boolean {
414 return this.configuration
?.requireAuthorize
?? true;
417 private logPrefix
= (connectorId
?: number): string => {
418 return Utils
.logPrefix(
419 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
420 !Utils.isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}
` : ''
425 private handleStartTransactionResponse(
427 startResponse
: StartTransactionResponse
429 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
430 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
431 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
433 logger
.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
434 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;