1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'async_hooks';
5 import BaseError from
'../exception/BaseError';
6 import PerformanceStatistics from
'../performance/PerformanceStatistics';
8 type AutomaticTransactionGeneratorConfiguration
,
11 } from
'../types/AutomaticTransactionGenerator';
12 import { RequestCommand
} from
'../types/ocpp/Requests';
15 type AuthorizeRequest
,
16 type AuthorizeResponse
,
17 type StartTransactionRequest
,
18 type StartTransactionResponse
,
19 StopTransactionReason
,
20 type StopTransactionResponse
,
21 } from
'../types/ocpp/Transaction';
22 import Constants from
'../utils/Constants';
23 import logger from
'../utils/Logger';
24 import Utils from
'../utils/Utils';
25 import type ChargingStation from
'./ChargingStation';
26 import { ChargingStationUtils
} from
'./ChargingStationUtils';
28 const moduleName
= 'AutomaticTransactionGenerator';
30 export default class AutomaticTransactionGenerator
extends AsyncResource
{
31 private static readonly instances
: Map
<string, AutomaticTransactionGenerator
> = new Map
<
33 AutomaticTransactionGenerator
36 public readonly connectorsStatus
: Map
<number, Status
>;
37 public readonly configuration
: AutomaticTransactionGeneratorConfiguration
;
38 public started
: boolean;
39 private readonly chargingStation
: ChargingStation
;
40 private idTagIndex
: number;
43 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
44 chargingStation
: ChargingStation
48 this.configuration
= automaticTransactionGeneratorConfiguration
;
49 this.chargingStation
= chargingStation
;
51 this.connectorsStatus
= new Map
<number, Status
>();
52 this.initializeConnectorsStatus();
55 public static getInstance(
56 automaticTransactionGeneratorConfiguration
: AutomaticTransactionGeneratorConfiguration
,
57 chargingStation
: ChargingStation
58 ): AutomaticTransactionGenerator
{
59 if (AutomaticTransactionGenerator
.instances
.has(chargingStation
.stationInfo
.hashId
) === false) {
60 AutomaticTransactionGenerator
.instances
.set(
61 chargingStation
.stationInfo
.hashId
,
62 new AutomaticTransactionGenerator(
63 automaticTransactionGeneratorConfiguration
,
68 return AutomaticTransactionGenerator
.instances
.get(chargingStation
.stationInfo
.hashId
);
71 public start(): void {
72 if (this.checkChargingStation() === false) {
75 if (this.started
=== true) {
76 logger
.warn(`${this.logPrefix()} is already started`);
79 this.startConnectors();
84 if (this.started
=== false) {
85 logger
.warn(`${this.logPrefix()} is already stopped`);
88 this.stopConnectors();
92 public startConnector(connectorId
: number): void {
93 if (this.checkChargingStation(connectorId
) === false) {
96 if (this.connectorsStatus
.has(connectorId
) === false) {
97 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
98 throw new BaseError(`Connector ${connectorId} does not exist`);
100 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
101 this.runInAsyncScope(
102 this.internalStartConnector
.bind(this) as (
103 this: AutomaticTransactionGenerator
,
109 /* This is intentional */
111 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
112 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
116 public stopConnector(connectorId
: number): void {
117 if (this.connectorsStatus
.has(connectorId
) === false) {
118 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
119 throw new BaseError(`Connector ${connectorId} does not exist`);
121 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
122 this.connectorsStatus
.get(connectorId
).start
= false;
123 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
124 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
128 private startConnectors(): void {
130 this.connectorsStatus
?.size
> 0 &&
131 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
133 this.connectorsStatus
.clear();
134 this.initializeConnectorsStatus();
136 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
137 if (connectorId
> 0) {
138 this.startConnector(connectorId
);
143 private stopConnectors(): void {
144 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
145 if (connectorId
> 0) {
146 this.stopConnector(connectorId
);
151 private async internalStartConnector(connectorId
: number): Promise
<void> {
152 this.setStartConnectorStatus(connectorId
);
154 this.logPrefix(connectorId
) +
155 ' started on connector and will run for ' +
156 Utils
.formatDurationMilliSeconds(
157 this.connectorsStatus
.get(connectorId
).stopDate
.getTime() -
158 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
161 while (this.connectorsStatus
.get(connectorId
).start
=== true) {
162 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
163 this.stopConnector(connectorId
);
166 if (this.chargingStation
.isInAcceptedState() === false) {
168 this.logPrefix(connectorId
) +
169 ' entered in transaction loop while the charging station is not in accepted state'
171 this.stopConnector(connectorId
);
174 if (this.chargingStation
.isChargingStationAvailable() === false) {
176 this.logPrefix(connectorId
) +
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
) +
223 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
224 ' started and will stop in ' +
225 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
227 await Utils
.sleep(waitTrxEnd
);
230 this.logPrefix(connectorId
) +
231 ' stop transaction ' +
232 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
234 await this.stopTransaction(connectorId
);
237 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
238 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
240 this.logPrefix(connectorId
) +
241 ' skipped consecutively ' +
242 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
244 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
248 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
250 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
252 this.logPrefix(connectorId
) +
253 ' stopped on connector and lasted for ' +
254 Utils
.formatDurationMilliSeconds(
255 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
256 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
260 `${this.logPrefix(connectorId)} connector status: %j`,
261 this.connectorsStatus
.get(connectorId
)
265 private setStartConnectorStatus(connectorId
: number): void {
266 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
267 const previousRunDuration
=
268 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
269 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
270 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
271 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
273 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
274 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
275 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
276 (this.configuration
.stopAfterHours
??
277 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
282 this.connectorsStatus
.get(connectorId
).start
= true;
285 private initializeConnectorsStatus(): void {
286 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
287 if (connectorId
> 0) {
288 this.connectorsStatus
.set(connectorId
, {
290 authorizeRequests
: 0,
291 acceptedAuthorizeRequests
: 0,
292 rejectedAuthorizeRequests
: 0,
293 startTransactionRequests
: 0,
294 acceptedStartTransactionRequests
: 0,
295 rejectedStartTransactionRequests
: 0,
296 stopTransactionRequests
: 0,
297 acceptedStopTransactionRequests
: 0,
298 rejectedStopTransactionRequests
: 0,
299 skippedConsecutiveTransactions
: 0,
300 skippedTransactions
: 0,
306 private async startTransaction(
308 ): Promise
<StartTransactionResponse
| undefined> {
309 const measureId
= 'StartTransaction with ATG';
310 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
311 let startResponse
: StartTransactionResponse
;
312 if (this.chargingStation
.hasAuthorizedTags()) {
313 const idTag
= this.getIdTag(connectorId
);
314 const startTransactionLogMsg
= `${this.logPrefix(
316 )} start transaction with an idTag '${idTag}'`;
317 if (this.getRequireAuthorize()) {
318 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
320 const authorizeResponse
: AuthorizeResponse
=
321 await this.chargingStation
.ocppRequestService
.requestHandler
<
324 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
327 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
328 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
329 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
330 logger
.info(startTransactionLogMsg
);
332 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
333 StartTransactionRequest
,
334 StartTransactionResponse
335 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
339 this.handleStartTransactionResponse(connectorId
, startResponse
);
340 PerformanceStatistics
.endMeasure(measureId
, beginId
);
341 return startResponse
;
343 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
344 PerformanceStatistics
.endMeasure(measureId
, beginId
);
345 return startResponse
;
347 logger
.info(startTransactionLogMsg
);
349 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
350 StartTransactionRequest
,
351 StartTransactionResponse
352 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
356 this.handleStartTransactionResponse(connectorId
, startResponse
);
357 PerformanceStatistics
.endMeasure(measureId
, beginId
);
358 return startResponse
;
360 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
361 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
362 StartTransactionRequest
,
363 StartTransactionResponse
364 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
365 this.handleStartTransactionResponse(connectorId
, startResponse
);
366 PerformanceStatistics
.endMeasure(measureId
, beginId
);
367 return startResponse
;
370 private async stopTransaction(
372 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
373 ): Promise
<StopTransactionResponse
> {
374 const measureId
= 'StopTransaction with ATG';
375 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
376 let stopResponse
: StopTransactionResponse
;
377 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
378 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
379 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
380 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
381 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
383 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
386 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
388 `${this.logPrefix(connectorId)} stopping a not started transaction${
389 transactionId ? ' ' + transactionId.toString() : ''
393 PerformanceStatistics
.endMeasure(measureId
, beginId
);
397 private getRequireAuthorize(): boolean {
398 return this.configuration
?.requireAuthorize
?? true;
401 private getRandomIdTag(authorizationFile
: string): string {
402 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
403 this.idTagIndex
= Math.floor(Utils
.secureRandom() * tags
.length
);
404 return tags
[this.idTagIndex
];
407 private getRoundRobinIdTag(authorizationFile
: string): string {
408 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
409 const idTag
= tags
[this.idTagIndex
];
410 this.idTagIndex
= this.idTagIndex
=== tags
.length
- 1 ? 0 : this.idTagIndex
+ 1;
414 private getConnectorAffinityIdTag(authorizationFile
: string, connectorId
: number): string {
415 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
416 this.idTagIndex
= (this.chargingStation
.index
- 1 + (connectorId
- 1)) % tags
.length
;
417 return tags
[this.idTagIndex
];
420 private getIdTag(connectorId
: number): string {
421 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(
422 this.chargingStation
.stationInfo
424 switch (this.configuration
?.idTagDistribution
) {
425 case IdTagDistribution
.RANDOM
:
426 return this.getRandomIdTag(authorizationFile
);
427 case IdTagDistribution
.ROUND_ROBIN
:
428 return this.getRoundRobinIdTag(authorizationFile
);
429 case IdTagDistribution
.CONNECTOR_AFFINITY
:
430 return this.getConnectorAffinityIdTag(authorizationFile
, connectorId
);
432 return this.getRoundRobinIdTag(authorizationFile
);
436 private logPrefix(connectorId
?: number): string {
437 return Utils
.logPrefix(
438 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
439 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
444 private handleStartTransactionResponse(
446 startResponse
: StartTransactionResponse
448 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
449 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
450 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
452 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
453 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
457 private checkChargingStation(connectorId
?: number): boolean {
458 if (this.chargingStation
.started
=== false && this.chargingStation
.starting
=== false) {
459 logger
.warn(`${this.logPrefix(connectorId)} charging station is stopped, cannot proceed`);