refactor: split Utils static methods class into functions
[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 { ChargingStationUtils } 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 (
72 ChargingStationUtils.checkChargingStation(this.chargingStation, this.logPrefix()) === false
73 ) {
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 (
107 ChargingStationUtils.checkChargingStation(
108 this.chargingStation,
109 this.logPrefix(connectorId)
110 ) === false
111 ) {
112 return;
113 }
114 if (this.connectorsStatus.has(connectorId) === false) {
115 logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
116 throw new BaseError(`Connector ${connectorId} does not exist`);
117 }
118 if (this.connectorsStatus.get(connectorId)?.start === false) {
119 this.runInAsyncScope(
120 this.internalStartConnector.bind(this) as (
121 this: AutomaticTransactionGenerator,
122 ...args: any[]
123 ) => Promise<void>,
124 this,
125 connectorId
126 ).catch(Constants.EMPTY_FUNCTION);
127 } else if (this.connectorsStatus.get(connectorId)?.start === true) {
128 logger.warn(`${this.logPrefix(connectorId)} is already started on connector`);
129 }
130 }
131
132 public stopConnector(connectorId: number): void {
133 if (this.connectorsStatus.has(connectorId) === false) {
134 logger.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
135 throw new BaseError(`Connector ${connectorId} does not exist`);
136 }
137 if (this.connectorsStatus.get(connectorId)?.start === true) {
138 this.connectorsStatus.get(connectorId).start = false;
139 } else if (this.connectorsStatus.get(connectorId)?.start === false) {
140 logger.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
141 }
142 }
143
144 private startConnectors(): void {
145 if (
146 this.connectorsStatus?.size > 0 &&
147 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
148 ) {
149 this.connectorsStatus.clear();
150 this.initializeConnectorsStatus();
151 }
152 if (this.chargingStation.hasEvses) {
153 for (const [evseId, evseStatus] of this.chargingStation.evses) {
154 if (evseId > 0) {
155 for (const connectorId of evseStatus.connectors.keys()) {
156 this.startConnector(connectorId);
157 }
158 }
159 }
160 } else {
161 for (const connectorId of this.chargingStation.connectors.keys()) {
162 if (connectorId > 0) {
163 this.startConnector(connectorId);
164 }
165 }
166 }
167 }
168
169 private stopConnectors(): void {
170 if (this.chargingStation.hasEvses) {
171 for (const [evseId, evseStatus] of this.chargingStation.evses) {
172 if (evseId > 0) {
173 for (const connectorId of evseStatus.connectors.keys()) {
174 this.stopConnector(connectorId);
175 }
176 }
177 }
178 } else {
179 for (const connectorId of this.chargingStation.connectors.keys()) {
180 if (connectorId > 0) {
181 this.stopConnector(connectorId);
182 }
183 }
184 }
185 }
186
187 private async internalStartConnector(connectorId: number): Promise<void> {
188 this.setStartConnectorStatus(connectorId);
189 logger.info(
190 `${this.logPrefix(
191 connectorId
192 )} started on connector and will run for ${formatDurationMilliSeconds(
193 this.connectorsStatus.get(connectorId).stopDate.getTime() -
194 this.connectorsStatus.get(connectorId).startDate.getTime()
195 )}`
196 );
197 while (this.connectorsStatus.get(connectorId)?.start === true) {
198 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
199 this.stopConnector(connectorId);
200 break;
201 }
202 if (this.chargingStation.inAcceptedState() === false) {
203 logger.error(
204 `${this.logPrefix(
205 connectorId
206 )} entered in transaction loop while the charging station is not in accepted state`
207 );
208 this.stopConnector(connectorId);
209 break;
210 }
211 if (this.chargingStation.isChargingStationAvailable() === false) {
212 logger.info(
213 `${this.logPrefix(
214 connectorId
215 )} entered in transaction loop while the charging station is unavailable`
216 );
217 this.stopConnector(connectorId);
218 break;
219 }
220 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
221 logger.info(
222 `${this.logPrefix(
223 connectorId
224 )} entered in transaction loop while the connector ${connectorId} is unavailable`
225 );
226 this.stopConnector(connectorId);
227 break;
228 }
229 if (
230 this.chargingStation.getConnectorStatus(connectorId)?.status ===
231 ConnectorStatusEnum.Unavailable
232 ) {
233 logger.info(
234 `${this.logPrefix(
235 connectorId
236 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
237 );
238 this.stopConnector(connectorId);
239 break;
240 }
241 if (!this.chargingStation?.ocppRequestService) {
242 logger.info(
243 `${this.logPrefix(
244 connectorId
245 )} transaction loop waiting for charging station service to be initialized`
246 );
247 do {
248 await sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
249 } while (!this.chargingStation?.ocppRequestService);
250 }
251 const wait =
252 getRandomInteger(
253 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
254 .maxDelayBetweenTwoTransactions,
255 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
256 .minDelayBetweenTwoTransactions
257 ) * 1000;
258 logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
259 await sleep(wait);
260 const start = secureRandom();
261 if (
262 start <
263 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().probabilityOfStart
264 ) {
265 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
266 // Start transaction
267 const startResponse = await this.startTransaction(connectorId);
268 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
269 // Wait until end of transaction
270 const waitTrxEnd =
271 getRandomInteger(
272 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().maxDuration,
273 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().minDuration
274 ) * 1000;
275 logger.info(
276 `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation
277 .getConnectorStatus(connectorId)
278 ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds(
279 waitTrxEnd
280 )}`
281 );
282 await sleep(waitTrxEnd);
283 // Stop transaction
284 logger.info(
285 `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation
286 .getConnectorStatus(connectorId)
287 ?.transactionId?.toString()}`
288 );
289 await this.stopTransaction(connectorId);
290 }
291 } else {
292 ++this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions;
293 ++this.connectorsStatus.get(connectorId).skippedTransactions;
294 logger.info(
295 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
296 .get(connectorId)
297 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
298 .get(connectorId)
299 ?.skippedTransactions?.toString()} transaction(s)`
300 );
301 }
302 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
303 }
304 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
305 logger.info(
306 `${this.logPrefix(
307 connectorId
308 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
309 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
310 this.connectorsStatus.get(connectorId).startDate.getTime()
311 )}`
312 );
313 logger.debug(
314 `${this.logPrefix(connectorId)} connector status: %j`,
315 this.connectorsStatus.get(connectorId)
316 );
317 }
318
319 private setStartConnectorStatus(connectorId: number): void {
320 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
321 const previousRunDuration =
322 this.connectorsStatus.get(connectorId)?.startDate &&
323 this.connectorsStatus.get(connectorId)?.lastRunDate
324 ? this.connectorsStatus.get(connectorId).lastRunDate.getTime() -
325 this.connectorsStatus.get(connectorId).startDate.getTime()
326 : 0;
327 this.connectorsStatus.get(connectorId).startDate = new Date();
328 this.connectorsStatus.get(connectorId).stopDate = new Date(
329 this.connectorsStatus.get(connectorId).startDate.getTime() +
330 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().stopAfterHours *
331 3600 *
332 1000 -
333 previousRunDuration
334 );
335 this.connectorsStatus.get(connectorId).start = 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 = cloneObject(
358 this.chargingStation.getAutomaticTransactionGeneratorStatuses()
359 )[connectorId];
360 delete connectorStatus?.startDate;
361 delete connectorStatus?.lastRunDate;
362 delete connectorStatus?.stopDate;
363 delete connectorStatus?.stoppedDate;
364 return (
365 connectorStatus ?? {
366 start: false,
367 authorizeRequests: 0,
368 acceptedAuthorizeRequests: 0,
369 rejectedAuthorizeRequests: 0,
370 startTransactionRequests: 0,
371 acceptedStartTransactionRequests: 0,
372 rejectedStartTransactionRequests: 0,
373 stopTransactionRequests: 0,
374 acceptedStopTransactionRequests: 0,
375 rejectedStopTransactionRequests: 0,
376 skippedConsecutiveTransactions: 0,
377 skippedTransactions: 0,
378 }
379 );
380 }
381
382 private async startTransaction(
383 connectorId: number
384 ): Promise<StartTransactionResponse | undefined> {
385 const measureId = 'StartTransaction with ATG';
386 const beginId = PerformanceStatistics.beginMeasure(measureId);
387 let startResponse: StartTransactionResponse;
388 if (this.chargingStation.hasIdTags()) {
389 const idTag = IdTagsCache.getInstance().getIdTag(
390 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution,
391 this.chargingStation,
392 connectorId
393 );
394 const startTransactionLogMsg = `${this.logPrefix(
395 connectorId
396 )} start transaction with an idTag '${idTag}'`;
397 if (this.getRequireAuthorize()) {
398 this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
399 // Authorize idTag
400 const authorizeResponse: AuthorizeResponse =
401 await this.chargingStation.ocppRequestService.requestHandler<
402 AuthorizeRequest,
403 AuthorizeResponse
404 >(this.chargingStation, RequestCommand.AUTHORIZE, {
405 idTag,
406 });
407 ++this.connectorsStatus.get(connectorId).authorizeRequests;
408 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
409 ++this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests;
410 logger.info(startTransactionLogMsg);
411 // Start transaction
412 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
413 StartTransactionRequest,
414 StartTransactionResponse
415 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
416 connectorId,
417 idTag,
418 });
419 this.handleStartTransactionResponse(connectorId, startResponse);
420 PerformanceStatistics.endMeasure(measureId, beginId);
421 return startResponse;
422 }
423 ++this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests;
424 PerformanceStatistics.endMeasure(measureId, beginId);
425 return startResponse;
426 }
427 logger.info(startTransactionLogMsg);
428 // Start transaction
429 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
430 StartTransactionRequest,
431 StartTransactionResponse
432 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
433 connectorId,
434 idTag,
435 });
436 this.handleStartTransactionResponse(connectorId, startResponse);
437 PerformanceStatistics.endMeasure(measureId, beginId);
438 return startResponse;
439 }
440 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
441 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
442 StartTransactionRequest,
443 StartTransactionResponse
444 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
445 this.handleStartTransactionResponse(connectorId, startResponse);
446 PerformanceStatistics.endMeasure(measureId, beginId);
447 return startResponse;
448 }
449
450 private async stopTransaction(
451 connectorId: number,
452 reason: StopTransactionReason = StopTransactionReason.LOCAL
453 ): Promise<StopTransactionResponse> {
454 const measureId = 'StopTransaction with ATG';
455 const beginId = PerformanceStatistics.beginMeasure(measureId);
456 let stopResponse: StopTransactionResponse;
457 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
458 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
459 ++this.connectorsStatus.get(connectorId).stopTransactionRequests;
460 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
461 ++this.connectorsStatus.get(connectorId).acceptedStopTransactionRequests;
462 } else {
463 ++this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests;
464 }
465 } else {
466 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
467 logger.warn(
468 `${this.logPrefix(connectorId)} stopping a not started transaction${
469 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : ''
470 }`
471 );
472 }
473 PerformanceStatistics.endMeasure(measureId, beginId);
474 return stopResponse;
475 }
476
477 private getRequireAuthorize(): boolean {
478 return (
479 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
480 );
481 }
482
483 private logPrefix = (connectorId?: number): string => {
484 return logPrefix(
485 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
486 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}` : ''
487 }:`
488 );
489 };
490
491 private handleStartTransactionResponse(
492 connectorId: number,
493 startResponse: StartTransactionResponse
494 ): void {
495 ++this.connectorsStatus.get(connectorId).startTransactionRequests;
496 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
497 ++this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests;
498 } else {
499 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
500 ++this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests;
501 }
502 }
503 }