Strict null check fixes
[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
1895299d 58 ): AutomaticTransactionGenerator | undefined {
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 153 logger.info(
44eb6026
JB
154 `${this.logPrefix(
155 connectorId
156 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
157 this.connectorsStatus.get(connectorId).stopDate.getTime() -
158 this.connectorsStatus.get(connectorId).startDate.getTime()
159 )}`
e7aeea18 160 );
1895299d 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 167 logger.error(
44eb6026
JB
168 `${this.logPrefix(
169 connectorId
170 )} entered in transaction loop while the charging station is not in accepted state`
e7aeea18 171 );
9664ec50 172 this.stopConnector(connectorId);
17991e8c
JB
173 break;
174 }
1789ba2c 175 if (this.chargingStation.isChargingStationAvailable() === false) {
e7aeea18 176 logger.info(
44eb6026
JB
177 `${this.logPrefix(
178 connectorId
179 )} entered in transaction loop while the charging station is unavailable`
e7aeea18 180 );
9664ec50 181 this.stopConnector(connectorId);
ab5f4b03
JB
182 break;
183 }
1789ba2c 184 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
e7aeea18
JB
185 logger.info(
186 `${this.logPrefix(
187 connectorId
188 )} entered in transaction loop while the connector ${connectorId} is unavailable`
189 );
9c7195b2 190 this.stopConnector(connectorId);
17991e8c
JB
191 break;
192 }
c0560973 193 if (!this.chargingStation?.ocppRequestService) {
e7aeea18
JB
194 logger.info(
195 `${this.logPrefix(
196 connectorId
197 )} transaction loop waiting for charging station service to be initialized`
198 );
c0560973 199 do {
a4cc42ea 200 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
c0560973
JB
201 } while (!this.chargingStation?.ocppRequestService);
202 }
e7aeea18
JB
203 const wait =
204 Utils.getRandomInteger(
fa7bccf4
JB
205 this.configuration.maxDelayBetweenTwoTransactions,
206 this.configuration.minDelayBetweenTwoTransactions
e7aeea18
JB
207 ) * 1000;
208 logger.info(
44eb6026 209 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
e7aeea18 210 );
6af9012e 211 await Utils.sleep(wait);
c37528f1 212 const start = Utils.secureRandom();
fa7bccf4 213 if (start < this.configuration.probabilityOfStart) {
9664ec50 214 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
6af9012e 215 // Start transaction
aef1b33a 216 const startResponse = await this.startTransaction(connectorId);
0afed85f 217 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
6af9012e 218 // Wait until end of transaction
e7aeea18 219 const waitTrxEnd =
fa7bccf4
JB
220 Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
221 1000;
e7aeea18 222 logger.info(
44eb6026
JB
223 `${this.logPrefix(connectorId)} transaction ${this.chargingStation
224 .getConnectorStatus(connectorId)
72092cfc 225 ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
44eb6026
JB
226 waitTrxEnd
227 )}`
e7aeea18 228 );
6af9012e
JB
229 await Utils.sleep(waitTrxEnd);
230 // Stop transaction
e7aeea18 231 logger.info(
44eb6026
JB
232 `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation
233 .getConnectorStatus(connectorId)
1895299d 234 ?.transactionId?.toString()}`
e7aeea18 235 );
85d20667 236 await this.stopTransaction(connectorId);
6af9012e
JB
237 }
238 } else {
9664ec50
JB
239 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++;
240 this.connectorsStatus.get(connectorId).skippedTransactions++;
e7aeea18 241 logger.info(
44eb6026
JB
242 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus
243 .get(connectorId)
1895299d 244 ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
44eb6026 245 .get(connectorId)
1895299d 246 ?.skippedTransactions?.toString()} transaction(s)`
e7aeea18 247 );
6af9012e 248 }
9664ec50 249 this.connectorsStatus.get(connectorId).lastRunDate = new Date();
7d75bee1 250 }
9664ec50 251 this.connectorsStatus.get(connectorId).stoppedDate = new Date();
e7aeea18 252 logger.info(
44eb6026
JB
253 `${this.logPrefix(
254 connectorId
255 )} stopped on connector and lasted for ${Utils.formatDurationMilliSeconds(
256 this.connectorsStatus.get(connectorId).stoppedDate.getTime() -
257 this.connectorsStatus.get(connectorId).startDate.getTime()
258 )}`
e7aeea18
JB
259 );
260 logger.debug(
be9ee554 261 `${this.logPrefix(connectorId)} connector status: %j`,
e7aeea18
JB
262 this.connectorsStatus.get(connectorId)
263 );
6af9012e
JB
264 }
265
083fb002 266 private setStartConnectorStatus(connectorId: number): void {
9664ec50 267 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
e7aeea18 268 const previousRunDuration =
72092cfc
JB
269 this.connectorsStatus.get(connectorId)?.startDate &&
270 this.connectorsStatus.get(connectorId)?.lastRunDate
e7aeea18
JB
271 ? this.connectorsStatus.get(connectorId).lastRunDate.getTime() -
272 this.connectorsStatus.get(connectorId).startDate.getTime()
273 : 0;
9664ec50 274 this.connectorsStatus.get(connectorId).startDate = new Date();
e7aeea18
JB
275 this.connectorsStatus.get(connectorId).stopDate = new Date(
276 this.connectorsStatus.get(connectorId).startDate.getTime() +
fa7bccf4 277 (this.configuration.stopAfterHours ??
e7aeea18
JB
278 Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
279 3600 *
280 1000 -
281 previousRunDuration
282 );
083fb002 283 this.connectorsStatus.get(connectorId).start = true;
4dff3039
JB
284 }
285
7807ccf2 286 private initializeConnectorsStatus(): void {
4dff3039
JB
287 for (const connectorId of this.chargingStation.connectors.keys()) {
288 if (connectorId > 0) {
7807ccf2
JB
289 this.connectorsStatus.set(connectorId, {
290 start: false,
291 authorizeRequests: 0,
292 acceptedAuthorizeRequests: 0,
293 rejectedAuthorizeRequests: 0,
294 startTransactionRequests: 0,
295 acceptedStartTransactionRequests: 0,
296 rejectedStartTransactionRequests: 0,
297 stopTransactionRequests: 0,
298 acceptedStopTransactionRequests: 0,
299 rejectedStopTransactionRequests: 0,
300 skippedConsecutiveTransactions: 0,
301 skippedTransactions: 0,
302 });
4dff3039
JB
303 }
304 }
72740232
JB
305 }
306
e7aeea18
JB
307 private async startTransaction(
308 connectorId: number
0afed85f 309 ): Promise<StartTransactionResponse | undefined> {
aef1b33a
JB
310 const measureId = 'StartTransaction with ATG';
311 const beginId = PerformanceStatistics.beginMeasure(measureId);
312 let startResponse: StartTransactionResponse;
313 if (this.chargingStation.hasAuthorizedTags()) {
c72f6634 314 const idTag = this.getIdTag(connectorId);
5cf9050d
JB
315 const startTransactionLogMsg = `${this.logPrefix(
316 connectorId
ba7965c4 317 )} start transaction with an idTag '${idTag}'`;
ccb1d6e9 318 if (this.getRequireAuthorize()) {
2e3d65ae 319 this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
f4bf2abd 320 // Authorize idTag
2e3d65ae 321 const authorizeResponse: AuthorizeResponse =
f7f98c68 322 await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
323 AuthorizeRequest,
324 AuthorizeResponse
08f130a0 325 >(this.chargingStation, RequestCommand.AUTHORIZE, {
ef6fa3fb
JB
326 idTag,
327 });
071a9315 328 this.connectorsStatus.get(connectorId).authorizeRequests++;
5fdab605 329 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
071a9315 330 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
5cf9050d 331 logger.info(startTransactionLogMsg);
5fdab605 332 // Start transaction
f7f98c68 333 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
334 StartTransactionRequest,
335 StartTransactionResponse
08f130a0 336 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
ef6fa3fb
JB
337 connectorId,
338 idTag,
339 });
d9ac47ef 340 this.handleStartTransactionResponse(connectorId, startResponse);
aef1b33a
JB
341 PerformanceStatistics.endMeasure(measureId, beginId);
342 return startResponse;
5fdab605 343 }
071a9315 344 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
aef1b33a 345 PerformanceStatistics.endMeasure(measureId, beginId);
0afed85f 346 return startResponse;
ef6076c1 347 }
5cf9050d 348 logger.info(startTransactionLogMsg);
5fdab605 349 // Start transaction
f7f98c68 350 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
351 StartTransactionRequest,
352 StartTransactionResponse
08f130a0 353 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
ef6fa3fb
JB
354 connectorId,
355 idTag,
356 });
d9ac47ef 357 this.handleStartTransactionResponse(connectorId, startResponse);
aef1b33a
JB
358 PerformanceStatistics.endMeasure(measureId, beginId);
359 return startResponse;
6af9012e 360 }
5cf9050d 361 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
f7f98c68 362 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
ef6fa3fb
JB
363 StartTransactionRequest,
364 StartTransactionResponse
08f130a0 365 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
431b6bd5 366 this.handleStartTransactionResponse(connectorId, startResponse);
aef1b33a
JB
367 PerformanceStatistics.endMeasure(measureId, beginId);
368 return startResponse;
6af9012e
JB
369 }
370
e7aeea18
JB
371 private async stopTransaction(
372 connectorId: number,
5e3cb728 373 reason: StopTransactionReason = StopTransactionReason.LOCAL
e7aeea18 374 ): Promise<StopTransactionResponse> {
aef1b33a
JB
375 const measureId = 'StopTransaction with ATG';
376 const beginId = PerformanceStatistics.beginMeasure(measureId);
0045cef5 377 let stopResponse: StopTransactionResponse;
6d9876e7 378 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
5e3cb728 379 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
071a9315 380 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
0afed85f 381 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
6d9876e7
JB
382 this.connectorsStatus.get(connectorId).acceptedStopTransactionRequests++;
383 } else {
384 this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests++;
385 }
0045cef5 386 } else {
1895299d 387 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
e7aeea18 388 logger.warn(
ba7965c4 389 `${this.logPrefix(connectorId)} stopping a not started transaction${
44eb6026 390 transactionId ? ` ${transactionId.toString()}` : ''
e7aeea18
JB
391 }`
392 );
0045cef5 393 }
aef1b33a
JB
394 PerformanceStatistics.endMeasure(measureId, beginId);
395 return stopResponse;
c0560973
JB
396 }
397
ccb1d6e9 398 private getRequireAuthorize(): boolean {
fa7bccf4 399 return this.configuration?.requireAuthorize ?? true;
ccb1d6e9
JB
400 }
401
c72f6634
JB
402 private getRandomIdTag(authorizationFile: string): string {
403 const tags = this.chargingStation.authorizedTagsCache.getAuthorizedTags(authorizationFile);
404 this.idTagIndex = Math.floor(Utils.secureRandom() * tags.length);
405 return tags[this.idTagIndex];
406 }
407
408 private getRoundRobinIdTag(authorizationFile: string): string {
409 const tags = this.chargingStation.authorizedTagsCache.getAuthorizedTags(authorizationFile);
410 const idTag = tags[this.idTagIndex];
411 this.idTagIndex = this.idTagIndex === tags.length - 1 ? 0 : this.idTagIndex + 1;
412 return idTag;
413 }
414
415 private getConnectorAffinityIdTag(authorizationFile: string, connectorId: number): string {
416 const tags = this.chargingStation.authorizedTagsCache.getAuthorizedTags(authorizationFile);
417 this.idTagIndex = (this.chargingStation.index - 1 + (connectorId - 1)) % tags.length;
418 return tags[this.idTagIndex];
419 }
420
421 private getIdTag(connectorId: number): string {
422 const authorizationFile = ChargingStationUtils.getAuthorizationFile(
423 this.chargingStation.stationInfo
424 );
425 switch (this.configuration?.idTagDistribution) {
426 case IdTagDistribution.RANDOM:
427 return this.getRandomIdTag(authorizationFile);
428 case IdTagDistribution.ROUND_ROBIN:
429 return this.getRoundRobinIdTag(authorizationFile);
430 case IdTagDistribution.CONNECTOR_AFFINITY:
431 return this.getConnectorAffinityIdTag(authorizationFile, connectorId);
432 default:
433 return this.getRoundRobinIdTag(authorizationFile);
434 }
435 }
436
6e0964c8 437 private logPrefix(connectorId?: number): string {
6cd85def
JB
438 return Utils.logPrefix(
439 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
a5e9befc 440 connectorId !== undefined ? ` on connector #${connectorId.toString()}` : ''
6cd85def
JB
441 }:`
442 );
6af9012e 443 }
d9ac47ef
JB
444
445 private handleStartTransactionResponse(
446 connectorId: number,
447 startResponse: StartTransactionResponse
448 ): void {
449 this.connectorsStatus.get(connectorId).startTransactionRequests++;
450 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
451 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
452 } else {
44eb6026 453 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
d9ac47ef
JB
454 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
455 }
456 }
d1c6c833
JB
457
458 private checkChargingStation(connectorId?: number): boolean {
cbf9b878 459 if (this.chargingStation.started === false && this.chargingStation.starting === false) {
d1c6c833 460 logger.warn(`${this.logPrefix(connectorId)} charging station is stopped, cannot proceed`);
cbf9b878 461 return false;
d1c6c833 462 }
cbf9b878 463 return true;
d1c6c833 464 }
6af9012e 465}