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