perf: remove AsyncResource usage
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { hoursToMilliseconds, secondsToMilliseconds } from 'date-fns';
4
5 import type { ChargingStation } from './ChargingStation';
6 import { checkChargingStation } from './Helpers';
7 import { IdTagsCache } from './IdTagsCache';
8 import { isIdTagAuthorized } from './ocpp';
9 import { BaseError } from '../exception';
10 import { PerformanceStatistics } from '../performance';
11 import {
12 AuthorizationStatus,
13 RequestCommand,
14 type StartTransactionRequest,
15 type StartTransactionResponse,
16 type Status,
17 StopTransactionReason,
18 type StopTransactionResponse,
19 } from '../types';
20 import {
21 Constants,
22 cloneObject,
23 formatDurationMilliSeconds,
24 getRandomInteger,
25 isNullOrUndefined,
26 logPrefix,
27 logger,
28 secureRandom,
29 sleep,
30 } from '../utils';
31
32 export class AutomaticTransactionGenerator {
33 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
34 string,
35 AutomaticTransactionGenerator
36 >();
37
38 public readonly connectorsStatus: Map<number, Status>;
39 public started: boolean;
40 private starting: boolean;
41 private stopping: boolean;
42 private readonly chargingStation: ChargingStation;
43
44 private constructor(chargingStation: ChargingStation) {
45 this.started = false;
46 this.starting = false;
47 this.stopping = false;
48 this.chargingStation = chargingStation;
49 this.connectorsStatus = new Map<number, Status>();
50 this.initializeConnectorsStatus();
51 }
52
53 public static getInstance(
54 chargingStation: ChargingStation,
55 ): AutomaticTransactionGenerator | undefined {
56 if (AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId) === false) {
57 AutomaticTransactionGenerator.instances.set(
58 chargingStation.stationInfo.hashId,
59 new AutomaticTransactionGenerator(chargingStation),
60 );
61 }
62 return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId);
63 }
64
65 public start(): void {
66 if (checkChargingStation(this.chargingStation, this.logPrefix()) === false) {
67 return;
68 }
69 if (this.started === true) {
70 logger.warn(`${this.logPrefix()} is already started`);
71 return;
72 }
73 if (this.starting === true) {
74 logger.warn(`${this.logPrefix()} is already starting`);
75 return;
76 }
77 this.starting = true;
78 this.startConnectors();
79 this.started = true;
80 this.starting = false;
81 }
82
83 public stop(): void {
84 if (this.started === false) {
85 logger.warn(`${this.logPrefix()} is already stopped`);
86 return;
87 }
88 if (this.stopping === true) {
89 logger.warn(`${this.logPrefix()} is already stopping`);
90 return;
91 }
92 this.stopping = true;
93 this.stopConnectors();
94 this.started = false;
95 this.stopping = false;
96 }
97
98 public startConnector(connectorId: number): void {
99 if (checkChargingStation(this.chargingStation, this.logPrefix(connectorId)) === false) {
100 return;
101 }
102 if (this.connectorsStatus.has(connectorId) === false) {
103 logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
104 throw new BaseError(`Connector ${connectorId} does not exist`);
105 }
106 if (this.connectorsStatus.get(connectorId)?.start === false) {
107 this.internalStartConnector(connectorId).catch(Constants.EMPTY_FUNCTION);
108 } else if (this.connectorsStatus.get(connectorId)?.start === true) {
109 logger.warn(`${this.logPrefix(connectorId)} is already started on connector`);
110 }
111 }
112
113 public stopConnector(connectorId: number): void {
114 if (this.connectorsStatus.has(connectorId) === false) {
115 logger.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
116 throw new BaseError(`Connector ${connectorId} does not exist`);
117 }
118 if (this.connectorsStatus.get(connectorId)?.start === true) {
119 this.connectorsStatus.get(connectorId)!.start = false;
120 } else if (this.connectorsStatus.get(connectorId)?.start === false) {
121 logger.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
122 }
123 }
124
125 private startConnectors(): void {
126 if (
127 this.connectorsStatus?.size > 0 &&
128 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
129 ) {
130 this.connectorsStatus.clear();
131 this.initializeConnectorsStatus();
132 }
133 if (this.chargingStation.hasEvses) {
134 for (const [evseId, evseStatus] of this.chargingStation.evses) {
135 if (evseId > 0) {
136 for (const connectorId of evseStatus.connectors.keys()) {
137 this.startConnector(connectorId);
138 }
139 }
140 }
141 } else {
142 for (const connectorId of this.chargingStation.connectors.keys()) {
143 if (connectorId > 0) {
144 this.startConnector(connectorId);
145 }
146 }
147 }
148 }
149
150 private stopConnectors(): void {
151 if (this.chargingStation.hasEvses) {
152 for (const [evseId, evseStatus] of this.chargingStation.evses) {
153 if (evseId > 0) {
154 for (const connectorId of evseStatus.connectors.keys()) {
155 this.stopConnector(connectorId);
156 }
157 }
158 }
159 } else {
160 for (const connectorId of this.chargingStation.connectors.keys()) {
161 if (connectorId > 0) {
162 this.stopConnector(connectorId);
163 }
164 }
165 }
166 }
167
168 private async internalStartConnector(connectorId: number): Promise<void> {
169 this.setStartConnectorStatus(connectorId);
170 logger.info(
171 `${this.logPrefix(
172 connectorId,
173 )} started on connector and will run for ${formatDurationMilliSeconds(
174 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
175 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
176 )}`,
177 );
178 while (this.connectorsStatus.get(connectorId)?.start === true) {
179 await this.waitChargingStationServiceInitialization(connectorId);
180 await this.waitChargingStationAvailable(connectorId);
181 await this.waitConnectorAvailable(connectorId);
182 if (!this.canStartConnector(connectorId)) {
183 this.stopConnector(connectorId);
184 break;
185 }
186 const wait = secondsToMilliseconds(
187 getRandomInteger(
188 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
189 .maxDelayBetweenTwoTransactions,
190 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
191 .minDelayBetweenTwoTransactions,
192 ),
193 );
194 logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
195 await sleep(wait);
196 const start = secureRandom();
197 if (
198 start <
199 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
200 ) {
201 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0;
202 // Start transaction
203 const startResponse = await this.startTransaction(connectorId);
204 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
205 // Wait until end of transaction
206 const waitTrxEnd = secondsToMilliseconds(
207 getRandomInteger(
208 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().maxDuration,
209 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().minDuration,
210 ),
211 );
212 logger.info(
213 `${this.logPrefix(
214 connectorId,
215 )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId)
216 ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`,
217 );
218 await sleep(waitTrxEnd);
219 await this.stopTransaction(connectorId);
220 }
221 } else {
222 ++this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions!;
223 ++this.connectorsStatus.get(connectorId)!.skippedTransactions!;
224 logger.info(
225 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
226 connectorId,
227 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
228 ?.skippedTransactions} transaction(s)`,
229 );
230 }
231 this.connectorsStatus.get(connectorId)!.lastRunDate = new Date();
232 }
233 this.connectorsStatus.get(connectorId)!.stoppedDate = new Date();
234 logger.info(
235 `${this.logPrefix(
236 connectorId,
237 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
238 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
239 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
240 )}`,
241 );
242 logger.debug(
243 `${this.logPrefix(connectorId)} connector status: %j`,
244 this.connectorsStatus.get(connectorId),
245 );
246 }
247
248 private setStartConnectorStatus(connectorId: number): void {
249 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0;
250 const previousRunDuration =
251 this.connectorsStatus.get(connectorId)?.startDate &&
252 this.connectorsStatus.get(connectorId)?.lastRunDate
253 ? this.connectorsStatus.get(connectorId)!.lastRunDate!.getTime() -
254 this.connectorsStatus.get(connectorId)!.startDate!.getTime()
255 : 0;
256 this.connectorsStatus.get(connectorId)!.startDate = new Date();
257 this.connectorsStatus.get(connectorId)!.stopDate = new Date(
258 this.connectorsStatus.get(connectorId)!.startDate!.getTime() +
259 hoursToMilliseconds(
260 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().stopAfterHours,
261 ) -
262 previousRunDuration,
263 );
264 this.connectorsStatus.get(connectorId)!.start = true;
265 }
266
267 private canStartConnector(connectorId: number): boolean {
268 if (new Date() > this.connectorsStatus.get(connectorId)!.stopDate!) {
269 return false;
270 }
271 if (this.chargingStation.inAcceptedState() === false) {
272 logger.error(
273 `${this.logPrefix(
274 connectorId,
275 )} entered in transaction loop while the charging station is not in accepted state`,
276 );
277 return false;
278 }
279 if (this.chargingStation.isChargingStationAvailable() === false) {
280 logger.info(
281 `${this.logPrefix(
282 connectorId,
283 )} entered in transaction loop while the charging station is unavailable`,
284 );
285 return false;
286 }
287 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
288 logger.info(
289 `${this.logPrefix(
290 connectorId,
291 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
292 );
293 return false;
294 }
295 return true;
296 }
297
298 private async waitChargingStationServiceInitialization(connectorId: number): Promise<void> {
299 let logged = false;
300 while (!this.chargingStation?.ocppRequestService) {
301 if (!logged) {
302 logger.info(
303 `${this.logPrefix(
304 connectorId,
305 )} transaction loop waiting for charging station service to be initialized`,
306 );
307 logged = true;
308 }
309 await sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
310 }
311 }
312
313 private async waitChargingStationAvailable(connectorId: number): Promise<void> {
314 let logged = false;
315 while (!this.chargingStation.isChargingStationAvailable()) {
316 if (!logged) {
317 logger.info(
318 `${this.logPrefix(
319 connectorId,
320 )} transaction loop waiting for charging station to be available`,
321 );
322 logged = true;
323 }
324 await sleep(Constants.CHARGING_STATION_ATG_AVAILABILITY_TIME);
325 }
326 }
327
328 private async waitConnectorAvailable(connectorId: number): Promise<void> {
329 let logged = false;
330 while (!this.chargingStation.isConnectorAvailable(connectorId)) {
331 if (!logged) {
332 logger.info(
333 `${this.logPrefix(
334 connectorId,
335 )} transaction loop waiting for connector ${connectorId} to be available`,
336 );
337 logged = true;
338 }
339 await sleep(Constants.CHARGING_STATION_ATG_AVAILABILITY_TIME);
340 }
341 }
342
343 private initializeConnectorsStatus(): void {
344 if (this.chargingStation.hasEvses) {
345 for (const [evseId, evseStatus] of this.chargingStation.evses) {
346 if (evseId > 0) {
347 for (const connectorId of evseStatus.connectors.keys()) {
348 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
349 }
350 }
351 }
352 } else {
353 for (const connectorId of this.chargingStation.connectors.keys()) {
354 if (connectorId > 0) {
355 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
356 }
357 }
358 }
359 }
360
361 private getConnectorStatus(connectorId: number): Status {
362 const connectorStatus = this.chargingStation.getAutomaticTransactionGeneratorStatuses()?.[
363 connectorId
364 ]
365 ? cloneObject<Status>(
366 this.chargingStation.getAutomaticTransactionGeneratorStatuses()![connectorId],
367 )
368 : undefined;
369 this.resetConnectorStatus(connectorStatus);
370 return (
371 connectorStatus ?? {
372 start: false,
373 authorizeRequests: 0,
374 acceptedAuthorizeRequests: 0,
375 rejectedAuthorizeRequests: 0,
376 startTransactionRequests: 0,
377 acceptedStartTransactionRequests: 0,
378 rejectedStartTransactionRequests: 0,
379 stopTransactionRequests: 0,
380 acceptedStopTransactionRequests: 0,
381 rejectedStopTransactionRequests: 0,
382 skippedConsecutiveTransactions: 0,
383 skippedTransactions: 0,
384 }
385 );
386 }
387
388 private resetConnectorStatus(connectorStatus: Status | undefined): void {
389 if (connectorStatus === undefined) {
390 return;
391 }
392 delete connectorStatus?.startDate;
393 delete connectorStatus?.lastRunDate;
394 delete connectorStatus?.stopDate;
395 delete connectorStatus?.stoppedDate;
396 if (
397 !this.started &&
398 (connectorStatus.start === true ||
399 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().enable === false)
400 ) {
401 connectorStatus.start = false;
402 }
403 }
404
405 private async startTransaction(
406 connectorId: number,
407 ): Promise<StartTransactionResponse | undefined> {
408 const measureId = 'StartTransaction with ATG';
409 const beginId = PerformanceStatistics.beginMeasure(measureId);
410 let startResponse: StartTransactionResponse | undefined;
411 if (this.chargingStation.hasIdTags()) {
412 const idTag = IdTagsCache.getInstance().getIdTag(
413 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().idTagDistribution!,
414 this.chargingStation,
415 connectorId,
416 );
417 const startTransactionLogMsg = `${this.logPrefix(
418 connectorId,
419 )} start transaction with an idTag '${idTag}'`;
420 if (this.getRequireAuthorize()) {
421 ++this.connectorsStatus.get(connectorId)!.authorizeRequests!;
422 if (await isIdTagAuthorized(this.chargingStation, connectorId, idTag)) {
423 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests!;
424 logger.info(startTransactionLogMsg);
425 // Start transaction
426 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
427 StartTransactionRequest,
428 StartTransactionResponse
429 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
430 connectorId,
431 idTag,
432 });
433 this.handleStartTransactionResponse(connectorId, startResponse);
434 PerformanceStatistics.endMeasure(measureId, beginId);
435 return startResponse;
436 }
437 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests!;
438 PerformanceStatistics.endMeasure(measureId, beginId);
439 return startResponse;
440 }
441 logger.info(startTransactionLogMsg);
442 // Start transaction
443 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
444 StartTransactionRequest,
445 StartTransactionResponse
446 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
447 connectorId,
448 idTag,
449 });
450 this.handleStartTransactionResponse(connectorId, startResponse);
451 PerformanceStatistics.endMeasure(measureId, beginId);
452 return startResponse;
453 }
454 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
455 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
456 StartTransactionRequest,
457 StartTransactionResponse
458 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
459 this.handleStartTransactionResponse(connectorId, startResponse);
460 PerformanceStatistics.endMeasure(measureId, beginId);
461 return startResponse;
462 }
463
464 private async stopTransaction(
465 connectorId: number,
466 reason = StopTransactionReason.LOCAL,
467 ): Promise<StopTransactionResponse | undefined> {
468 const measureId = 'StopTransaction with ATG';
469 const beginId = PerformanceStatistics.beginMeasure(measureId);
470 let stopResponse: StopTransactionResponse | undefined;
471 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
472 logger.info(
473 `${this.logPrefix(
474 connectorId,
475 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
476 ?.transactionId}`,
477 );
478 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
479 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests!;
480 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
481 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests!;
482 } else {
483 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests!;
484 }
485 } else {
486 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
487 logger.debug(
488 `${this.logPrefix(connectorId)} stopping a not started transaction${
489 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}` : ''
490 }`,
491 );
492 }
493 PerformanceStatistics.endMeasure(measureId, beginId);
494 return stopResponse;
495 }
496
497 private getRequireAuthorize(): boolean {
498 return (
499 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
500 );
501 }
502
503 private logPrefix = (connectorId?: number): string => {
504 return logPrefix(
505 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
506 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}` : ''
507 }:`,
508 );
509 };
510
511 private handleStartTransactionResponse(
512 connectorId: number,
513 startResponse: StartTransactionResponse,
514 ): void {
515 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests!;
516 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
517 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests!;
518 } else {
519 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
520 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests!;
521 }
522 }
523 }