fix: ensure running transactions are stopped at CS stop
[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 await this.stopTransaction(connectorId);
240 }
241 } else {
242 ++this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions!;
243 ++this.connectorsStatus.get(connectorId)!.skippedTransactions!;
244 logger.info(
245 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
246 connectorId,
247 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
248 ?.skippedTransactions} transaction(s)`,
249 );
250 }
251 this.connectorsStatus.get(connectorId)!.lastRunDate = new Date();
252 }
253 this.connectorsStatus.get(connectorId)!.stoppedDate = new Date();
254 logger.info(
255 `${this.logPrefix(
256 connectorId,
257 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
258 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
259 this.connectorsStatus.get(connectorId)!.startDate!.getTime(),
260 )}`,
261 );
262 logger.debug(
263 `${this.logPrefix(connectorId)} connector status: %j`,
264 this.connectorsStatus.get(connectorId),
265 );
266 }
267
268 private setStartConnectorStatus(connectorId: number): void {
269 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0;
270 const previousRunDuration =
271 this.connectorsStatus.get(connectorId)?.startDate &&
272 this.connectorsStatus.get(connectorId)?.lastRunDate
273 ? this.connectorsStatus.get(connectorId)!.lastRunDate!.getTime() -
274 this.connectorsStatus.get(connectorId)!.startDate!.getTime()
275 : 0;
276 this.connectorsStatus.get(connectorId)!.startDate = new Date();
277 this.connectorsStatus.get(connectorId)!.stopDate = new Date(
278 this.connectorsStatus.get(connectorId)!.startDate!.getTime() +
279 hoursToMilliseconds(
280 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().stopAfterHours,
281 ) -
282 previousRunDuration,
283 );
284 this.connectorsStatus.get(connectorId)!.start = true;
285 }
286
287 private canStartConnector(connectorId: number): boolean {
288 if (new Date() > this.connectorsStatus.get(connectorId)!.stopDate!) {
289 return false;
290 }
291 if (this.chargingStation.inAcceptedState() === false) {
292 logger.error(
293 `${this.logPrefix(
294 connectorId,
295 )} entered in transaction loop while the charging station is not in accepted state`,
296 );
297 return false;
298 }
299 if (this.chargingStation.isChargingStationAvailable() === false) {
300 logger.info(
301 `${this.logPrefix(
302 connectorId,
303 )} entered in transaction loop while the charging station is unavailable`,
304 );
305 return false;
306 }
307 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
308 logger.info(
309 `${this.logPrefix(
310 connectorId,
311 )} entered in transaction loop while the connector ${connectorId} is unavailable`,
312 );
313 return false;
314 }
315 if (
316 this.chargingStation.getConnectorStatus(connectorId)?.status ===
317 ConnectorStatusEnum.Unavailable
318 ) {
319 logger.info(
320 `${this.logPrefix(
321 connectorId,
322 )} entered in transaction loop while the connector ${connectorId} status is unavailable`,
323 );
324 return false;
325 }
326 return true;
327 }
328
329 private initializeConnectorsStatus(): void {
330 if (this.chargingStation.hasEvses) {
331 for (const [evseId, evseStatus] of this.chargingStation.evses) {
332 if (evseId > 0) {
333 for (const connectorId of evseStatus.connectors.keys()) {
334 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
335 }
336 }
337 }
338 } else {
339 for (const connectorId of this.chargingStation.connectors.keys()) {
340 if (connectorId > 0) {
341 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId));
342 }
343 }
344 }
345 }
346
347 private getConnectorStatus(connectorId: number): Status {
348 const connectorStatus = this.chargingStation.getAutomaticTransactionGeneratorStatuses()?.[
349 connectorId
350 ]
351 ? cloneObject<Status>(
352 this.chargingStation.getAutomaticTransactionGeneratorStatuses()![connectorId],
353 )
354 : undefined;
355 delete connectorStatus?.startDate;
356 delete connectorStatus?.lastRunDate;
357 delete connectorStatus?.stopDate;
358 delete connectorStatus?.stoppedDate;
359 if (!this.started && connectorStatus?.start === true) {
360 connectorStatus.start = false;
361 }
362 return (
363 connectorStatus ?? {
364 start: false,
365 authorizeRequests: 0,
366 acceptedAuthorizeRequests: 0,
367 rejectedAuthorizeRequests: 0,
368 startTransactionRequests: 0,
369 acceptedStartTransactionRequests: 0,
370 rejectedStartTransactionRequests: 0,
371 stopTransactionRequests: 0,
372 acceptedStopTransactionRequests: 0,
373 rejectedStopTransactionRequests: 0,
374 skippedConsecutiveTransactions: 0,
375 skippedTransactions: 0,
376 }
377 );
378 }
379
380 private async startTransaction(
381 connectorId: number,
382 ): Promise<StartTransactionResponse | undefined> {
383 const measureId = 'StartTransaction with ATG';
384 const beginId = PerformanceStatistics.beginMeasure(measureId);
385 let startResponse: StartTransactionResponse | undefined;
386 if (this.chargingStation.hasIdTags()) {
387 const idTag = IdTagsCache.getInstance().getIdTag(
388 this.chargingStation.getAutomaticTransactionGeneratorConfiguration().idTagDistribution!,
389 this.chargingStation,
390 connectorId,
391 );
392 const startTransactionLogMsg = `${this.logPrefix(
393 connectorId,
394 )} start transaction with an idTag '${idTag}'`;
395 if (this.getRequireAuthorize()) {
396 ++this.connectorsStatus.get(connectorId)!.authorizeRequests!;
397 if (await OCPPServiceUtils.isIdTagAuthorized(this.chargingStation, connectorId, idTag)) {
398 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests!;
399 logger.info(startTransactionLogMsg);
400 // Start transaction
401 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
402 StartTransactionRequest,
403 StartTransactionResponse
404 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
405 connectorId,
406 idTag,
407 });
408 this.handleStartTransactionResponse(connectorId, startResponse);
409 PerformanceStatistics.endMeasure(measureId, beginId);
410 return startResponse;
411 }
412 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests!;
413 PerformanceStatistics.endMeasure(measureId, beginId);
414 return startResponse;
415 }
416 logger.info(startTransactionLogMsg);
417 // Start transaction
418 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
419 StartTransactionRequest,
420 StartTransactionResponse
421 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
422 connectorId,
423 idTag,
424 });
425 this.handleStartTransactionResponse(connectorId, startResponse);
426 PerformanceStatistics.endMeasure(measureId, beginId);
427 return startResponse;
428 }
429 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
430 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
431 StartTransactionRequest,
432 StartTransactionResponse
433 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
434 this.handleStartTransactionResponse(connectorId, startResponse);
435 PerformanceStatistics.endMeasure(measureId, beginId);
436 return startResponse;
437 }
438
439 private async stopTransaction(
440 connectorId: number,
441 reason = StopTransactionReason.LOCAL,
442 ): Promise<StopTransactionResponse | undefined> {
443 const measureId = 'StopTransaction with ATG';
444 const beginId = PerformanceStatistics.beginMeasure(measureId);
445 let stopResponse: StopTransactionResponse | undefined;
446 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
447 logger.info(
448 `${this.logPrefix(
449 connectorId,
450 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
451 ?.transactionId}`,
452 );
453 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
454 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests!;
455 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
456 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests!;
457 } else {
458 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests!;
459 }
460 } else {
461 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
462 logger.debug(
463 `${this.logPrefix(connectorId)} stopping a not started transaction${
464 !isNullOrUndefined(transactionId) ? ` with id ${transactionId}` : ''
465 }`,
466 );
467 }
468 PerformanceStatistics.endMeasure(measureId, beginId);
469 return stopResponse;
470 }
471
472 private getRequireAuthorize(): boolean {
473 return (
474 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
475 );
476 }
477
478 private logPrefix = (connectorId?: number): string => {
479 return logPrefix(
480 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
481 !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}` : ''
482 }:`,
483 );
484 };
485
486 private handleStartTransactionResponse(
487 connectorId: number,
488 startResponse: StartTransactionResponse,
489 ): void {
490 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests!;
491 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
492 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests!;
493 } else {
494 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
495 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests!;
496 }
497 }
498 }