fix: make ATG wait for CS/connector availability
[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 if (!this.chargingStation?.ocppRequestService) {
324 logger.info(
325 `${this.logPrefix(
326 connectorId,
327 )} transaction loop waiting for charging station service to be initialized`,
328 );
329 do {
330 await sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
331 } while (!this.chargingStation?.ocppRequestService);
332 }
333 }
334
335 private async waitChargingStationAvailable(connectorId: number): Promise<void> {
336 if (!this.chargingStation.isChargingStationAvailable()) {
337 logger.info(
338 `${this.logPrefix(
339 connectorId,
340 )} transaction loop waiting for charging station to be available`,
341 );
342 do {
343 await sleep(Constants.CHARGING_STATION_ATG_AVAILABILITY_TIME);
344 } while (!this.chargingStation.isChargingStationAvailable());
345 }
346 }
347
348 private async waitConnectorAvailable(connectorId: number): Promise<void> {
349 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
350 logger.info(
351 `${this.logPrefix(
352 connectorId,
353 )} transaction loop waiting for connector ${connectorId} to be available`,
354 );
355 do {
356 await sleep(Constants.CHARGING_STATION_ATG_AVAILABILITY_TIME);
357 } while (!this.chargingStation.isConnectorAvailable(connectorId));
358 }
359 }
360
361 private initializeConnectorsStatus(): void {
362 if (this.chargingStation.hasEvses) {
363 for (const [evseId, evseStatus] of this.chargingStation.evses) {
364 if (evseId > 0) {
365 for (const connectorId of evseStatus.connectors.keys()) {
366 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
367 }
368 }
369 }
370 } else {
371 for (const connectorId of this.chargingStation.connectors.keys()) {
372 if (connectorId > 0) {
373 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
374 }
375 }
376 }
377 }
378
379 private getConnectorStatus(connectorId: number): Status {
380 const connectorStatus = this.chargingStation.getAutomaticTransactionGeneratorStatuses()?.[
381 connectorId
382 ]
383 ? cloneObject<Status>(
384 this.chargingStation.getAutomaticTransactionGeneratorStatuses()![connectorId],
385 )
386 : undefined;
387 this.resetConnectorStatus(connectorStatus);
388 return (
389 connectorStatus ?? {
390 start: false,
391 authorizeRequests: 0,
392 acceptedAuthorizeRequests: 0,
393 rejectedAuthorizeRequests: 0,
394 startTransactionRequests: 0,
395 acceptedStartTransactionRequests: 0,
396 rejectedStartTransactionRequests: 0,
397 stopTransactionRequests: 0,
398 acceptedStopTransactionRequests: 0,
399 rejectedStopTransactionRequests: 0,
400 skippedConsecutiveTransactions: 0,
401 skippedTransactions: 0,
402 }
403 );
404 }
405
406 private resetConnectorStatus(connectorStatus: Status | undefined): void {
407 delete connectorStatus?.startDate;
408 delete connectorStatus?.lastRunDate;
409 delete connectorStatus?.stopDate;
410 delete connectorStatus?.stoppedDate;
411 if (
412 !this.started &&
413 (connectorStatus?.start === true ||
414 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().enable === false)
415 ) {
416 connectorStatus!.start = false;
417 }
418 }
419
420 private async startTransaction(
421 connectorId: number,
422 ): Promise<StartTransactionResponse | undefined> {
423 const measureId = 'StartTransaction with ATG';
424 const beginId = PerformanceStatistics.beginMeasure(measureId);
425 let startResponse: StartTransactionResponse | undefined;
426 if (this.chargingStation.hasIdTags()) {
427 const idTag = IdTagsCache.getInstance().getIdTag(
428 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().idTagDistribution!,
429 this.chargingStation,
430 connectorId,
431 );
432 const startTransactionLogMsg = `${this.logPrefix(
433 connectorId,
434 )} start transaction with an idTag '${idTag}'`;
435 if (this.getRequireAuthorize()) {
436 ++this.connectorsStatus.get(connectorId)!.authorizeRequests!;
437 if (await OCPPServiceUtils.isIdTagAuthorized(this.chargingStation, connectorId, idTag)) {
438 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests!;
439 logger.info(startTransactionLogMsg);
440 // Start transaction
441 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
442 StartTransactionRequest,
443 StartTransactionResponse
444 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
445 connectorId,
446 idTag,
447 });
448 this.handleStartTransactionResponse(connectorId, startResponse);
449 PerformanceStatistics.endMeasure(measureId, beginId);
450 return startResponse;
451 }
452 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests!;
453 PerformanceStatistics.endMeasure(measureId, beginId);
454 return startResponse;
455 }
456 logger.info(startTransactionLogMsg);
457 // Start transaction
458 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
459 StartTransactionRequest,
460 StartTransactionResponse
461 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
462 connectorId,
463 idTag,
464 });
465 this.handleStartTransactionResponse(connectorId, startResponse);
466 PerformanceStatistics.endMeasure(measureId, beginId);
467 return startResponse;
468 }
469 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
470 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
471 StartTransactionRequest,
472 StartTransactionResponse
473 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
474 this.handleStartTransactionResponse(connectorId, startResponse);
475 PerformanceStatistics.endMeasure(measureId, beginId);
476 return startResponse;
477 }
478
479 private async stopTransaction(
480 connectorId: number,
481 reason = StopTransactionReason.LOCAL,
482 ): Promise<StopTransactionResponse | undefined> {
483 const measureId = 'StopTransaction with ATG';
484 const beginId = PerformanceStatistics.beginMeasure(measureId);
485 let stopResponse: StopTransactionResponse | undefined;
486 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
487 logger.info(
488 `${this.logPrefix(
489 connectorId,
490 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
491 ?.transactionId}`,
492 );
493 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
494 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests!;
495 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
496 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests!;
497 } else {
498 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests!;
499 }
500 } else {
501 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
502 logger.debug(
503 `${this.logPrefix(connectorId)} stopping a not started transaction${
504 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}` : ''
505 }`,
506 );
507 }
508 PerformanceStatistics.endMeasure(measureId, beginId);
509 return stopResponse;
510 }
511
512 private getRequireAuthorize(): boolean {
513 return (
514 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
515 );
516 }
517
518 private logPrefix = (connectorId?: number): string => {
519 return logPrefix(
520 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
521 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}` : ''
522 }:`,
523 );
524 };
525
526 private handleStartTransactionResponse(
527 connectorId: number,
528 startResponse: StartTransactionResponse,
529 ): void {
530 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests!;
531 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
532 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests!;
533 } else {
534 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
535 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests!;
536 }
537 }
538 }