1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { AuthorizationStatus
, AuthorizeResponse
, StartTransactionResponse
, StopTransactionReason
, StopTransactionResponse
} from
'../types/ocpp/Transaction';
5 import ChargingStation from
'./ChargingStation';
6 import Constants from
'../utils/Constants';
7 import PerformanceStatistics from
'../performance/PerformanceStatistics';
8 import Utils from
'../utils/Utils';
9 import logger from
'../utils/Logger';
11 export default class AutomaticTransactionGenerator
{
12 public started
: boolean;
13 private startDate
!: Date;
14 private lastRunDate
!: Date;
15 private stopDate
!: Date;
16 private chargingStation
: ChargingStation
;
18 constructor(chargingStation
: ChargingStation
) {
19 this.chargingStation
= chargingStation
;
23 public start(): void {
24 const previousRunDuration
= (this?.startDate
&& this?.lastRunDate
) ? (this.lastRunDate
.getTime() - this.startDate
.getTime()) : 0;
25 this.startDate
= new Date();
26 this.lastRunDate
= this.startDate
;
27 this.stopDate
= new Date(this.startDate
.getTime()
28 + (this.chargingStation
.stationInfo
?.AutomaticTransactionGenerator
?.stopAfterHours
?? Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) * 3600 * 1000
29 - previousRunDuration
);
31 for (const connector
in this.chargingStation
.connectors
) {
32 if (Utils
.convertToInt(connector
) > 0) {
33 // Avoid hogging the event loop with a busy loop
35 this.startOnConnector(Utils
.convertToInt(connector
)).catch(() => { /* This is intentional */ });
39 logger
.info(this.logPrefix() + ' started and will run for ' + Utils
.formatDurationMilliSeconds(this.stopDate
.getTime() - this.startDate
.getTime()));
44 logger
.error(`${this.logPrefix()} trying to stop while not started`);
48 logger
.info(`${this.logPrefix()} over and lasted for ${Utils.formatDurationMilliSeconds(this.lastRunDate.getTime() - this.startDate.getTime())}. Stopping all transactions`);
51 private async startOnConnector(connectorId
: number): Promise
<void> {
52 logger
.info(this.logPrefix(connectorId
) + ' started on connector');
53 let skippedTransactions
= 0;
54 let skippedTransactionsTotal
= 0;
55 while (this.started
) {
56 if ((new Date()) > this.stopDate
) {
60 if (!this.chargingStation
.isRegistered()) {
61 logger
.error(this.logPrefix(connectorId
) + ' Entered in transaction loop while the charging station is not registered');
64 if (!this.chargingStation
.isChargingStationAvailable()) {
65 logger
.info(this.logPrefix(connectorId
) + ' Entered in transaction loop while the charging station is unavailable');
69 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
70 logger
.info(`${this.logPrefix(connectorId)} Entered in transaction loop while the connector ${connectorId} is unavailable, stop it`);
73 if (!this.chargingStation
?.ocppRequestService
) {
74 logger
.info(`${this.logPrefix(connectorId)} Transaction loop waiting for charging station service to be initialized`);
76 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
77 } while (!this.chargingStation
?.ocppRequestService
);
79 const wait
= Utils
.getRandomInt(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDelayBetweenTwoTransactions
,
80 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDelayBetweenTwoTransactions
) * 1000;
81 logger
.info(this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
));
82 await Utils
.sleep(wait
);
83 const start
= Utils
.secureRandom();
84 if (start
< this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.probabilityOfStart
) {
85 skippedTransactions
= 0;
87 const startResponse
= await this.startTransaction(connectorId
);
88 if (startResponse
?.idTagInfo
?.status !== AuthorizationStatus
.ACCEPTED
) {
89 logger
.warn(this.logPrefix(connectorId
) + ' transaction rejected');
90 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_WAIT_TIME
);
92 // Wait until end of transaction
93 const waitTrxEnd
= Utils
.getRandomInt(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDuration
,
94 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDuration
) * 1000;
95 logger
.info(this.logPrefix(connectorId
) + ' transaction ' + this.chargingStation
.getConnector(connectorId
).transactionId
.toString() + ' will stop in ' + Utils
.formatDurationMilliSeconds(waitTrxEnd
));
96 await Utils
.sleep(waitTrxEnd
);
98 logger
.info(this.logPrefix(connectorId
) + ' stop transaction ' + this.chargingStation
.getConnector(connectorId
).transactionId
.toString());
99 await this.stopTransaction(connectorId
);
102 skippedTransactions
++;
103 skippedTransactionsTotal
++;
104 logger
.info(this.logPrefix(connectorId
) + ' skipped transaction ' + skippedTransactions
.toString() + '/' + skippedTransactionsTotal
.toString());
106 this.lastRunDate
= new Date();
108 await this.stopTransaction(connectorId
);
109 logger
.info(this.logPrefix(connectorId
) + ' stopped on connector');
112 private async startTransaction(connectorId
: number): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
113 const measureId
= 'StartTransaction with ATG';
114 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
115 let startResponse
: StartTransactionResponse
;
116 if (this.chargingStation
.hasAuthorizedTags()) {
117 const tagId
= this.chargingStation
.getRandomTagId();
118 if (this.chargingStation
.getAutomaticTransactionGeneratorRequireAuthorize()) {
120 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(connectorId
, tagId
);
121 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
122 logger
.info(this.logPrefix(connectorId
) + ' start transaction for tagID ' + tagId
);
124 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, tagId
);
125 PerformanceStatistics
.endMeasure(measureId
, beginId
);
126 return startResponse
;
128 PerformanceStatistics
.endMeasure(measureId
, beginId
);
129 return authorizeResponse
;
131 logger
.info(this.logPrefix(connectorId
) + ' start transaction for tagID ' + tagId
);
133 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, tagId
);
134 PerformanceStatistics
.endMeasure(measureId
, beginId
);
135 return startResponse
;
137 logger
.info(this.logPrefix(connectorId
) + ' start transaction without a tagID');
138 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
);
139 PerformanceStatistics
.endMeasure(measureId
, beginId
);
140 return startResponse
;
143 private async stopTransaction(connectorId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
144 const measureId
= 'StopTransaction with ATG';
145 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
146 const transactionId
= this.chargingStation
.getConnector(connectorId
).transactionId
;
147 let stopResponse
: StopTransactionResponse
;
148 if (this.chargingStation
.getConnector(connectorId
)?.transactionStarted
) {
149 stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
150 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
151 this.chargingStation
.getTransactionIdTag(transactionId
),
154 logger
.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction ${transactionId}`);
156 PerformanceStatistics
.endMeasure(measureId
, beginId
);
160 private logPrefix(connectorId
?: number): string {
162 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG on connector #' + connectorId
.toString() + ':');
164 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG:');