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