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