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 readonly chargingStation
: ChargingStation
;
15 private readonly 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 if (this.connectorsStatus
?.size
> 0 && this.connectorsStatus
.size
!== this.chargingStation
.getNumberOfConnectors()) {
44 this.connectorsStatus
.clear();
46 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
47 if (connectorId
> 0) {
48 this.startConnector(connectorId
);
53 private stopConnectors(): void {
54 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
55 if (connectorId
> 0) {
56 this.stopConnector(connectorId
);
61 private async internalStartConnector(connectorId
: number): Promise
<void> {
62 this.initStartConnectorStatus(connectorId
);
63 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()));
64 while (this.connectorsStatus
.get(connectorId
).start
) {
65 if ((new Date()) > this.connectorsStatus
.get(connectorId
).stopDate
) {
66 this.stopConnector(connectorId
);
69 if (!this.chargingStation
.isInAcceptedState()) {
70 logger
.error(this.logPrefix(connectorId
) + ' entered in transaction loop while the charging station is not in accepted state');
71 this.stopConnector(connectorId
);
74 if (!this.chargingStation
.isChargingStationAvailable()) {
75 logger
.info(this.logPrefix(connectorId
) + ' entered in transaction loop while the charging station is unavailable');
76 this.stopConnector(connectorId
);
79 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
80 logger
.info(`${this.logPrefix(connectorId)} entered in transaction loop while the connector ${connectorId} is unavailable`);
81 this.stopConnector(connectorId
);
84 if (!this.chargingStation
?.ocppRequestService
) {
85 logger
.info(`${this.logPrefix(connectorId)} transaction loop waiting for charging station service to be initialized`);
87 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
88 } while (!this.chargingStation
?.ocppRequestService
);
90 const wait
= Utils
.getRandomInteger(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDelayBetweenTwoTransactions
,
91 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDelayBetweenTwoTransactions
) * 1000;
92 logger
.info(this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
));
93 await Utils
.sleep(wait
);
94 const start
= Utils
.secureRandom();
95 if (start
< this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.probabilityOfStart
) {
96 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
98 const startResponse
= await this.startTransaction(connectorId
);
99 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
100 if (startResponse
?.idTagInfo
?.status !== AuthorizationStatus
.ACCEPTED
) {
101 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
102 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
104 // Wait until end of transaction
105 const waitTrxEnd
= Utils
.getRandomInteger(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDuration
,
106 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDuration
) * 1000;
107 logger
.info(this.logPrefix(connectorId
) + ' transaction ' + this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() + ' started and will stop in ' + Utils
.formatDurationMilliSeconds(waitTrxEnd
));
108 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
109 await Utils
.sleep(waitTrxEnd
);
111 logger
.info(this.logPrefix(connectorId
) + ' stop transaction ' + this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString());
112 await this.stopTransaction(connectorId
);
115 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
116 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
117 logger
.info(this.logPrefix(connectorId
) + ' skipped consecutively ' + this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() + '/' + this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() + ' transaction(s)');
119 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
121 await this.stopTransaction(connectorId
);
122 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
123 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()));
124 logger
.debug(`${this.logPrefix(connectorId)} connector status %j`, this.connectorsStatus
.get(connectorId
));
127 private startConnector(connectorId
: number): void {
128 // Avoid hogging the event loop with a busy loop
130 this.internalStartConnector(connectorId
).catch(() => { /* This is intentional */ });
134 private stopConnector(connectorId
: number): void {
135 this.connectorsStatus
.set(connectorId
, { ...this.connectorsStatus
.get(connectorId
), start
: false });
138 private initStartConnectorStatus(connectorId
: number): void {
139 this.connectorsStatus
.get(connectorId
).authorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
140 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
141 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
142 this.connectorsStatus
.get(connectorId
).startTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
143 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
144 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
145 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
146 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
147 this.connectorsStatus
.get(connectorId
).skippedTransactions
= this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
148 const previousRunDuration
= (this?.connectorsStatus
.get(connectorId
)?.startDate
&& this?.connectorsStatus
.get(connectorId
)?.lastRunDate
)
149 ? (this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() - this.connectorsStatus
.get(connectorId
).startDate
.getTime())
151 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
152 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(this.connectorsStatus
.get(connectorId
).startDate
.getTime()
153 + (this.chargingStation
.stationInfo
?.AutomaticTransactionGenerator
?.stopAfterHours
?? Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) * 3600 * 1000
154 - previousRunDuration
);
155 this.connectorsStatus
.get(connectorId
).start
= true;
158 private async startTransaction(connectorId
: number): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
159 const measureId
= 'StartTransaction with ATG';
160 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
161 let startResponse
: StartTransactionResponse
;
162 if (this.chargingStation
.hasAuthorizedTags()) {
163 const idTag
= this.chargingStation
.getRandomIdTag();
164 if (this.chargingStation
.getAutomaticTransactionGeneratorRequireAuthorize()) {
166 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(connectorId
, idTag
);
167 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
168 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
169 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
170 logger
.info(this.logPrefix(connectorId
) + ' start transaction for idTag ' + idTag
);
172 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, idTag
);
173 PerformanceStatistics
.endMeasure(measureId
, beginId
);
174 return startResponse
;
176 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
177 PerformanceStatistics
.endMeasure(measureId
, beginId
);
178 return authorizeResponse
;
180 logger
.info(this.logPrefix(connectorId
) + ' start transaction for idTag ' + idTag
);
182 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, idTag
);
183 PerformanceStatistics
.endMeasure(measureId
, beginId
);
184 return startResponse
;
186 logger
.info(this.logPrefix(connectorId
) + ' start transaction without an idTag');
187 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
);
188 PerformanceStatistics
.endMeasure(measureId
, beginId
);
189 return startResponse
;
192 private async stopTransaction(connectorId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
193 const measureId
= 'StopTransaction with ATG';
194 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
195 let transactionId
= 0;
196 let stopResponse
: StopTransactionResponse
;
197 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
198 transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
199 stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
200 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
201 this.chargingStation
.getTransactionIdTag(transactionId
),
203 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
205 logger
.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`);
207 PerformanceStatistics
.endMeasure(measureId
, beginId
);
211 private logPrefix(connectorId
?: number): string {
213 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG on connector #' + connectorId
.toString() + ':');
215 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG:');