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