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