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