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