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