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 connectorId
of this.chargingStation
.connectors
.keys()) {
44 if (connectorId
> 0) {
45 this.startConnector(connectorId
);
50 private stopConnectors(): void {
51 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
52 if (connectorId
> 0) {
53 this.stopConnector(connectorId
);
58 private async internalStartConnector(connectorId
: number): Promise
<void> {
59 this.initStartConnectorStatus(connectorId
);
60 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()));
61 while (this.connectorsStatus
.get(connectorId
).start
) {
62 if ((new Date()) > this.connectorsStatus
.get(connectorId
).stopDate
) {
63 this.stopConnector(connectorId
);
66 if (!this.chargingStation
.isRegistered()) {
67 logger
.error(this.logPrefix(connectorId
) + ' entered in transaction loop while the charging station is not registered');
68 this.stopConnector(connectorId
);
71 if (!this.chargingStation
.isChargingStationAvailable()) {
72 logger
.info(this.logPrefix(connectorId
) + ' entered in transaction loop while the charging station is unavailable');
73 this.stopConnector(connectorId
);
76 if (!this.chargingStation
.isConnectorAvailable(connectorId
)) {
77 logger
.info(`${this.logPrefix(connectorId)} entered in transaction loop while the connector ${connectorId} is unavailable`);
78 this.stopConnector(connectorId
);
81 if (!this.chargingStation
?.ocppRequestService
) {
82 logger
.info(`${this.logPrefix(connectorId)} transaction loop waiting for charging station service to be initialized`);
84 await Utils
.sleep(Constants
.CHARGING_STATION_ATG_INITIALIZATION_TIME
);
85 } while (!this.chargingStation
?.ocppRequestService
);
87 const wait
= Utils
.getRandomInteger(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDelayBetweenTwoTransactions
,
88 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDelayBetweenTwoTransactions
) * 1000;
89 logger
.info(this.logPrefix(connectorId
) + ' waiting for ' + Utils
.formatDurationMilliSeconds(wait
));
90 await Utils
.sleep(wait
);
91 const start
= Utils
.secureRandom();
92 if (start
< this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.probabilityOfStart
) {
93 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
95 const startResponse
= await this.startTransaction(connectorId
);
96 this.connectorsStatus
.get(connectorId
).startTransactionRequests
++;
97 if (startResponse
?.idTagInfo
?.status !== AuthorizationStatus
.ACCEPTED
) {
98 logger
.warn(this.logPrefix(connectorId
) + ' start transaction rejected');
99 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
++;
101 // Wait until end of transaction
102 const waitTrxEnd
= Utils
.getRandomInteger(this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.maxDuration
,
103 this.chargingStation
.stationInfo
.AutomaticTransactionGenerator
.minDuration
) * 1000;
104 logger
.info(this.logPrefix(connectorId
) + ' transaction ' + this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString() + ' started and will stop in ' + Utils
.formatDurationMilliSeconds(waitTrxEnd
));
105 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
++;
106 await Utils
.sleep(waitTrxEnd
);
108 logger
.info(this.logPrefix(connectorId
) + ' stop transaction ' + this.chargingStation
.getConnectorStatus(connectorId
).transactionId
.toString());
109 await this.stopTransaction(connectorId
);
112 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
++;
113 this.connectorsStatus
.get(connectorId
).skippedTransactions
++;
114 logger
.info(this.logPrefix(connectorId
) + ' skipped consecutively ' + this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
.toString() + '/' + this.connectorsStatus
.get(connectorId
).skippedTransactions
.toString() + ' transaction(s)');
116 this.connectorsStatus
.get(connectorId
).lastRunDate
= new Date();
118 await this.stopTransaction(connectorId
);
119 this.connectorsStatus
.get(connectorId
).stoppedDate
= new Date();
120 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()));
121 logger
.debug(`${this.logPrefix(connectorId)} connector status %j`, this.connectorsStatus
.get(connectorId
));
124 private startConnector(connectorId
: number): void {
125 // Avoid hogging the event loop with a busy loop
127 this.internalStartConnector(connectorId
).catch(() => { /* This is intentional */ });
131 private stopConnector(connectorId
: number): void {
132 this.connectorsStatus
.set(connectorId
, { ...this.connectorsStatus
.get(connectorId
), start
: false });
135 private initStartConnectorStatus(connectorId
: number): void {
136 this.connectorsStatus
.get(connectorId
).authorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.authorizeRequests
?? 0;
137 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.acceptedAuthorizeRequests
?? 0;
138 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
= this?.connectorsStatus
.get(connectorId
)?.rejectedAuthorizeRequests
?? 0;
139 this.connectorsStatus
.get(connectorId
).startTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.startTransactionRequests
?? 0;
140 this.connectorsStatus
.get(connectorId
).acceptedStartTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.acceptedStartTransactionRequests
?? 0;
141 this.connectorsStatus
.get(connectorId
).rejectedStartTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.rejectedStartTransactionRequests
?? 0;
142 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
= this?.connectorsStatus
.get(connectorId
)?.stopTransactionRequests
?? 0;
143 this.connectorsStatus
.get(connectorId
).skippedConsecutiveTransactions
= 0;
144 this.connectorsStatus
.get(connectorId
).skippedTransactions
= this?.connectorsStatus
.get(connectorId
)?.skippedTransactions
?? 0;
145 const previousRunDuration
= (this?.connectorsStatus
.get(connectorId
)?.startDate
&& this?.connectorsStatus
.get(connectorId
)?.lastRunDate
)
146 ? (this.connectorsStatus
.get(connectorId
).lastRunDate
.getTime() - this.connectorsStatus
.get(connectorId
).startDate
.getTime())
148 this.connectorsStatus
.get(connectorId
).startDate
= new Date();
149 this.connectorsStatus
.get(connectorId
).stopDate
= new Date(this.connectorsStatus
.get(connectorId
).startDate
.getTime()
150 + (this.chargingStation
.stationInfo
?.AutomaticTransactionGenerator
?.stopAfterHours
?? Constants
.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS
) * 3600 * 1000
151 - previousRunDuration
);
152 this.connectorsStatus
.get(connectorId
).start
= true;
155 private async startTransaction(connectorId
: number): Promise
<StartTransactionResponse
| AuthorizeResponse
> {
156 const measureId
= 'StartTransaction with ATG';
157 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
158 let startResponse
: StartTransactionResponse
;
159 if (this.chargingStation
.hasAuthorizedTags()) {
160 const idTag
= this.chargingStation
.getRandomIdTag();
161 if (this.chargingStation
.getAutomaticTransactionGeneratorRequireAuthorize()) {
163 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(connectorId
, idTag
);
164 this.connectorsStatus
.get(connectorId
).authorizeRequests
++;
165 if (authorizeResponse
?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
166 this.connectorsStatus
.get(connectorId
).acceptedAuthorizeRequests
++;
167 logger
.info(this.logPrefix(connectorId
) + ' start transaction for idTag ' + idTag
);
169 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, idTag
);
170 PerformanceStatistics
.endMeasure(measureId
, beginId
);
171 return startResponse
;
173 this.connectorsStatus
.get(connectorId
).rejectedAuthorizeRequests
++;
174 PerformanceStatistics
.endMeasure(measureId
, beginId
);
175 return authorizeResponse
;
177 logger
.info(this.logPrefix(connectorId
) + ' start transaction for idTag ' + idTag
);
179 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
, idTag
);
180 PerformanceStatistics
.endMeasure(measureId
, beginId
);
181 return startResponse
;
183 logger
.info(this.logPrefix(connectorId
) + ' start transaction without an idTag');
184 startResponse
= await this.chargingStation
.ocppRequestService
.sendStartTransaction(connectorId
);
185 PerformanceStatistics
.endMeasure(measureId
, beginId
);
186 return startResponse
;
189 private async stopTransaction(connectorId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
190 const measureId
= 'StopTransaction with ATG';
191 const beginId
= PerformanceStatistics
.beginMeasure(measureId
);
192 let transactionId
= 0;
193 let stopResponse
: StopTransactionResponse
;
194 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
195 transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
196 stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
197 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
198 this.chargingStation
.getTransactionIdTag(transactionId
),
200 this.connectorsStatus
.get(connectorId
).stopTransactionRequests
++;
202 logger
.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`);
204 PerformanceStatistics
.endMeasure(measureId
, beginId
);
208 private logPrefix(connectorId
?: number): string {
210 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG on connector #' + connectorId
.toString() + ':');
212 return Utils
.logPrefix(' ' + this.chargingStation
.stationInfo
.chargingStationId
+ ' | ATG:');