1 // Partial Copyright Jerome Benoit. 2021. 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.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.connectorsStatus
.has(connectorId
) === false) {
91 logger
.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
92 throw new BaseError(`Connector ${connectorId} does not exist`);
94 if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
96 this.internalStartConnector
.bind(this) as (this: this, ...args
: any[]) => unknown
,
100 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
101 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
105 public stopConnector(connectorId
: number): void {
106 if (this.connectorsStatus
.has(connectorId
) === false) {
107 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
108 throw new BaseError(`Connector ${connectorId} does not exist`);
110 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
111 this.connectorsStatus
.get(connectorId
).start
= false;
112 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
113 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
117 private startConnectors(): void {
119 this.connectorsStatus
?.size
> 0 &&
120 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
122 this.connectorsStatus
.clear();
123 this.initializeConnectorsStatus();
125 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
126 if (connectorId
> 0) {
127 this.startConnector(connectorId
);
132 private stopConnectors(): void {
133 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
134 if (connectorId
> 0) {
135 this.stopConnector(connectorId
);
140 private async internalStartConnector(connectorId
: number): Promise
<void> {
141 this.setStartConnectorStatus(connectorId
);
143 this.logPrefix(connectorId
) +
144 ' started on connector and will run for ' +
145 Utils
.formatDurationMilliSeconds(
146 this.connectorsStatus
.get(connectorId
).stopDate
.getTime() -
147 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
150 while (this.connectorsStatus
.get(connectorId
).start
=== true) {
151 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
152 this.stopConnector(connectorId
);
155 if (!this.chargingStation
.isInAcceptedState()) {
157 this.logPrefix(connectorId
) +
158 ' entered in transaction loop while the charging station is not in accepted state'
160 this.stopConnector(connectorId
);
163 if (!this.chargingStation
.isChargingStationAvailable()) {
165 this.logPrefix(connectorId
) +
166 ' entered in transaction loop while the charging station is unavailable'
168 this.stopConnector(connectorId
);
171 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
175 )} entered in transaction loop while the connector ${connectorId} is unavailable`
177 this.stopConnector(connectorId
);
180 if (!this.chargingStation
?.ocppRequestService
) {
184 )} transaction loop waiting for charging station service to be initialized`
187 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
188 } while (!this.chargingStation
?.ocppRequestService
);
191 Utils
.getRandomInteger(
192 this.configuration
.maxDelayBetweenTwoTransactions
,
193 this.configuration
.minDelayBetweenTwoTransactions
196 this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
)
198 await Utils
.sleep(wait
);
199 const start
= Utils
.secureRandom();
200 if (start
< this.configuration
.probabilityOfStart
) {
201 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
203 const startResponse
= await this.startTransaction(connectorId
);
204 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
205 // Wait until end of transaction
207 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
210 this.logPrefix(connectorId
) +
212 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
213 ' started and will stop in ' +
214 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
216 await Utils
.sleep(waitTrxEnd
);
219 this.logPrefix(connectorId
) +
220 ' stop transaction ' +
221 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
223 await this.stopTransaction(connectorId
);
226 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
227 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
229 this.logPrefix(connectorId
) +
230 ' skipped consecutively ' +
231 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
233 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
237 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
239 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
241 this.logPrefix(connectorId
) +
242 ' stopped on connector and lasted for ' +
243 Utils
.formatDurationMilliSeconds(
244 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
245 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
249 `${this.logPrefix(connectorId)} connector status: %j`,
250 this.connectorsStatus
.get(connectorId
)
254 private setStartConnectorStatus(connectorId
: number): void {
255 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
256 const previousRunDuration
=
257 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
258 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
259 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
260 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
262 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
263 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
264 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
265 (this.configuration
.stopAfterHours
??
266 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
271 this.connectorsStatus
.get(connectorId
).start
= true;
274 private initializeConnectorsStatus(): void {
275 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
276 if (connectorId
> 0) {
277 this.connectorsStatus
.set(connectorId
, {
279 authorizeRequests
: 0,
280 acceptedAuthorizeRequests
: 0,
281 rejectedAuthorizeRequests
: 0,
282 startTransactionRequests
: 0,
283 acceptedStartTransactionRequests
: 0,
284 rejectedStartTransactionRequests
: 0,
285 stopTransactionRequests
: 0,
286 acceptedStopTransactionRequests
: 0,
287 rejectedStopTransactionRequests
: 0,
288 skippedConsecutiveTransactions
: 0,
289 skippedTransactions
: 0,
295 private async startTransaction(
297 ): Promise
<StartTransactionResponse
| undefined> {
298 const measureId
= 'StartTransaction with ATG';
299 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
300 let startResponse
: StartTransactionResponse
;
301 if (this.chargingStation
.hasAuthorizedTags()) {
302 const idTag
= this.getIdTag(connectorId
);
303 const startTransactionLogMsg
= `${this.logPrefix(
305 )} start transaction with an idTag '${idTag}'`;
306 if (this.getRequireAuthorize()) {
307 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
309 const authorizeResponse
: AuthorizeResponse
=
310 await this.chargingStation
.ocppRequestService
.requestHandler
<
313 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
316 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
317 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
318 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
319 logger
.info(startTransactionLogMsg
);
321 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
322 StartTransactionRequest
,
323 StartTransactionResponse
324 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
328 this.handleStartTransactionResponse(connectorId
, startResponse
);
329 PerformanceStatistics
.endMeasure(measureId
, beginId
);
330 return startResponse
;
332 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
333 PerformanceStatistics
.endMeasure(measureId
, beginId
);
334 return startResponse
;
336 logger
.info(startTransactionLogMsg
);
338 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
339 StartTransactionRequest
,
340 StartTransactionResponse
341 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
345 this.handleStartTransactionResponse(connectorId
, startResponse
);
346 PerformanceStatistics
.endMeasure(measureId
, beginId
);
347 return startResponse
;
349 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
350 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
351 StartTransactionRequest
,
352 StartTransactionResponse
353 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
354 this.handleStartTransactionResponse(connectorId
, startResponse
);
355 PerformanceStatistics
.endMeasure(measureId
, beginId
);
356 return startResponse
;
359 private async stopTransaction(
361 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
362 ): Promise
<StopTransactionResponse
> {
363 const measureId
= 'StopTransaction with ATG';
364 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
365 let stopResponse
: StopTransactionResponse
;
366 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
367 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
368 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
369 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
370 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
372 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
375 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
377 `${this.logPrefix(connectorId)} stopping a not started transaction${
378 transactionId ? ' ' + transactionId.toString() : ''
382 PerformanceStatistics
.endMeasure(measureId
, beginId
);
386 private getRequireAuthorize(): boolean {
387 return this.configuration
?.requireAuthorize
?? true;
390 private getRandomIdTag(authorizationFile
: string): string {
391 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
392 this.idTagIndex
= Math.floor(Utils
.secureRandom() * tags
.length
);
393 return tags
[this.idTagIndex
];
396 private getRoundRobinIdTag(authorizationFile
: string): string {
397 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
398 const idTag
= tags
[this.idTagIndex
];
399 this.idTagIndex
= this.idTagIndex
=== tags
.length
- 1 ? 0 : this.idTagIndex
+ 1;
403 private getConnectorAffinityIdTag(authorizationFile
: string, connectorId
: number): string {
404 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
405 this.idTagIndex
= (this.chargingStation
.index
- 1 + (connectorId
- 1)) % tags
.length
;
406 return tags
[this.idTagIndex
];
409 private getIdTag(connectorId
: number): string {
410 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(
411 this.chargingStation
.stationInfo
413 switch (this.configuration
?.idTagDistribution
) {
414 case IdTagDistribution
.RANDOM
:
415 return this.getRandomIdTag(authorizationFile
);
416 case IdTagDistribution
.ROUND_ROBIN
:
417 return this.getRoundRobinIdTag(authorizationFile
);
418 case IdTagDistribution
.CONNECTOR_AFFINITY
:
419 return this.getConnectorAffinityIdTag(authorizationFile
, connectorId
);
421 return this.getRoundRobinIdTag(authorizationFile
);
425 private logPrefix(connectorId
?: number): string {
426 return Utils
.logPrefix(
427 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
428 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
433 private handleStartTransactionResponse(
435 startResponse
: StartTransactionResponse
437 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
438 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
439 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
441 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
442 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;