fix: only reset defined ATG connector status
[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 if (connectorStatus === undefined) {
402 return;
403 }
404 delete connectorStatus?.startDate;
405 delete connectorStatus?.lastRunDate;
406 delete connectorStatus?.stopDate;
407 delete connectorStatus?.stoppedDate;
408 if (
409 !this.started &&
410 (connectorStatus.start === true ||
411 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().enable === false)
412 ) {
413 connectorStatus.start = false;
414 }
415 }
416
417 private async startTransaction(
418 connectorId: number,
419 ): Promise<StartTransactionResponse | undefined> {
420 const measureId = 'StartTransaction with ATG';
421 const beginId = PerformanceStatistics.beginMeasure(measureId);
422 let startResponse: StartTransactionResponse | undefined;
423 if (this.chargingStation.hasIdTags()) {
424 const idTag = IdTagsCache.getInstance().getIdTag(
425 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().idTagDistribution!,
426 this.chargingStation,
427 connectorId,
428 );
429 const startTransactionLogMsg = `${this.logPrefix(
430 connectorId,
431 )} start transaction with an idTag '${idTag}'`;
432 if (this.getRequireAuthorize()) {
433 ++this.connectorsStatus.get(connectorId)!.authorizeRequests!;
434 if (await OCPPServiceUtils.isIdTagAuthorized(this.chargingStation, connectorId, idTag)) {
435 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests!;
436 logger.info(startTransactionLogMsg);
437 // Start transaction
438 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
439 StartTransactionRequest,
440 StartTransactionResponse
441 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
442 connectorId,
443 idTag,
444 });
445 this.handleStartTransactionResponse(connectorId, startResponse);
446 PerformanceStatistics.endMeasure(measureId, beginId);
447 return startResponse;
448 }
449 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests!;
450 PerformanceStatistics.endMeasure(measureId, beginId);
451 return startResponse;
452 }
453 logger.info(startTransactionLogMsg);
454 // Start transaction
455 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
456 StartTransactionRequest,
457 StartTransactionResponse
458 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
459 connectorId,
460 idTag,
461 });
462 this.handleStartTransactionResponse(connectorId, startResponse);
463 PerformanceStatistics.endMeasure(measureId, beginId);
464 return startResponse;
465 }
466 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
467 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
468 StartTransactionRequest,
469 StartTransactionResponse
470 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
471 this.handleStartTransactionResponse(connectorId, startResponse);
472 PerformanceStatistics.endMeasure(measureId, beginId);
473 return startResponse;
474 }
475
476 private async stopTransaction(
477 connectorId: number,
478 reason = StopTransactionReason.LOCAL,
479 ): Promise<StopTransactionResponse | undefined> {
480 const measureId = 'StopTransaction with ATG';
481 const beginId = PerformanceStatistics.beginMeasure(measureId);
482 let stopResponse: StopTransactionResponse | undefined;
483 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
484 logger.info(
485 `${this.logPrefix(
486 connectorId,
487 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
488 ?.transactionId}`,
489 );
490 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
491 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests!;
492 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
493 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests!;
494 } else {
495 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests!;
496 }
497 } else {
498 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
499 logger.debug(
500 `${this.logPrefix(connectorId)} stopping a not started transaction${
501 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}` : ''
502 }`,
503 );
504 }
505 PerformanceStatistics.endMeasure(measureId, beginId);
506 return stopResponse;
507 }
508
509 private getRequireAuthorize(): boolean {
510 return (
511 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
512 );
513 }
514
515 private logPrefix = (connectorId?: number): string => {
516 return logPrefix(
517 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
518 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}` : ''
519 }:`,
520 );
521 };
522
523 private handleStartTransactionResponse(
524 connectorId: number,
525 startResponse: StartTransactionResponse,
526 ): void {
527 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests!;
528 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
529 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests!;
530 } else {
531 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
532 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests!;
533 }
534 }
535 }