build(deps-dev): apply updates
[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 type { ChargingStation } from './ChargingStation';
6 import { checkChargingStation } from './ChargingStationUtils';
7 import { IdTagsCache } from './IdTagsCache';
8 import { BaseError } from '../exception';
9 import { PerformanceStatistics } from '../performance';
10 import {
11 AuthorizationStatus,
12 type AuthorizeRequest,
13 type AuthorizeResponse,
14 ConnectorStatusEnum,
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 if (new Date() > this.connectorsStatus.get(connectorId)!.stopDate!) {
192 this.stopConnector(connectorId);
193 break;
194 }
195 if (this.chargingStation.inAcceptedState() === false) {
196 logger.error(
197 `${this.logPrefix(
198 connectorId,
199 )} entered in transaction loop while the charging station is not in accepted state`,
200 );
201 this.stopConnector(connectorId);
202 break;
203 }
204 if (this.chargingStation.isChargingStationAvailable() === false) {
205 logger.info(
206 `${this.logPrefix(
207 connectorId,
208 )} entered in transaction loop while the charging station is unavailable`,
209 );
210 this.stopConnector(connectorId);
211 break;
212 }
213 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
214 logger.info(
215 `${this.logPrefix(
216 connectorId,
217 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
218 );
219 this.stopConnector(connectorId);
220 break;
221 }
222 if (
223 this.chargingStation.getConnectorStatus(connectorId)?.status ===
224 ConnectorStatusEnum.Unavailable
225 ) {
226 logger.info(
227 `${this.logPrefix(
228 connectorId,
229 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
230 );
231 this.stopConnector(connectorId);
232 break;
233 }
234 if (!this.chargingStation?.ocppRequestService) {
235 logger.info(
236 `${this.logPrefix(
237 connectorId,
238 )} transaction loop waiting for charging station service to be initialized`,
239 );
240 do {
241 await sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
242 } while (!this.chargingStation?.ocppRequestService);
243 }
244 const wait =
245 getRandomInteger(
246 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
247 .maxDelayBetweenTwoTransactions,
248 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
249 .minDelayBetweenTwoTransactions,
250 ) * 1000;
251 logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
252 await sleep(wait);
253 const start = secureRandom();
254 if (
255 start <
256 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
257 ) {
258 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0;
259 // Start transaction
260 const startResponse = await this.startTransaction(connectorId);
261 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
262 // Wait until end of transaction
263 const waitTrxEnd =
264 getRandomInteger(
265 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().maxDuration,
266 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().minDuration,
267 ) * 1000;
268 logger.info(
269 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
270 .getConnectorStatus(connectorId)
271 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
272 waitTrxEnd,
273 )}`,
274 );
275 await sleep(waitTrxEnd);
276 // Stop transaction
277 logger.info(
278 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
279 .getConnectorStatus(connectorId)
280 ?.transactionId?.toString()}`,
281 );
282 await this.stopTransaction(connectorId);
283 }
284 } else {
285 ++this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions!;
286 ++this.connectorsStatus.get(connectorId)!.skippedTransactions!;
287 logger.info(
288 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
289 .get(connectorId)
290 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
291 .get(connectorId)
292 ?.skippedTransactions?.toString()} transaction(s)`,
293 );
294 }
295 this.connectorsStatus.get(connectorId)!.lastRunDate = new Date();
296 }
297 this.connectorsStatus.get(connectorId)!.stoppedDate = new Date();
298 logger.info(
299 `${this.logPrefix(
300 connectorId,
301 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
302 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
303 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
304 )}`,
305 );
306 logger.debug(
307 `${this.logPrefix(connectorId)} connector status: %j`,
308 this.connectorsStatus.get(connectorId),
309 );
310 }
311
312 private setStartConnectorStatus(connectorId: number): void {
313 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0;
314 const previousRunDuration =
315 this.connectorsStatus.get(connectorId)?.startDate &&
316 this.connectorsStatus.get(connectorId)?.lastRunDate
317 ? this.connectorsStatus.get(connectorId)!.lastRunDate!.getTime() -
318 this.connectorsStatus.get(connectorId)!.startDate!.getTime()
319 : 0;
320 this.connectorsStatus.get(connectorId)!.startDate = new Date();
321 this.connectorsStatus.get(connectorId)!.stopDate = new Date(
322 this.connectorsStatus.get(connectorId)!.startDate!.getTime() +
323 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().stopAfterHours *
324 3600 *
325 1000 -
326 previousRunDuration,
327 );
328 this.connectorsStatus.get(connectorId)!.start = true;
329 }
330
331 private initializeConnectorsStatus(): void {
332 if (this.chargingStation.hasEvses) {
333 for (const [evseId, evseStatus] of this.chargingStation.evses) {
334 if (evseId > 0) {
335 for (const connectorId of evseStatus.connectors.keys()) {
336 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
337 }
338 }
339 }
340 } else {
341 for (const connectorId of this.chargingStation.connectors.keys()) {
342 if (connectorId > 0) {
343 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
344 }
345 }
346 }
347 }
348
349 private getConnectorStatus(connectorId: number): Status {
350 const connectorStatus = cloneObject(
351 this.chargingStation.getAutomaticTransactionGeneratorStatuses()!,
352 )[connectorId];
353 delete connectorStatus?.startDate;
354 delete connectorStatus?.lastRunDate;
355 delete connectorStatus?.stopDate;
356 delete connectorStatus?.stoppedDate;
357 return (
358 connectorStatus ?? {
359 start: false,
360 authorizeRequests: 0,
361 acceptedAuthorizeRequests: 0,
362 rejectedAuthorizeRequests: 0,
363 startTransactionRequests: 0,
364 acceptedStartTransactionRequests: 0,
365 rejectedStartTransactionRequests: 0,
366 stopTransactionRequests: 0,
367 acceptedStopTransactionRequests: 0,
368 rejectedStopTransactionRequests: 0,
369 skippedConsecutiveTransactions: 0,
370 skippedTransactions: 0,
371 }
372 );
373 }
374
375 private async startTransaction(
376 connectorId: number,
377 ): Promise<StartTransactionResponse | undefined> {
378 const measureId = 'StartTransaction with ATG';
379 const beginId = PerformanceStatistics.beginMeasure(measureId);
380 let startResponse: StartTransactionResponse | undefined;
381 if (this.chargingStation.hasIdTags()) {
382 const idTag = IdTagsCache.getInstance().getIdTag(
383 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().idTagDistribution!,
384 this.chargingStation,
385 connectorId,
386 );
387 const startTransactionLogMsg = `${this.logPrefix(
388 connectorId,
389 )} start transaction with an idTag '${idTag}'`;
390 if (this.getRequireAuthorize()) {
391 this.chargingStation.getConnectorStatus(connectorId)!.authorizeIdTag = idTag;
392 // Authorize idTag
393 const authorizeResponse: AuthorizeResponse =
394 await this.chargingStation.ocppRequestService.requestHandler<
395 AuthorizeRequest,
396 AuthorizeResponse
397 >(this.chargingStation, RequestCommand.AUTHORIZE, {
398 idTag,
399 });
400 ++this.connectorsStatus.get(connectorId)!.authorizeRequests!;
401 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
402 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests!;
403 logger.info(startTransactionLogMsg);
404 // Start transaction
405 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
406 StartTransactionRequest,
407 StartTransactionResponse
408 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
409 connectorId,
410 idTag,
411 });
412 this.handleStartTransactionResponse(connectorId, startResponse);
413 PerformanceStatistics.endMeasure(measureId, beginId);
414 return startResponse;
415 }
416 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests!;
417 PerformanceStatistics.endMeasure(measureId, beginId);
418 return startResponse;
419 }
420 logger.info(startTransactionLogMsg);
421 // Start transaction
422 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
423 StartTransactionRequest,
424 StartTransactionResponse
425 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
426 connectorId,
427 idTag,
428 });
429 this.handleStartTransactionResponse(connectorId, startResponse);
430 PerformanceStatistics.endMeasure(measureId, beginId);
431 return startResponse;
432 }
433 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
434 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
435 StartTransactionRequest,
436 StartTransactionResponse
437 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
438 this.handleStartTransactionResponse(connectorId, startResponse);
439 PerformanceStatistics.endMeasure(measureId, beginId);
440 return startResponse;
441 }
442
443 private async stopTransaction(
444 connectorId: number,
445 reason: StopTransactionReason = StopTransactionReason.LOCAL,
446 ): Promise<StopTransactionResponse | undefined> {
447 const measureId = 'StopTransaction with ATG';
448 const beginId = PerformanceStatistics.beginMeasure(measureId);
449 let stopResponse: StopTransactionResponse | undefined;
450 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
451 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
452 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests!;
453 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
454 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests!;
455 } else {
456 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests!;
457 }
458 } else {
459 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
460 logger.warn(
461 `${this.logPrefix(connectorId)} stopping a not started transaction${
462 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : ''
463 }`,
464 );
465 }
466 PerformanceStatistics.endMeasure(measureId, beginId);
467 return stopResponse;
468 }
469
470 private getRequireAuthorize(): boolean {
471 return (
472 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
473 );
474 }
475
476 private logPrefix = (connectorId?: number): string => {
477 return logPrefix(
478 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
479 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId!.toString()}` : ''
480 }:`,
481 );
482 };
483
484 private handleStartTransactionResponse(
485 connectorId: number,
486 startResponse: StartTransactionResponse,
487 ): void {
488 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests!;
489 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
490 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests!;
491 } else {
492 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
493 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests!;
494 }
495 }
496 }