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