| 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 = Utils.cloneObject( |
| 334 | this.chargingStation.getAutomaticTransactionGeneratorStatuses() |
| 335 | )[connectorId]; |
| 336 | delete connectorStatus?.startDate; |
| 337 | delete connectorStatus?.lastRunDate; |
| 338 | delete connectorStatus?.stopDate; |
| 339 | delete connectorStatus?.stoppedDate; |
| 340 | return ( |
| 341 | connectorStatus ?? { |
| 342 | start: false, |
| 343 | authorizeRequests: 0, |
| 344 | acceptedAuthorizeRequests: 0, |
| 345 | rejectedAuthorizeRequests: 0, |
| 346 | startTransactionRequests: 0, |
| 347 | acceptedStartTransactionRequests: 0, |
| 348 | rejectedStartTransactionRequests: 0, |
| 349 | stopTransactionRequests: 0, |
| 350 | acceptedStopTransactionRequests: 0, |
| 351 | rejectedStopTransactionRequests: 0, |
| 352 | skippedConsecutiveTransactions: 0, |
| 353 | skippedTransactions: 0, |
| 354 | } |
| 355 | ); |
| 356 | } |
| 357 | |
| 358 | private async startTransaction( |
| 359 | connectorId: number |
| 360 | ): Promise<StartTransactionResponse | undefined> { |
| 361 | const measureId = 'StartTransaction with ATG'; |
| 362 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 363 | let startResponse: StartTransactionResponse; |
| 364 | if (this.chargingStation.hasIdTags()) { |
| 365 | const idTag = IdTagsCache.getInstance().getIdTag( |
| 366 | this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution, |
| 367 | this.chargingStation, |
| 368 | connectorId |
| 369 | ); |
| 370 | const startTransactionLogMsg = `${this.logPrefix( |
| 371 | connectorId |
| 372 | )} start transaction with an idTag '${idTag}'`; |
| 373 | if (this.getRequireAuthorize()) { |
| 374 | this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag; |
| 375 | // Authorize idTag |
| 376 | const authorizeResponse: AuthorizeResponse = |
| 377 | await this.chargingStation.ocppRequestService.requestHandler< |
| 378 | AuthorizeRequest, |
| 379 | AuthorizeResponse |
| 380 | >(this.chargingStation, RequestCommand.AUTHORIZE, { |
| 381 | idTag, |
| 382 | }); |
| 383 | ++this.connectorsStatus.get(connectorId).authorizeRequests; |
| 384 | if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { |
| 385 | ++this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests; |
| 386 | logger.info(startTransactionLogMsg); |
| 387 | // Start transaction |
| 388 | startResponse = await this.chargingStation.ocppRequestService.requestHandler< |
| 389 | StartTransactionRequest, |
| 390 | StartTransactionResponse |
| 391 | >(this.chargingStation, RequestCommand.START_TRANSACTION, { |
| 392 | connectorId, |
| 393 | idTag, |
| 394 | }); |
| 395 | this.handleStartTransactionResponse(connectorId, startResponse); |
| 396 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 397 | return startResponse; |
| 398 | } |
| 399 | ++this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests; |
| 400 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 401 | return startResponse; |
| 402 | } |
| 403 | logger.info(startTransactionLogMsg); |
| 404 | // Start transaction |
| 405 | startResponse = await this.chargingStation.ocppRequestService.requestHandler< |
| 406 | StartTransactionRequest, |
| 407 | StartTransactionResponse |
| 408 | >(this.chargingStation, RequestCommand.START_TRANSACTION, { |
| 409 | connectorId, |
| 410 | idTag, |
| 411 | }); |
| 412 | this.handleStartTransactionResponse(connectorId, startResponse); |
| 413 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 414 | return startResponse; |
| 415 | } |
| 416 | logger.info(`${this.logPrefix(connectorId)} start transaction without an idTag`); |
| 417 | startResponse = await this.chargingStation.ocppRequestService.requestHandler< |
| 418 | StartTransactionRequest, |
| 419 | StartTransactionResponse |
| 420 | >(this.chargingStation, RequestCommand.START_TRANSACTION, { connectorId }); |
| 421 | this.handleStartTransactionResponse(connectorId, startResponse); |
| 422 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 423 | return startResponse; |
| 424 | } |
| 425 | |
| 426 | private async stopTransaction( |
| 427 | connectorId: number, |
| 428 | reason: StopTransactionReason = StopTransactionReason.LOCAL |
| 429 | ): Promise<StopTransactionResponse> { |
| 430 | const measureId = 'StopTransaction with ATG'; |
| 431 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 432 | let stopResponse: StopTransactionResponse; |
| 433 | if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) { |
| 434 | stopResponse = await this.chargingStation.stopTransactionOnConnector(connectorId, reason); |
| 435 | ++this.connectorsStatus.get(connectorId).stopTransactionRequests; |
| 436 | if (stopResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { |
| 437 | ++this.connectorsStatus.get(connectorId).acceptedStopTransactionRequests; |
| 438 | } else { |
| 439 | ++this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests; |
| 440 | } |
| 441 | } else { |
| 442 | const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId; |
| 443 | logger.warn( |
| 444 | `${this.logPrefix(connectorId)} stopping a not started transaction${ |
| 445 | !Utils.isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : '' |
| 446 | }` |
| 447 | ); |
| 448 | } |
| 449 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 450 | return stopResponse; |
| 451 | } |
| 452 | |
| 453 | private getRequireAuthorize(): boolean { |
| 454 | return ( |
| 455 | this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.requireAuthorize ?? true |
| 456 | ); |
| 457 | } |
| 458 | |
| 459 | private logPrefix = (connectorId?: number): string => { |
| 460 | return Utils.logPrefix( |
| 461 | ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${ |
| 462 | !Utils.isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}` : '' |
| 463 | }:` |
| 464 | ); |
| 465 | }; |
| 466 | |
| 467 | private handleStartTransactionResponse( |
| 468 | connectorId: number, |
| 469 | startResponse: StartTransactionResponse |
| 470 | ): void { |
| 471 | ++this.connectorsStatus.get(connectorId).startTransactionRequests; |
| 472 | if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { |
| 473 | ++this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests; |
| 474 | } else { |
| 475 | logger.warn(`${this.logPrefix(connectorId)} start transaction rejected`); |
| 476 | ++this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests; |
| 477 | } |
| 478 | } |
| 479 | } |