fix: fix reservation removal at transaction start
[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 { 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 // Authorize idTag
401 const authorizeResponse: AuthorizeResponse =
402 await this.chargingStation.ocppRequestService.requestHandler<
403 AuthorizeRequest,
404 AuthorizeResponse
405 >(this.chargingStation, RequestCommand.AUTHORIZE, {
406 idTag,
407 });
408 ++this.connectorsStatus.get(connectorId)!.authorizeRequests!;
409 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
410 if (
411 isNullOrUndefined(this.chargingStation.getConnectorStatus(connectorId)!.authorizeIdTag)
412 ) {
413 logger.warn(
414 `${this.chargingStation.logPrefix()} IdTag ${idTag} is not set as authorized remotely, applying deferred initialization`,
415 );
416 this.chargingStation.getConnectorStatus(connectorId)!.authorizeIdTag = idTag;
417 }
418 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests!;
419 logger.info(startTransactionLogMsg);
420 // Start transaction
421 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
422 StartTransactionRequest,
423 StartTransactionResponse
424 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
425 connectorId,
426 idTag,
427 });
428 this.handleStartTransactionResponse(connectorId, startResponse);
429 PerformanceStatistics.endMeasure(measureId, beginId);
430 return startResponse;
431 }
432 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests!;
433 PerformanceStatistics.endMeasure(measureId, beginId);
434 return startResponse;
435 }
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 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
450 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
451 StartTransactionRequest,
452 StartTransactionResponse
453 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
454 this.handleStartTransactionResponse(connectorId, startResponse);
455 PerformanceStatistics.endMeasure(measureId, beginId);
456 return startResponse;
457 }
458
459 private async stopTransaction(
460 connectorId: number,
461 reason: StopTransactionReason = StopTransactionReason.LOCAL,
462 ): Promise<StopTransactionResponse | undefined> {
463 const measureId = 'StopTransaction with ATG';
464 const beginId = PerformanceStatistics.beginMeasure(measureId);
465 let stopResponse: StopTransactionResponse | undefined;
466 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
467 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
468 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests!;
469 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
470 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests!;
471 } else {
472 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests!;
473 }
474 } else {
475 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
476 logger.warn(
477 `${this.logPrefix(connectorId)} stopping a not started transaction${
478 !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : ''
479 }`,
480 );
481 }
482 PerformanceStatistics.endMeasure(measureId, beginId);
483 return stopResponse;
484 }
485
486 private getRequireAuthorize(): boolean {
487 return (
488 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
489 );
490 }
491
492 private logPrefix = (connectorId?: number): string => {
493 return logPrefix(
494 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
495 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId!.toString()}` : ''
496 }:`,
497 );
498 };
499
500 private handleStartTransactionResponse(
501 connectorId: number,
502 startResponse: StartTransactionResponse,
503 ): void {
504 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests!;
505 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
506 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests!;
507 } else {
508 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
509 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests!;
510 }
511 }
512 }