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