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