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