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