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 { Status
} from
'../types/AutomaticTransactionGenerator';
9 import Utils from
'../utils/Utils';
10 import logger from
'../utils/Logger';
12 export default class AutomaticTransactionGenerator
{
13 public started
: boolean;
14 private chargingStation
: ChargingStation
;
15 private connectorsStatus
: Map
<number, Status
>;
17 constructor(chargingStation
: ChargingStation
) {
18 this.chargingStation
= chargingStation
;
19 this.connectorsStatus
= new Map
<number, Status
>();
20 this.stopConnectors();
24 public start(): void {
26 logger
.error(`${this.logPrefix()} trying to start while already started`);
29 this.startConnectors();
35 logger
.error(`${this.logPrefix()} trying to stop while not started`);
38 this.stopConnectors();
42 private startConnectors(): void {
43 for (const connector
in this.chargingStation
.connectors
) {
44 const connectorId
= Utils
.convertToInt(connector
);
45 if (connectorId
> 0) {
46 this.startConnector(connectorId
);
51 private stopConnectors(): void {
52 for (const connector
in this.chargingStation
.connectors
) {
53 const connectorId
= Utils
.convertToInt(connector
);
54 if (connectorId
> 0) {
55 this.stopConnector(connectorId
);
60 private async internalStartConnector(connectorId
: number): Promise
<void> {
61 this.initStartConnectorStatus(connectorId
);
62 logger
.info(this.logPrefix(connectorId
) + ' started on connector and will run for ' + Utils
.formatDurationMilliSeconds(this.connectorsStatus
.get(connectorId
).stopDate
.getTime() - this.connectorsStatus
.get(connectorId
).startDate
.getTime()));
63 while (this.connectorsStatus
.get(connectorId
).start
) {
64 if ((new Date()) > this.connectorsStatus
.get(connectorId
).stopDate
) {
65 this.stopConnector(connectorId
);
68 if (!this.chargingStation
.isRegistered()) {
69 logger
.error(this.logPrefix(connectorId
) + ' entered in transaction loop while the charging station is not registered');
70 this.stopConnector(connectorId
);
73 if (!this.chargingStation
.isChargingStationAvailable()) {
74 logger
.info(this.logPrefix(connectorId
) + ' entered in transaction loop while the charging station is unavailable');
75 this.stopConnector(connectorId
);
78 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
79 logger
.info(`${this.logPrefix(connectorId)} entered in transaction loop while the connector ${connectorId} is unavailable`);
80 this.stopConnector(connectorId
);
83 if (!this.chargingStation
?.ocppRequestService
) {
84 logger
.info(`${this.logPrefix(connectorId)} transaction loop waiting for charging station service to be initialized`);
86 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
87 } while (!this.chargingStation
?.ocppRequestService
);
89 const wait
= Utils
.getRandomInteger(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDelayBetweenTwoTransactions
,
90 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDelayBetweenTwoTransactions
) * 1000;
91 logger
.info(this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
));
92 await Utils
.sleep(wait
);
93 const start
= Utils
.secureRandom();
94 if (start
< this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.probabilityOfStart
) {
95 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
97 const startResponse
= await this.startTransaction(connectorId
);
98 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
99 if (startResponse
?.idTagInfo
?.status !== AuthorizationStatus
.ACCEPTED
) {
100 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
101 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
103 // Wait until end of transaction
104 const waitTrxEnd
= Utils
.getRandomInteger(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDuration
,
105 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDuration
) * 1000;
106 logger
.info(this.logPrefix(connectorId
) + ' transaction ' + this.chargingStation
.getConnector(connectorId
).transactionId
.toString() + ' started and will stop in ' + Utils
.formatDurationMilliSeconds(waitTrxEnd
));
107 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
108 await Utils
.sleep(waitTrxEnd
);
110 logger
.info(this.logPrefix(connectorId
) + ' stop transaction ' + this.chargingStation
.getConnector(connectorId
).transactionId
.toString());
111 await this.stopTransaction(connectorId
);
114 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
115 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
116 logger
.info(this.logPrefix(connectorId
) + ' skipped consecutively ' + this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() + '/' + this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() + ' transaction(s)');
118 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
120 await this.stopTransaction(connectorId
);
121 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
122 logger
.info(this.logPrefix(connectorId
) + ' stopped on connector and lasted for ' + Utils
.formatDurationMilliSeconds(this.connectorsStatus
.get(connectorId
).stoppedDate
.getTime() - this.connectorsStatus
.get(connectorId
).startDate
.getTime()));
123 logger
.debug(`${this.logPrefix(connectorId)} connector status %j`, this.connectorsStatus
.get(connectorId
));
126 private startConnector(connectorId
: number): void {
127 // Avoid hogging the event loop with a busy loop
129 this.internalStartConnector(connectorId
).catch(() => { /* This is intentional */ });
133 private stopConnector(connectorId
: number): void {
134 this.connectorsStatus
.set(connectorId
, { ...this.connectorsStatus
.get(connectorId
), start
: false });
137 private initStartConnectorStatus(connectorId
: number): void {
138 this.connectorsStatus
.get(connectorId
).authorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
139 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
140 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
141 this.connectorsStatus
.get(connectorId
).startTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
142 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
143 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
144 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
145 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
146 this.connectorsStatus
.get(connectorId
).skippedTransactions
= this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
147 const previousRunDuration
= (this?.connectorsStatus
.get(connectorId
)?.startDate
&& this?.connectorsStatus
.get(connectorId
)?.lastRunDate
)
148 ? (this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() - this.connectorsStatus
.get(connectorId
).startDate
.getTime())
150 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
151 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(this.connectorsStatus
.get(connectorId
).startDate
.getTime()
152 + (this.chargingStation
.stationInfo
?.AutomaticTransactionGenerator
?.stopAfterHours
?? Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) * 3600 * 1000
153 - previousRunDuration
);
154 this.connectorsStatus
.get(connectorId
).start
= true;
157 private async startTransaction(connectorId
: number): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
158 const measureId
= 'StartTransaction with ATG';
159 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
160 let startResponse
: StartTransactionResponse
;
161 if (this.chargingStation
.hasAuthorizedTags()) {
162 const idTag
= this.chargingStation
.getRandomIdTag();
163 if (this.chargingStation
.getAutomaticTransactionGeneratorRequireAuthorize()) {
165 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(connectorId
, idTag
);
166 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
167 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
168 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
169 logger
.info(this.logPrefix(connectorId
) + ' start transaction for idTag ' + idTag
);
171 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, idTag
);
172 PerformanceStatistics
.endMeasure(measureId
, beginId
);
173 return startResponse
;
175 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
176 PerformanceStatistics
.endMeasure(measureId
, beginId
);
177 return authorizeResponse
;
179 logger
.info(this.logPrefix(connectorId
) + ' start transaction for idTag ' + idTag
);
181 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, idTag
);
182 PerformanceStatistics
.endMeasure(measureId
, beginId
);
183 return startResponse
;
185 logger
.info(this.logPrefix(connectorId
) + ' start transaction without an idTag');
186 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
);
187 PerformanceStatistics
.endMeasure(measureId
, beginId
);
188 return startResponse
;
191 private async stopTransaction(connectorId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
192 const measureId
= 'StopTransaction with ATG';
193 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
194 let transactionId
= 0;
195 let stopResponse
: StopTransactionResponse
;
196 if (this.chargingStation
.getConnector(connectorId
)?.transactionStarted
) {
197 transactionId
= this.chargingStation
.getConnector(connectorId
).transactionId
;
198 stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
199 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
200 this.chargingStation
.getTransactionIdTag(transactionId
),
202 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
204 logger
.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`);
206 PerformanceStatistics
.endMeasure(measureId
, beginId
);
210 private logPrefix(connectorId
?: number): string {
212 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG on connector #' + connectorId
.toString() + ':');
214 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG:');