3b27f247d3419f38756582f42ba9b83248049f9d
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { hoursToMilliseconds, secondsToMilliseconds } from 'date-fns'
4
5 import type { ChargingStation } from './ChargingStation.js'
6 import { checkChargingStation } from './Helpers.js'
7 import { IdTagsCache } from './IdTagsCache.js'
8 import { isIdTagAuthorized } from './ocpp/index.js'
9 import { BaseError } from '../exception/index.js'
10 import { PerformanceStatistics } from '../performance/index.js'
11 import {
12 AuthorizationStatus,
13 RequestCommand,
14 type StartTransactionRequest,
15 type StartTransactionResponse,
16 type Status,
17 StopTransactionReason,
18 type StopTransactionResponse
19 } from '../types/index.js'
20 import {
21 Constants,
22 cloneObject,
23 convertToDate,
24 formatDurationMilliSeconds,
25 getRandomInteger,
26 isValidTime,
27 logPrefix,
28 logger,
29 secureRandom,
30 sleep
31 } from '../utils/index.js'
32
33 export class AutomaticTransactionGenerator {
34 private static readonly instances: Map<string, AutomaticTransactionGenerator> = new Map<
35 string,
36 AutomaticTransactionGenerator
37 >()
38
39 public readonly connectorsStatus: Map<number, Status>
40 public started: boolean
41 private starting: boolean
42 private stopping: boolean
43 private readonly chargingStation: ChargingStation
44
45 private constructor (chargingStation: ChargingStation) {
46 this.started = false
47 this.starting = false
48 this.stopping = false
49 this.chargingStation = chargingStation
50 this.connectorsStatus = new Map<number, Status>()
51 this.initializeConnectorsStatus()
52 }
53
54 public static getInstance (
55 chargingStation: ChargingStation
56 ): AutomaticTransactionGenerator | undefined {
57 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
58 if (!AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo!.hashId)) {
59 AutomaticTransactionGenerator.instances.set(
60 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
61 chargingStation.stationInfo!.hashId,
62 new AutomaticTransactionGenerator(chargingStation)
63 )
64 }
65 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
66 return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo!.hashId)
67 }
68
69 public start (): void {
70 if (!checkChargingStation(this.chargingStation, this.logPrefix())) {
71 return
72 }
73 if (this.started) {
74 logger.warn(`${this.logPrefix()} is already started`)
75 return
76 }
77 if (this.starting) {
78 logger.warn(`${this.logPrefix()} is already starting`)
79 return
80 }
81 this.starting = true
82 this.startConnectors()
83 this.started = true
84 this.starting = false
85 }
86
87 public stop (): void {
88 if (!this.started) {
89 logger.warn(`${this.logPrefix()} is already stopped`)
90 return
91 }
92 if (this.stopping) {
93 logger.warn(`${this.logPrefix()} is already stopping`)
94 return
95 }
96 this.stopping = true
97 this.stopConnectors()
98 this.started = false
99 this.stopping = false
100 }
101
102 public startConnector (connectorId: number): void {
103 if (!checkChargingStation(this.chargingStation, this.logPrefix(connectorId))) {
104 return
105 }
106 if (!this.connectorsStatus.has(connectorId)) {
107 logger.error(`${this.logPrefix(connectorId)} starting on non existing connector`)
108 throw new BaseError(`Connector ${connectorId} does not exist`)
109 }
110 if (this.connectorsStatus.get(connectorId)?.start === false) {
111 this.internalStartConnector(connectorId).catch(Constants.EMPTY_FUNCTION)
112 } else if (this.connectorsStatus.get(connectorId)?.start === true) {
113 logger.warn(`${this.logPrefix(connectorId)} is already started on connector`)
114 }
115 }
116
117 public stopConnector (connectorId: number): void {
118 if (!this.connectorsStatus.has(connectorId)) {
119 logger.error(`${this.logPrefix(connectorId)} stopping on non existing connector`)
120 throw new BaseError(`Connector ${connectorId} does not exist`)
121 }
122 if (this.connectorsStatus.get(connectorId)?.start === true) {
123 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
124 this.connectorsStatus.get(connectorId)!.start = false
125 } else if (this.connectorsStatus.get(connectorId)?.start === false) {
126 logger.warn(`${this.logPrefix(connectorId)} is already stopped on connector`)
127 }
128 }
129
130 private startConnectors (): void {
131 if (
132 this.connectorsStatus.size > 0 &&
133 this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()
134 ) {
135 this.connectorsStatus.clear()
136 this.initializeConnectorsStatus()
137 }
138 if (this.chargingStation.hasEvses) {
139 for (const [evseId, evseStatus] of this.chargingStation.evses) {
140 if (evseId > 0) {
141 for (const connectorId of evseStatus.connectors.keys()) {
142 this.startConnector(connectorId)
143 }
144 }
145 }
146 } else {
147 for (const connectorId of this.chargingStation.connectors.keys()) {
148 if (connectorId > 0) {
149 this.startConnector(connectorId)
150 }
151 }
152 }
153 }
154
155 private stopConnectors (): void {
156 if (this.chargingStation.hasEvses) {
157 for (const [evseId, evseStatus] of this.chargingStation.evses) {
158 if (evseId > 0) {
159 for (const connectorId of evseStatus.connectors.keys()) {
160 this.stopConnector(connectorId)
161 }
162 }
163 }
164 } else {
165 for (const connectorId of this.chargingStation.connectors.keys()) {
166 if (connectorId > 0) {
167 this.stopConnector(connectorId)
168 }
169 }
170 }
171 }
172
173 private async internalStartConnector (connectorId: number): Promise<void> {
174 this.setStartConnectorStatus(connectorId)
175 logger.info(
176 `${this.logPrefix(
177 connectorId
178 )} started on connector and will run for ${formatDurationMilliSeconds(
179 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
180 this.connectorsStatus.get(connectorId)!.stopDate!.getTime() -
181 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
182 this.connectorsStatus.get(connectorId)!.startDate!.getTime()
183 )}`
184 )
185 while (this.connectorsStatus.get(connectorId)?.start === true) {
186 await this.waitChargingStationAvailable(connectorId)
187 await this.waitConnectorAvailable(connectorId)
188 if (!this.canStartConnector(connectorId)) {
189 this.stopConnector(connectorId)
190 break
191 }
192 const wait = secondsToMilliseconds(
193 getRandomInteger(
194 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
195 ?.maxDelayBetweenTwoTransactions,
196 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
197 ?.minDelayBetweenTwoTransactions
198 )
199 )
200 logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`)
201 await sleep(wait)
202 const start = secureRandom()
203 if (
204 start <
205 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
206 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()!.probabilityOfStart
207 ) {
208 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
209 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0
210 // Start transaction
211 const startResponse = await this.startTransaction(connectorId)
212 if (startResponse?.idTagInfo.status === AuthorizationStatus.ACCEPTED) {
213 // Wait until end of transaction
214 const waitTrxEnd = secondsToMilliseconds(
215 getRandomInteger(
216 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.maxDuration,
217 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.minDuration
218 )
219 )
220 logger.info(
221 `${this.logPrefix(
222 connectorId
223 )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId)
224 ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`
225 )
226 await sleep(waitTrxEnd)
227 await this.stopTransaction(connectorId)
228 }
229 } else {
230 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
231 ++this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions
232 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
233 ++this.connectorsStatus.get(connectorId)!.skippedTransactions
234 logger.info(
235 `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get(
236 connectorId
237 )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId)
238 ?.skippedTransactions} transaction(s)`
239 )
240 }
241 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
242 this.connectorsStatus.get(connectorId)!.lastRunDate = new Date()
243 }
244 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
245 this.connectorsStatus.get(connectorId)!.stoppedDate = new Date()
246 logger.info(
247 `${this.logPrefix(
248 connectorId
249 )} stopped on connector and lasted for ${formatDurationMilliSeconds(
250 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
251 this.connectorsStatus.get(connectorId)!.stoppedDate!.getTime() -
252 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
253 this.connectorsStatus.get(connectorId)!.startDate!.getTime()
254 )}`
255 )
256 logger.debug(
257 `${this.logPrefix(connectorId)} connector status: %j`,
258 this.connectorsStatus.get(connectorId)
259 )
260 }
261
262 private setStartConnectorStatus (connectorId: number): void {
263 const previousRunDuration =
264 isValidTime(this.connectorsStatus.get(connectorId)?.startDate) &&
265 isValidTime(this.connectorsStatus.get(connectorId)?.lastRunDate) &&
266 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
267 this.connectorsStatus.get(connectorId)!.lastRunDate! >
268 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
269 this.connectorsStatus.get(connectorId)!.startDate!
270 ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
271 this.connectorsStatus.get(connectorId)!.lastRunDate!.getTime() -
272 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
273 this.connectorsStatus.get(connectorId)!.startDate!.getTime()
274 : 0
275 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
276 this.connectorsStatus.get(connectorId)!.startDate = new Date()
277 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
278 this.connectorsStatus.get(connectorId)!.stopDate = new Date(
279 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
280 this.connectorsStatus.get(connectorId)!.startDate!.getTime() +
281 hoursToMilliseconds(
282 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
283 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()!.stopAfterHours
284 ) -
285 previousRunDuration
286 )
287 delete this.connectorsStatus.get(connectorId)?.stoppedDate
288 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
289 this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions = 0
290 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
291 this.connectorsStatus.get(connectorId)!.start = true
292 }
293
294 private canStartConnector (connectorId: number): boolean {
295 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
296 if (new Date() > this.connectorsStatus.get(connectorId)!.stopDate!) {
297 logger.info(
298 `${this.logPrefix(
299 connectorId
300 )} entered in transaction loop while the ATG stop date has been reached`
301 )
302 return false
303 }
304 if (!this.chargingStation.inAcceptedState()) {
305 logger.error(
306 `${this.logPrefix(
307 connectorId
308 )} entered in transaction loop while the charging station is not in accepted state`
309 )
310 return false
311 }
312 if (!this.chargingStation.isChargingStationAvailable()) {
313 logger.info(
314 `${this.logPrefix(
315 connectorId
316 )} entered in transaction loop while the charging station is unavailable`
317 )
318 return false
319 }
320 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
321 logger.info(
322 `${this.logPrefix(
323 connectorId
324 )} entered in transaction loop while the connector ${connectorId} is unavailable`
325 )
326 return false
327 }
328 return true
329 }
330
331 private async waitChargingStationAvailable (connectorId: number): Promise<void> {
332 let logged = false
333 while (!this.chargingStation.isChargingStationAvailable()) {
334 if (!logged) {
335 logger.info(
336 `${this.logPrefix(
337 connectorId
338 )} transaction loop waiting for charging station to be available`
339 )
340 logged = true
341 }
342 await sleep(Constants.CHARGING_STATION_ATG_AVAILABILITY_TIME)
343 }
344 }
345
346 private async waitConnectorAvailable (connectorId: number): Promise<void> {
347 let logged = false
348 while (!this.chargingStation.isConnectorAvailable(connectorId)) {
349 if (!logged) {
350 logger.info(
351 `${this.logPrefix(
352 connectorId
353 )} transaction loop waiting for connector ${connectorId} to be available`
354 )
355 logged = true
356 }
357 await sleep(Constants.CHARGING_STATION_ATG_AVAILABILITY_TIME)
358 }
359 }
360
361 private initializeConnectorsStatus (): void {
362 if (this.chargingStation.hasEvses) {
363 for (const [evseId, evseStatus] of this.chargingStation.evses) {
364 if (evseId > 0) {
365 for (const connectorId of evseStatus.connectors.keys()) {
366 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId))
367 }
368 }
369 }
370 } else {
371 for (const connectorId of this.chargingStation.connectors.keys()) {
372 if (connectorId > 0) {
373 this.connectorsStatus.set(connectorId, this.getConnectorStatus(connectorId))
374 }
375 }
376 }
377 }
378
379 private getConnectorStatus (connectorId: number): Status {
380 const connectorStatus =
381 this.chargingStation.getAutomaticTransactionGeneratorStatuses()?.[connectorId - 1] != null
382 ? cloneObject<Status>(
383 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
384 this.chargingStation.getAutomaticTransactionGeneratorStatuses()![connectorId - 1]
385 )
386 : undefined
387 if (connectorStatus != null) {
388 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
389 connectorStatus.startDate = convertToDate(connectorStatus.startDate)!
390 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
391 connectorStatus.lastRunDate = convertToDate(connectorStatus.lastRunDate)!
392 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
393 connectorStatus.stopDate = convertToDate(connectorStatus.stopDate)!
394 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
395 connectorStatus.stoppedDate = convertToDate(connectorStatus.stoppedDate)!
396 if (
397 !this.started &&
398 (connectorStatus.start ||
399 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.enable !== true)
400 ) {
401 connectorStatus.start = false
402 }
403 }
404 return (
405 connectorStatus ?? {
406 start: false,
407 authorizeRequests: 0,
408 acceptedAuthorizeRequests: 0,
409 rejectedAuthorizeRequests: 0,
410 startTransactionRequests: 0,
411 acceptedStartTransactionRequests: 0,
412 rejectedStartTransactionRequests: 0,
413 stopTransactionRequests: 0,
414 acceptedStopTransactionRequests: 0,
415 rejectedStopTransactionRequests: 0,
416 skippedConsecutiveTransactions: 0,
417 skippedTransactions: 0
418 }
419 )
420 }
421
422 private async startTransaction (
423 connectorId: number
424 ): Promise<StartTransactionResponse | undefined> {
425 const measureId = 'StartTransaction with ATG'
426 const beginId = PerformanceStatistics.beginMeasure(measureId)
427 let startResponse: StartTransactionResponse | undefined
428 if (this.chargingStation.hasIdTags()) {
429 const idTag = IdTagsCache.getInstance().getIdTag(
430 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
431 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()!.idTagDistribution!,
432 this.chargingStation,
433 connectorId
434 )
435 const startTransactionLogMsg = `${this.logPrefix(
436 connectorId
437 )} start transaction with an idTag '${idTag}'`
438 if (this.getRequireAuthorize()) {
439 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
440 ++this.connectorsStatus.get(connectorId)!.authorizeRequests
441 if (await isIdTagAuthorized(this.chargingStation, connectorId, idTag)) {
442 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
443 ++this.connectorsStatus.get(connectorId)!.acceptedAuthorizeRequests
444 logger.info(startTransactionLogMsg)
445 // Start transaction
446 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
447 StartTransactionRequest,
448 StartTransactionResponse
449 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
450 connectorId,
451 idTag
452 })
453 this.handleStartTransactionResponse(connectorId, startResponse)
454 PerformanceStatistics.endMeasure(measureId, beginId)
455 return startResponse
456 }
457 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
458 ++this.connectorsStatus.get(connectorId)!.rejectedAuthorizeRequests
459 PerformanceStatistics.endMeasure(measureId, beginId)
460 return startResponse
461 }
462 logger.info(startTransactionLogMsg)
463 // Start transaction
464 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
465 StartTransactionRequest,
466 StartTransactionResponse
467 >(this.chargingStation, RequestCommand.START_TRANSACTION, {
468 connectorId,
469 idTag
470 })
471 this.handleStartTransactionResponse(connectorId, startResponse)
472 PerformanceStatistics.endMeasure(measureId, beginId)
473 return startResponse
474 }
475 logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`)
476 startResponse = await this.chargingStation.ocppRequestService.requestHandler<
477 StartTransactionRequest,
478 StartTransactionResponse
479 >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId })
480 this.handleStartTransactionResponse(connectorId, startResponse)
481 PerformanceStatistics.endMeasure(measureId, beginId)
482 return startResponse
483 }
484
485 private async stopTransaction (
486 connectorId: number,
487 reason = StopTransactionReason.LOCAL
488 ): Promise<StopTransactionResponse | undefined> {
489 const measureId = 'StopTransaction with ATG'
490 const beginId = PerformanceStatistics.beginMeasure(measureId)
491 let stopResponse: StopTransactionResponse | undefined
492 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
493 logger.info(
494 `${this.logPrefix(
495 connectorId
496 )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId)
497 ?.transactionId}`
498 )
499 stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason)
500 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
501 ++this.connectorsStatus.get(connectorId)!.stopTransactionRequests
502 if (stopResponse.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
503 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
504 ++this.connectorsStatus.get(connectorId)!.acceptedStopTransactionRequests
505 } else {
506 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
507 ++this.connectorsStatus.get(connectorId)!.rejectedStopTransactionRequests
508 }
509 } else {
510 const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId
511 logger.debug(
512 `${this.logPrefix(connectorId)} stopping a not started transaction${
513 transactionId != null ? ` with id ${transactionId}` : ''
514 }`
515 )
516 }
517 PerformanceStatistics.endMeasure(measureId, beginId)
518 return stopResponse
519 }
520
521 private getRequireAuthorize (): boolean {
522 return (
523 this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true
524 )
525 }
526
527 private readonly logPrefix = (connectorId?: number): string => {
528 return logPrefix(
529 ` ${this.chargingStation.stationInfo?.chargingStationId} | ATG${
530 connectorId != null ? ` on connector #${connectorId}` : ''
531 }:`
532 )
533 }
534
535 private handleStartTransactionResponse (
536 connectorId: number,
537 startResponse: StartTransactionResponse
538 ): void {
539 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
540 ++this.connectorsStatus.get(connectorId)!.startTransactionRequests
541 if (startResponse.idTagInfo.status === AuthorizationStatus.ACCEPTED) {
542 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
543 ++this.connectorsStatus.get(connectorId)!.acceptedStartTransactionRequests
544 } else {
545 logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`)
546 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
547 ++this.connectorsStatus.get(connectorId)!.rejectedStartTransactionRequests
548 }
549 }
550 }