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