refactor(simulator): use helper for undefined or null 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 { type ChargingStation, ChargingStationUtils, IdTagsCache } from './internal';
6 import { BaseError } from '../exception';
7 // import { PerformanceStatistics } from '../performance';
8 import { PerformanceStatistics } from '../performance/PerformanceStatistics';
9 import {
10 AuthorizationStatus,
11 type AuthorizeRequest,
12 type AuthorizeResponse,
13 type AutomaticTransactionGeneratorConfiguration,
14 ConnectorStatusEnum,
15 RequestCommand,
16 type StartTransactionRequest,
17 type StartTransactionResponse,
18 type Status,
19 StopTransactionReason,
20 type StopTransactionResponse,
21 } from '../types';
22 import { Constants, Utils, logger } from '../utils';
23
24 const moduleName = 'AutomaticTransactionGenerator';
25
26 export class AutomaticTransactionGenerator extends AsyncResource {
27 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
28 string,
29 AutomaticTransactionGenerator
30 >();
31
32 public readonly connectorsStatus: Map<number, Status>;
33 public readonly configuration: AutomaticTransactionGeneratorConfiguration;
34 public started: boolean;
35 private readonly chargingStation: ChargingStation;
36
37 private constructor(
38 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
39 chargingStation: ChargingStation
40 ) {
41 super(moduleName);
42 this.started = false;
43 this.configuration = automaticTransactionGeneratorConfiguration;
44 this.chargingStation = chargingStation;
45 this.connectorsStatus = new Map<number, Status>();
46 this.initializeConnectorsStatus();
47 }
48
49 public static getInstance(
50 automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration,
51 chargingStation: ChargingStation
52 ): AutomaticTransactionGenerator | undefined {
53 if (AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId) === false) {
54 AutomaticTransactionGenerator.instances.set(
55 chargingStation.stationInfo.hashId,
56 new AutomaticTransactionGenerator(
57 automaticTransactionGeneratorConfiguration,
58 chargingStation
59 )
60 );
61 }
62 return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId);
63 }
64
65 public start(): void {
66 if (
67 ChargingStationUtils.checkChargingStation(this.chargingStation, this.logPrefix()) === false
68 ) {
69 return;
70 }
71 if (this.started === true) {
72 logger.warn(`${this.logPrefix()} is already started`);
73 return;
74 }
75 this.startConnectors();
76 this.started = true;
77 }
78
79 public stop(): void {
80 if (this.started === false) {
81 logger.warn(`${this.logPrefix()} is already stopped`);
82 return;
83 }
84 this.stopConnectors();
85 this.started = false;
86 }
87
88 public startConnector(connectorId: number): void {
89 if (
90 ChargingStationUtils.checkChargingStation(
91 this.chargingStation,
92 this.logPrefix(connectorId)
93 ) === false
94 ) {
95 return;
96 }
97 if (this.connectorsStatus.has(connectorId) === false) {
98 logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`);
99 throw new BaseError(`Connector ${connectorId} does not exist`);
100 }
101 if (this.connectorsStatus.get(connectorId)?.start === false) {
102 this.runInAsyncScope(
103 this.internalStartConnector.bind(this) as (
104 this: AutomaticTransactionGenerator,
105 ...args: any[]
106 ) => Promise<void>,
107 this,
108 connectorId
109 ).catch(Constants.EMPTY_FUNCTION);
110 } else if (this.connectorsStatus.get(connectorId)?.start === true) {
111 logger.warn(`${this.logPrefix(connectorId)} is already started on connector`);
112 }
113 }
114
115 public stopConnector(connectorId: number): void {
116 if (this.connectorsStatus.has(connectorId) === false) {
117 logger.error(`${this.logPrefix(connectorId)} stopping on non existing connector`);
118 throw new BaseError(`Connector ${connectorId} does not exist`);
119 }
120 if (this.connectorsStatus.get(connectorId)?.start === true) {
121 this.connectorsStatus.get(connectorId).start = false;
122 } else if (this.connectorsStatus.get(connectorId)?.start === false) {
123 logger.warn(`${this.logPrefix(connectorId)} is already stopped on connector`);
124 }
125 }
126
127 private startConnectors(): void {
128 if (
129 this.connectorsStatus?.size > 0 &&
130 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
131 ) {
132 this.connectorsStatus.clear();
133 this.initializeConnectorsStatus();
134 }
135 for (const connectorId of this.chargingStation.connectors.keys()) {
136 if (connectorId > 0) {
137 this.startConnector(connectorId);
138 }
139 }
140 }
141
142 private stopConnectors(): void {
143 for (const connectorId of this.chargingStation.connectors.keys()) {
144 if (connectorId > 0) {
145 this.stopConnector(connectorId);
146 }
147 }
148 }
149
150 private async internalStartConnector(connectorId: number): Promise<void> {
151 this.setStartConnectorStatus(connectorId);
152 logger.info(
153 `${this.logPrefix(
154 connectorId
155 )} started on connector and will run for ${Utils.formatDurationMilliSeconds(
156 this.connectorsStatus.get(connectorId).stopDate.getTime() -
157 this.connectorsStatus.get(connectorId).startDate.getTime()
158 )}`
159 );
160 while (this.connectorsStatus.get(connectorId)?.start === true) {
161 if (new Date() > this.connectorsStatus.get(connectorId).stopDate) {
162 this.stopConnector(connectorId);
163 break;
164 }
165 if (this.chargingStation.isInAcceptedState() === false) {
166 logger.error(
167 `${this.logPrefix(
168 connectorId
169 )} entered in transaction loop while the charging station is not in accepted state`
170 );
171 this.stopConnector(connectorId);
172 break;
173 }
174 if (this.chargingStation.isChargingStationAvailable() === false) {
175 logger.info(
176 `${this.logPrefix(
177 connectorId
178 )} entered in transaction loop while the charging station is unavailable`
179 );
180 this.stopConnector(connectorId);
181 break;
182 }
183 if (this.chargingStation.isConnectorAvailable(connectorId) === false) {
184 logger.info(
185 `${this.logPrefix(
186 connectorId
187 )} entered in transaction loop while the connector ${connectorId} is unavailable`
188 );
189 this.stopConnector(connectorId);
190 break;
191 }
192 if (
193 this.chargingStation.getConnectorStatus(connectorId)?.status ===
194 ConnectorStatusEnum.Unavailable
195 ) {
196 logger.info(
197 `${this.logPrefix(
198 connectorId
199 )} entered in transaction loop while the connector ${connectorId} status is unavailable`
200 );
201 this.stopConnector(connectorId);
202 break;
203 }
204 if (!this.chargingStation?.ocppRequestService) {
205 logger.info(
206 `${this.logPrefix(
207 connectorId
208 )} transaction loop waiting for charging station service to be initialized`
209 );
210 do {
211 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
212 } while (!this.chargingStation?.ocppRequestService);
213 }
214 const wait =
215 Utils.getRandomInteger(
216 this.configuration.maxDelayBetweenTwoTransactions,
217 this.configuration.minDelayBetweenTwoTransactions
218 ) * 1000;
219 logger.info(
220 `${this.logPrefix(connectorId)} waiting for ${Utils.formatDurationMilliSeconds(wait)}`
221 );
222 await Utils.sleep(wait);
223 const start = Utils.secureRandom();
224 if (start < this.configuration.probabilityOfStart) {
225 this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
226 // Start transaction
227 const startResponse = await this.startTransaction(connectorId);
228 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
229 // Wait until end of transaction
230 const waitTrxEnd =
231 Utils.getRandomInteger(this.configuration.maxDuration, this.configuration.minDuration) *
232 1000;
233 logger.info(
234 `${this.logPrefix(connectorId)} transaction ${this.chargingStation
235 .getConnectorStatus(connectorId)
236 ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
237 waitTrxEnd
238 )}`
239 );
240 await Utils.sleep(waitTrxEnd);
241 // Stop transaction
242 logger.info(
243 `${this.logPrefix(connectorId)} stop transaction ${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 ${Utils.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 (this.configuration.stopAfterHours ??
289 Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) *
290 3600 *
291 1000 -
292 previousRunDuration
293 );
294 this.connectorsStatus.get(connectorId).start = true;
295 }
296
297 private initializeConnectorsStatus(): void {
298 for (const connectorId of this.chargingStation.connectors.keys()) {
299 if (connectorId > 0) {
300 this.connectorsStatus.set(connectorId, {
301 start: false,
302 authorizeRequests: 0,
303 acceptedAuthorizeRequests: 0,
304 rejectedAuthorizeRequests: 0,
305 startTransactionRequests: 0,
306 acceptedStartTransactionRequests: 0,
307 rejectedStartTransactionRequests: 0,
308 stopTransactionRequests: 0,
309 acceptedStopTransactionRequests: 0,
310 rejectedStopTransactionRequests: 0,
311 skippedConsecutiveTransactions: 0,
312 skippedTransactions: 0,
313 });
314 }
315 }
316 }
317
318 private async startTransaction(
319 connectorId: number
320 ): Promise<StartTransactionResponse | undefined> {
321 const measureId = 'StartTransaction with ATG';
322 const beginId = PerformanceStatistics.beginMeasure(measureId);
323 let startResponse: StartTransactionResponse;
324 if (this.chargingStation.hasIdTags()) {
325 const idTag = IdTagsCache.getInstance().getIdTag(
326 this.configuration?.idTagDistribution,
327 this.chargingStation,
328 connectorId
329 );
330 const startTransactionLogMsg = `${this.logPrefix(
331 connectorId
332 )} start transaction with an idTag '${idTag}'`;
333 if (this.getRequireAuthorize()) {
334 this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag;
335 // Authorize idTag
336 const authorizeResponse: AuthorizeResponse =
337 await this.chargingStation.ocppRequestService.requestHandler<
338 AuthorizeRequest,
339 AuthorizeResponse
340 >(this.chargingStation, RequestCommand.AUTHORIZE, {
341 idTag,
342 });
343 this.connectorsStatus.get(connectorId).authorizeRequests++;
344 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
345 this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++;
346 logger.info(startTransactionLogMsg);
347 // Start transaction
348 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
349 StartTransactionRequest,
350 StartTransactionResponse
351 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
352 connectorId,
353 idTag,
354 });
355 this.handleStartTransactionResponse(connectorId, startResponse);
356 PerformanceStatistics.endMeasure(measureId, beginId);
357 return startResponse;
358 }
359 this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++;
360 PerformanceStatistics.endMeasure(measureId, beginId);
361 return startResponse;
362 }
363 logger.info(startTransactionLogMsg);
364 // Start transaction
365 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
366 StartTransactionRequest,
367 StartTransactionResponse
368 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
369 connectorId,
370 idTag,
371 });
372 this.handleStartTransactionResponse(connectorId, startResponse);
373 PerformanceStatistics.endMeasure(measureId, beginId);
374 return startResponse;
375 }
376 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`);
377 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
378 StartTransactionRequest,
379 StartTransactionResponse
380 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId });
381 this.handleStartTransactionResponse(connectorId, startResponse);
382 PerformanceStatistics.endMeasure(measureId, beginId);
383 return startResponse;
384 }
385
386 private async stopTransaction(
387 connectorId: number,
388 reason: StopTransactionReason = StopTransactionReason.LOCAL
389 ): Promise<StopTransactionResponse> {
390 const measureId = 'StopTransaction with ATG';
391 const beginId = PerformanceStatistics.beginMeasure(measureId);
392 let stopResponse: StopTransactionResponse;
393 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
394 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason);
395 this.connectorsStatus.get(connectorId).stopTransactionRequests++;
396 if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
397 this.connectorsStatus.get(connectorId).acceptedStopTransactionRequests++;
398 } else {
399 this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests++;
400 }
401 } else {
402 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId;
403 logger.warn(
404 `${this.logPrefix(connectorId)} stopping a not started transaction${
405 !Utils.isNullOrUndefined(transactionId) ? ` ${transactionId?.toString()}` : ''
406 }`
407 );
408 }
409 PerformanceStatistics.endMeasure(measureId, beginId);
410 return stopResponse;
411 }
412
413 private getRequireAuthorize(): boolean {
414 return this.configuration?.requireAuthorize ?? true;
415 }
416
417 private logPrefix = (connectorId?: number): string => {
418 return Utils.logPrefix(
419 ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${
420 !Utils.isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}` : ''
421 }:`
422 );
423 };
424
425 private handleStartTransactionResponse(
426 connectorId: number,
427 startResponse: StartTransactionResponse
428 ): void {
429 this.connectorsStatus.get(connectorId).startTransactionRequests++;
430 if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
431 this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++;
432 } else {
433 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`);
434 this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++;
435 }
436 }
437 }