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