Apply prettier formating
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import {
4 AuthorizationStatus,
5 AuthorizeResponse,
6 StartTransactionResponse,
7 StopTransactionReason,
8 StopTransactionResponse,
9 } from '../types/ocpp/Transaction';
10
11 import type ChargingStation from './ChargingStation';
12 import Constants from '../utils/Constants';
13 import PerformanceStatistics from '../performance/PerformanceStatistics';
14 import { Status } from '../types/AutomaticTransactionGenerator';
15 import Utils from '../utils/Utils';
16 import logger from '../utils/Logger';
17
18 export default class AutomaticTransactionGenerator {
19 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
20 string,
21 AutomaticTransactionGenerator
22 >();
23 public started: boolean;
24 private readonly chargingStation: ChargingStation;
25 private readonly connectorsStatus: Map<number, Status>;
26
27 private constructor(chargingStation: ChargingStation) {
28 this.chargingStation = chargingStation;
29 this.connectorsStatus = new Map<number, Status>();
30 this.stopConnectors();
31 this.started = false;
32 }
33
34 public static getInstance(chargingStation: ChargingStation): AutomaticTransactionGenerator {
35 if (!AutomaticTransactionGenerator.instances.has(chargingStation.id)) {
36 AutomaticTransactionGenerator.instances.set(
37 chargingStation.id,
38 new AutomaticTransactionGenerator(chargingStation)
39 );
40 }
41 return AutomaticTransactionGenerator.instances.get(chargingStation.id);
42 }
43
44 public start(): void {
45 if (this.started) {
46 logger.error(`${this.logPrefix()} trying to start while already started`);
47 return;
48 }
49 this.startConnectors();
50 this.started = true;
51 }
52
53 public stop(): void {
54 if (!this.started) {
55 logger.error(`${this.logPrefix()} trying to stop while not started`);
56 return;
57 }
58 this.stopConnectors();
59 this.started = false;
60 }
61
62 private startConnectors(): void {
63 if (
64 this.connectorsStatus?.size > 0 &&
65 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
66 ) {
67 this.connectorsStatus.clear();
68 }
69 for (const connectorId of this.chargingStation.connectors.keys()) {
70 if (connectorId > 0) {
71 this.startConnector(connectorId);
72 }
73 }
74 }
75
76 private stopConnectors(): void {
77 for (const connectorId of this.chargingStation.connectors.keys()) {
78 if (connectorId > 0) {
79 this.stopConnector(connectorId);
80 }
81 }
82 }
83
84 private async internalStartConnector(connectorId: number): Promise<void> {
85 this.initStartConnectorStatus(connectorId);
86 logger.info(
87 this.logPrefix(connectorId) +
88 ' started on connector and will run for ' +
89 Utils.formatDurationMilliSeconds(
90 this.connectorsStatus.get(connectorId).stopDate.getTime() -
91 this.connectorsStatus.get(connectorId).startDate.getTime()
92 )
93 );
94 while (this.connectorsStatus.get(connectorId).start) {
95 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
96 this.stopConnector(connectorId);
97 break;
98 }
99 if (!this.chargingStation.isInAcceptedState()) {
100 logger.error(
101 this.logPrefix(connectorId) +
102 ' entered in transaction loop while the charging station is not in accepted state'
103 );
104 this.stopConnector(connectorId);
105 break;
106 }
107 if (!this.chargingStation.isChargingStationAvailable()) {
108 logger.info(
109 this.logPrefix(connectorId) +
110 ' entered in transaction loop while the charging station is unavailable'
111 );
112 this.stopConnector(connectorId);
113 break;
114 }
115 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
116 logger.info(
117 `${this.logPrefix(
118 connectorId
119 )} entered in transaction loop while the connector ${connectorId} is unavailable`
120 );
121 this.stopConnector(connectorId);
122 break;
123 }
124 if (!this.chargingStation?.ocppRequestService) {
125 logger.info(
126 `${this.logPrefix(
127 connectorId
128 )} transaction loop waiting for charging station service to be initialized`
129 );
130 do {
131 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
132 } while (!this.chargingStation?.ocppRequestService);
133 }
134 const wait =
135 Utils.getRandomInteger(
136 this.chargingStation.stationInfo.AutomaticTransactionGenerator
137 .maxDelayBetweenTwoTransactions,
138 this.chargingStation.stationInfo.AutomaticTransactionGenerator
139 .minDelayBetweenTwoTransactions
140 ) * 1000;
141 logger.info(
142 this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)
143 );
144 await Utils.sleep(wait);
145 const start = Utils.secureRandom();
146 if (
147 start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart
148 ) {
149 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
150 // Start transaction
151 const startResponse = await this.startTransaction(connectorId);
152 this.connectorsStatus.get(connectorId).startTransactionRequests++;
153 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
154 logger.warn(this.logPrefix(connectorId) + ' start transaction rejected');
155 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
156 } else {
157 // Wait until end of transaction
158 const waitTrxEnd =
159 Utils.getRandomInteger(
160 this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
161 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration
162 ) * 1000;
163 logger.info(
164 this.logPrefix(connectorId) +
165 ' transaction ' +
166 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() +
167 ' started and will stop in ' +
168 Utils.formatDurationMilliSeconds(waitTrxEnd)
169 );
170 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
171 await Utils.sleep(waitTrxEnd);
172 // Stop transaction
173 logger.info(
174 this.logPrefix(connectorId) +
175 ' stop transaction ' +
176 this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()
177 );
178 await this.stopTransaction(connectorId);
179 }
180 } else {
181 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
182 this.connectorsStatus.get(connectorId).skippedTransactions++;
183 logger.info(
184 this.logPrefix(connectorId) +
185 ' skipped consecutively ' +
186 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() +
187 '/' +
188 this.connectorsStatus.get(connectorId).skippedTransactions.toString() +
189 ' transaction(s)'
190 );
191 }
192 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
193 }
194 await this.stopTransaction(connectorId);
195 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
196 logger.info(
197 this.logPrefix(connectorId) +
198 ' stopped on connector and lasted for ' +
199 Utils.formatDurationMilliSeconds(
200 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
201 this.connectorsStatus.get(connectorId).startDate.getTime()
202 )
203 );
204 logger.debug(
205 `${this.logPrefix(connectorId)} connector status %j`,
206 this.connectorsStatus.get(connectorId)
207 );
208 }
209
210 private startConnector(connectorId: number): void {
211 // Avoid hogging the event loop with a busy loop
212 setImmediate(() => {
213 this.internalStartConnector(connectorId).catch(() => {
214 /* This is intentional */
215 });
216 });
217 }
218
219 private stopConnector(connectorId: number): void {
220 this.connectorsStatus.set(connectorId, {
221 ...this.connectorsStatus.get(connectorId),
222 start: false,
223 });
224 }
225
226 private initStartConnectorStatus(connectorId: number): void {
227 this.connectorsStatus.get(connectorId).authorizeRequests =
228 this?.connectorsStatus.get(connectorId)?.authorizeRequests ?? 0;
229 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests =
230 this?.connectorsStatus.get(connectorId)?.acceptedAuthorizeRequests ?? 0;
231 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests =
232 this?.connectorsStatus.get(connectorId)?.rejectedAuthorizeRequests ?? 0;
233 this.connectorsStatus.get(connectorId).startTransactionRequests =
234 this?.connectorsStatus.get(connectorId)?.startTransactionRequests ?? 0;
235 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests =
236 this?.connectorsStatus.get(connectorId)?.acceptedStartTransactionRequests ?? 0;
237 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests =
238 this?.connectorsStatus.get(connectorId)?.rejectedStartTransactionRequests ?? 0;
239 this.connectorsStatus.get(connectorId).stopTransactionRequests =
240 this?.connectorsStatus.get(connectorId)?.stopTransactionRequests ?? 0;
241 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
242 this.connectorsStatus.get(connectorId).skippedTransactions =
243 this?.connectorsStatus.get(connectorId)?.skippedTransactions ?? 0;
244 const previousRunDuration =
245 this?.connectorsStatus.get(connectorId)?.startDate &&
246 this?.connectorsStatus.get(connectorId)?.lastRunDate
247 ? this.connectorsStatus.get(connectorId).lastRunDate.getTime() -
248 this.connectorsStatus.get(connectorId).startDate.getTime()
249 : 0;
250 this.connectorsStatus.get(connectorId).startDate = new Date();
251 this.connectorsStatus.get(connectorId).stopDate = new Date(
252 this.connectorsStatus.get(connectorId).startDate.getTime() +
253 (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ??
254 Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
255 3600 *
256 1000 -
257 previousRunDuration
258 );
259 this.connectorsStatus.get(connectorId).start = true;
260 }
261
262 private async startTransaction(
263 connectorId: number
264 ): Promise<StartTransactionResponse | AuthorizeResponse> {
265 const measureId = 'StartTransaction with ATG';
266 const beginId = PerformanceStatistics.beginMeasure(measureId);
267 let startResponse: StartTransactionResponse;
268 if (this.chargingStation.hasAuthorizedTags()) {
269 const idTag = this.chargingStation.getRandomIdTag();
270 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
271 // Authorize idTag
272 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(
273 connectorId,
274 idTag
275 );
276 this.connectorsStatus.get(connectorId).authorizeRequests++;
277 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
278 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
279 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
280 // Start transaction
281 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(
282 connectorId,
283 idTag
284 );
285 PerformanceStatistics.endMeasure(measureId, beginId);
286 return startResponse;
287 }
288 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
289 PerformanceStatistics.endMeasure(measureId, beginId);
290 return authorizeResponse;
291 }
292 logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag);
293 // Start transaction
294 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(
295 connectorId,
296 idTag
297 );
298 PerformanceStatistics.endMeasure(measureId, beginId);
299 return startResponse;
300 }
301 logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag');
302 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
303 PerformanceStatistics.endMeasure(measureId, beginId);
304 return startResponse;
305 }
306
307 private async stopTransaction(
308 connectorId: number,
309 reason: StopTransactionReason = StopTransactionReason.NONE
310 ): Promise<StopTransactionResponse> {
311 const measureId = 'StopTransaction with ATG';
312 const beginId = PerformanceStatistics.beginMeasure(measureId);
313 let transactionId = 0;
314 let stopResponse: StopTransactionResponse;
315 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
316 transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
317 stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(
318 transactionId,
319 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
320 this.chargingStation.getTransactionIdTag(transactionId),
321 reason
322 );
323 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
324 } else {
325 logger.warn(
326 `${this.logPrefix(connectorId)} trying to stop a not started transaction${
327 transactionId ? ' ' + transactionId.toString() : ''
328 }`
329 );
330 }
331 PerformanceStatistics.endMeasure(measureId, beginId);
332 return stopResponse;
333 }
334
335 private logPrefix(connectorId?: number): string {
336 if (connectorId) {
337 return Utils.logPrefix(
338 ' ' +
339 this.chargingStation.stationInfo.chargingStationId +
340 ' | ATG on connector #' +
341 connectorId.toString() +
342 ':'
343 );
344 }
345 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
346 }
347 }