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