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 (
97 this: AutomaticTransactionGenerator
,
103 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
104 logger
.warn(`${this.logPrefix(connectorId)} is already started on connector`);
108 public stopConnector(connectorId
: number): void {
109 if (this.connectorsStatus
.has(connectorId
) === false) {
110 logger
.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
111 throw new BaseError(`Connector ${connectorId} does not exist`);
113 if (this.connectorsStatus
.get(connectorId
)?.start
=== true) {
114 this.connectorsStatus
.get(connectorId
).start
= false;
115 } else if (this.connectorsStatus
.get(connectorId
)?.start
=== false) {
116 logger
.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
120 private startConnectors(): void {
122 this.connectorsStatus
?.size
> 0 &&
123 this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()
125 this.connectorsStatus
.clear();
126 this.initializeConnectorsStatus();
128 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
129 if (connectorId
> 0) {
130 this.startConnector(connectorId
);
135 private stopConnectors(): void {
136 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
137 if (connectorId
> 0) {
138 this.stopConnector(connectorId
);
143 private async internalStartConnector(connectorId
: number): Promise
<void> {
144 this.setStartConnectorStatus(connectorId
);
146 this.logPrefix(connectorId
) +
147 ' started on connector and will run for ' +
148 Utils
.formatDurationMilliSeconds(
149 this.connectorsStatus
.get(connectorId
).stopDate
.getTime() -
150 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
153 while (this.connectorsStatus
.get(connectorId
).start
=== true) {
154 if (new Date() > this.connectorsStatus
.get(connectorId
).stopDate
) {
155 this.stopConnector(connectorId
);
158 if (this.chargingStation
.isInAcceptedState() === false) {
160 this.logPrefix(connectorId
) +
161 ' entered in transaction loop while the charging station is not in accepted state'
163 this.stopConnector(connectorId
);
166 if (this.chargingStation
.isChargingStationAvailable() === false) {
168 this.logPrefix(connectorId
) +
169 ' entered in transaction loop while the charging station is unavailable'
171 this.stopConnector(connectorId
);
174 if (this.chargingStation
.isConnectorAvailable(connectorId
) === false) {
178 )} entered in transaction loop while the connector ${connectorId} is unavailable`
180 this.stopConnector(connectorId
);
183 if (!this.chargingStation
?.ocppRequestService
) {
187 )} transaction loop waiting for charging station service to be initialized`
190 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
191 } while (!this.chargingStation
?.ocppRequestService
);
194 Utils
.getRandomInteger(
195 this.configuration
.maxDelayBetweenTwoTransactions
,
196 this.configuration
.minDelayBetweenTwoTransactions
199 this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
)
201 await Utils
.sleep(wait
);
202 const start
= Utils
.secureRandom();
203 if (start
< this.configuration
.probabilityOfStart
) {
204 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
206 const startResponse
= await this.startTransaction(connectorId
);
207 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
208 // Wait until end of transaction
210 Utils
.getRandomInteger(this.configuration
.maxDuration
, this.configuration
.minDuration
) *
213 this.logPrefix(connectorId
) +
215 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() +
216 ' started and will stop in ' +
217 Utils
.formatDurationMilliSeconds(waitTrxEnd
)
219 await Utils
.sleep(waitTrxEnd
);
222 this.logPrefix(connectorId
) +
223 ' stop transaction ' +
224 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString()
226 await this.stopTransaction(connectorId
);
229 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
230 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
232 this.logPrefix(connectorId
) +
233 ' skipped consecutively ' +
234 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() +
236 this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() +
240 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
242 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
244 this.logPrefix(connectorId
) +
245 ' stopped on connector and lasted for ' +
246 Utils
.formatDurationMilliSeconds(
247 this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() -
248 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
252 `${this.logPrefix(connectorId)} connector status: %j`,
253 this.connectorsStatus
.get(connectorId
)
257 private setStartConnectorStatus(connectorId
: number): void {
258 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
259 const previousRunDuration
=
260 this?.connectorsStatus
.get(connectorId
)?.startDate
&&
261 this?.connectorsStatus
.get(connectorId
)?.lastRunDate
262 ? this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() -
263 this.connectorsStatus
.get(connectorId
).startDate
.getTime()
265 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
266 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(
267 this.connectorsStatus
.get(connectorId
).startDate
.getTime() +
268 (this.configuration
.stopAfterHours
??
269 Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) *
274 this.connectorsStatus
.get(connectorId
).start
= true;
277 private initializeConnectorsStatus(): void {
278 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
279 if (connectorId
> 0) {
280 this.connectorsStatus
.set(connectorId
, {
282 authorizeRequests
: 0,
283 acceptedAuthorizeRequests
: 0,
284 rejectedAuthorizeRequests
: 0,
285 startTransactionRequests
: 0,
286 acceptedStartTransactionRequests
: 0,
287 rejectedStartTransactionRequests
: 0,
288 stopTransactionRequests
: 0,
289 acceptedStopTransactionRequests
: 0,
290 rejectedStopTransactionRequests
: 0,
291 skippedConsecutiveTransactions
: 0,
292 skippedTransactions
: 0,
298 private async startTransaction(
300 ): Promise
<StartTransactionResponse
| undefined> {
301 const measureId
= 'StartTransaction with ATG';
302 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
303 let startResponse
: StartTransactionResponse
;
304 if (this.chargingStation
.hasAuthorizedTags()) {
305 const idTag
= this.getIdTag(connectorId
);
306 const startTransactionLogMsg
= `${this.logPrefix(
308 )} start transaction with an idTag '${idTag}'`;
309 if (this.getRequireAuthorize()) {
310 this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
= idTag
;
312 const authorizeResponse
: AuthorizeResponse
=
313 await this.chargingStation
.ocppRequestService
.requestHandler
<
316 >(this.chargingStation
, RequestCommand
.AUTHORIZE
, {
319 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
320 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
321 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
322 logger
.info(startTransactionLogMsg
);
324 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
325 StartTransactionRequest
,
326 StartTransactionResponse
327 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
331 this.handleStartTransactionResponse(connectorId
, startResponse
);
332 PerformanceStatistics
.endMeasure(measureId
, beginId
);
333 return startResponse
;
335 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
336 PerformanceStatistics
.endMeasure(measureId
, beginId
);
337 return startResponse
;
339 logger
.info(startTransactionLogMsg
);
341 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
342 StartTransactionRequest
,
343 StartTransactionResponse
344 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, {
348 this.handleStartTransactionResponse(connectorId
, startResponse
);
349 PerformanceStatistics
.endMeasure(measureId
, beginId
);
350 return startResponse
;
352 logger
.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
353 startResponse
= await this.chargingStation
.ocppRequestService
.requestHandler
<
354 StartTransactionRequest
,
355 StartTransactionResponse
356 >(this.chargingStation
, RequestCommand
.START_TRANSACTION
, { connectorId
});
357 this.handleStartTransactionResponse(connectorId
, startResponse
);
358 PerformanceStatistics
.endMeasure(measureId
, beginId
);
359 return startResponse
;
362 private async stopTransaction(
364 reason
: StopTransactionReason
= StopTransactionReason
.LOCAL
365 ): Promise
<StopTransactionResponse
> {
366 const measureId
= 'StopTransaction with ATG';
367 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
368 let stopResponse
: StopTransactionResponse
;
369 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
370 stopResponse
= await this.chargingStation
.stopTransactionOnConnector(connectorId
, reason
);
371 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
372 if (stopResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
373 this.connectorsStatus
.get(connectorId
).acceptedStopTransactionRequests
++;
375 this.connectorsStatus
.get(connectorId
).rejectedStopTransactionRequests
++;
378 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
380 `${this.logPrefix(connectorId)} stopping a not started transaction${
381 transactionId ? ' ' + transactionId.toString() : ''
385 PerformanceStatistics
.endMeasure(measureId
, beginId
);
389 private getRequireAuthorize(): boolean {
390 return this.configuration
?.requireAuthorize
?? true;
393 private getRandomIdTag(authorizationFile
: string): string {
394 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
395 this.idTagIndex
= Math.floor(Utils
.secureRandom() * tags
.length
);
396 return tags
[this.idTagIndex
];
399 private getRoundRobinIdTag(authorizationFile
: string): string {
400 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
401 const idTag
= tags
[this.idTagIndex
];
402 this.idTagIndex
= this.idTagIndex
=== tags
.length
- 1 ? 0 : this.idTagIndex
+ 1;
406 private getConnectorAffinityIdTag(authorizationFile
: string, connectorId
: number): string {
407 const tags
= this.chargingStation
.authorizedTagsCache
.getAuthorizedTags(authorizationFile
);
408 this.idTagIndex
= (this.chargingStation
.index
- 1 + (connectorId
- 1)) % tags
.length
;
409 return tags
[this.idTagIndex
];
412 private getIdTag(connectorId
: number): string {
413 const authorizationFile
= ChargingStationUtils
.getAuthorizationFile(
414 this.chargingStation
.stationInfo
416 switch (this.configuration
?.idTagDistribution
) {
417 case IdTagDistribution
.RANDOM
:
418 return this.getRandomIdTag(authorizationFile
);
419 case IdTagDistribution
.ROUND_ROBIN
:
420 return this.getRoundRobinIdTag(authorizationFile
);
421 case IdTagDistribution
.CONNECTOR_AFFINITY
:
422 return this.getConnectorAffinityIdTag(authorizationFile
, connectorId
);
424 return this.getRoundRobinIdTag(authorizationFile
);
428 private logPrefix(connectorId
?: number): string {
429 return Utils
.logPrefix(
430 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
431 connectorId !== undefined ? ` on connector #${connectorId.toString()}
` : ''
436 private handleStartTransactionResponse(
438 startResponse
: StartTransactionResponse
440 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
441 if (startResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
442 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
444 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
445 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;