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