| 1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
| 2 | |
| 3 | import { AuthorizationStatus, AuthorizeResponse, StartTransactionResponse, StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction'; |
| 4 | |
| 5 | import ChargingStation from './ChargingStation'; |
| 6 | import Constants from '../utils/Constants'; |
| 7 | import PerformanceStatistics from '../performance/PerformanceStatistics'; |
| 8 | import { Status } from '../types/AutomaticTransactionGenerator'; |
| 9 | import Utils from '../utils/Utils'; |
| 10 | import logger from '../utils/Logger'; |
| 11 | |
| 12 | export default class AutomaticTransactionGenerator { |
| 13 | public started: boolean; |
| 14 | private readonly chargingStation: ChargingStation; |
| 15 | private readonly connectorsStatus: Map<number, Status>; |
| 16 | |
| 17 | constructor(chargingStation: ChargingStation) { |
| 18 | this.chargingStation = chargingStation; |
| 19 | this.connectorsStatus = new Map<number, Status>(); |
| 20 | this.stopConnectors(); |
| 21 | this.started = false; |
| 22 | } |
| 23 | |
| 24 | public start(): void { |
| 25 | if (this.started) { |
| 26 | logger.error(`${this.logPrefix()} trying to start while already started`); |
| 27 | return; |
| 28 | } |
| 29 | this.startConnectors(); |
| 30 | this.started = true; |
| 31 | } |
| 32 | |
| 33 | public stop(): void { |
| 34 | if (!this.started) { |
| 35 | logger.error(`${this.logPrefix()} trying to stop while not started`); |
| 36 | return; |
| 37 | } |
| 38 | this.stopConnectors(); |
| 39 | this.started = false; |
| 40 | } |
| 41 | |
| 42 | private startConnectors(): void { |
| 43 | if (this.connectorsStatus?.size !== 0 && this.connectorsStatus.size !== this.chargingStation.getNumberOfConnectors()) { |
| 44 | this.connectorsStatus.clear(); |
| 45 | } |
| 46 | for (const connectorId of this.chargingStation.connectors.keys()) { |
| 47 | if (connectorId > 0) { |
| 48 | this.startConnector(connectorId); |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | private stopConnectors(): void { |
| 54 | for (const connectorId of this.chargingStation.connectors.keys()) { |
| 55 | if (connectorId > 0) { |
| 56 | this.stopConnector(connectorId); |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | private async internalStartConnector(connectorId: number): Promise<void> { |
| 62 | this.initStartConnectorStatus(connectorId); |
| 63 | logger.info(this.logPrefix(connectorId) + ' started on connector and will run for ' + Utils.formatDurationMilliSeconds(this.connectorsStatus.get(connectorId).stopDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime())); |
| 64 | while (this.connectorsStatus.get(connectorId).start) { |
| 65 | if ((new Date()) > this.connectorsStatus.get(connectorId).stopDate) { |
| 66 | this.stopConnector(connectorId); |
| 67 | break; |
| 68 | } |
| 69 | if (!this.chargingStation.isRegistered()) { |
| 70 | logger.error(this.logPrefix(connectorId) + ' entered in transaction loop while the charging station is not registered'); |
| 71 | this.stopConnector(connectorId); |
| 72 | break; |
| 73 | } |
| 74 | if (!this.chargingStation.isChargingStationAvailable()) { |
| 75 | logger.info(this.logPrefix(connectorId) + ' entered in transaction loop while the charging station is unavailable'); |
| 76 | this.stopConnector(connectorId); |
| 77 | break; |
| 78 | } |
| 79 | if (!this.chargingStation.isConnectorAvailable(connectorId)) { |
| 80 | logger.info(`${this.logPrefix(connectorId)} entered in transaction loop while the connector ${connectorId} is unavailable`); |
| 81 | this.stopConnector(connectorId); |
| 82 | break; |
| 83 | } |
| 84 | if (!this.chargingStation?.ocppRequestService) { |
| 85 | logger.info(`${this.logPrefix(connectorId)} transaction loop waiting for charging station service to be initialized`); |
| 86 | do { |
| 87 | await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME); |
| 88 | } while (!this.chargingStation?.ocppRequestService); |
| 89 | } |
| 90 | const wait = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions, |
| 91 | this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000; |
| 92 | logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait)); |
| 93 | await Utils.sleep(wait); |
| 94 | const start = Utils.secureRandom(); |
| 95 | if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) { |
| 96 | this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0; |
| 97 | // Start transaction |
| 98 | const startResponse = await this.startTransaction(connectorId); |
| 99 | this.connectorsStatus.get(connectorId).startTransactionRequests++; |
| 100 | if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) { |
| 101 | logger.warn(this.logPrefix(connectorId) + ' start transaction rejected'); |
| 102 | this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests++; |
| 103 | } else { |
| 104 | // Wait until end of transaction |
| 105 | const waitTrxEnd = Utils.getRandomInteger(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration, |
| 106 | this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000; |
| 107 | logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnectorStatus(connectorId).transactionId.toString() + ' started and will stop in ' + Utils.formatDurationMilliSeconds(waitTrxEnd)); |
| 108 | this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests++; |
| 109 | await Utils.sleep(waitTrxEnd); |
| 110 | // Stop transaction |
| 111 | logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnectorStatus(connectorId).transactionId.toString()); |
| 112 | await this.stopTransaction(connectorId); |
| 113 | } |
| 114 | } else { |
| 115 | this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions++; |
| 116 | this.connectorsStatus.get(connectorId).skippedTransactions++; |
| 117 | logger.info(this.logPrefix(connectorId) + ' skipped consecutively ' + this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions.toString() + '/' + this.connectorsStatus.get(connectorId).skippedTransactions.toString() + ' transaction(s)'); |
| 118 | } |
| 119 | this.connectorsStatus.get(connectorId).lastRunDate = new Date(); |
| 120 | } |
| 121 | await this.stopTransaction(connectorId); |
| 122 | this.connectorsStatus.get(connectorId).stoppedDate = new Date(); |
| 123 | logger.info(this.logPrefix(connectorId) + ' stopped on connector and lasted for ' + Utils.formatDurationMilliSeconds(this.connectorsStatus.get(connectorId).stoppedDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime())); |
| 124 | logger.debug(`${this.logPrefix(connectorId)} connector status %j`, this.connectorsStatus.get(connectorId)); |
| 125 | } |
| 126 | |
| 127 | private startConnector(connectorId: number): void { |
| 128 | // Avoid hogging the event loop with a busy loop |
| 129 | setImmediate(() => { |
| 130 | this.internalStartConnector(connectorId).catch(() => { /* This is intentional */ }); |
| 131 | }); |
| 132 | } |
| 133 | |
| 134 | private stopConnector(connectorId: number): void { |
| 135 | this.connectorsStatus.set(connectorId, { ...this.connectorsStatus.get(connectorId), start: false }); |
| 136 | } |
| 137 | |
| 138 | private initStartConnectorStatus(connectorId: number): void { |
| 139 | this.connectorsStatus.get(connectorId).authorizeRequests = this?.connectorsStatus.get(connectorId)?.authorizeRequests ?? 0; |
| 140 | this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests = this?.connectorsStatus.get(connectorId)?.acceptedAuthorizeRequests ?? 0; |
| 141 | this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests = this?.connectorsStatus.get(connectorId)?.rejectedAuthorizeRequests ?? 0; |
| 142 | this.connectorsStatus.get(connectorId).startTransactionRequests = this?.connectorsStatus.get(connectorId)?.startTransactionRequests ?? 0; |
| 143 | this.connectorsStatus.get(connectorId).acceptedStartTransactionRequests = this?.connectorsStatus.get(connectorId)?.acceptedStartTransactionRequests ?? 0; |
| 144 | this.connectorsStatus.get(connectorId).rejectedStartTransactionRequests = this?.connectorsStatus.get(connectorId)?.rejectedStartTransactionRequests ?? 0; |
| 145 | this.connectorsStatus.get(connectorId).stopTransactionRequests = this?.connectorsStatus.get(connectorId)?.stopTransactionRequests ?? 0; |
| 146 | this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0; |
| 147 | this.connectorsStatus.get(connectorId).skippedTransactions = this?.connectorsStatus.get(connectorId)?.skippedTransactions ?? 0; |
| 148 | const previousRunDuration = (this?.connectorsStatus.get(connectorId)?.startDate && this?.connectorsStatus.get(connectorId)?.lastRunDate) |
| 149 | ? (this.connectorsStatus.get(connectorId).lastRunDate.getTime() - this.connectorsStatus.get(connectorId).startDate.getTime()) |
| 150 | : 0; |
| 151 | this.connectorsStatus.get(connectorId).startDate = new Date(); |
| 152 | this.connectorsStatus.get(connectorId).stopDate = new Date(this.connectorsStatus.get(connectorId).startDate.getTime() |
| 153 | + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000 |
| 154 | - previousRunDuration); |
| 155 | this.connectorsStatus.get(connectorId).start = true; |
| 156 | } |
| 157 | |
| 158 | private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> { |
| 159 | const measureId = 'StartTransaction with ATG'; |
| 160 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 161 | let startResponse: StartTransactionResponse; |
| 162 | if (this.chargingStation.hasAuthorizedTags()) { |
| 163 | const idTag = this.chargingStation.getRandomIdTag(); |
| 164 | if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) { |
| 165 | // Authorize idTag |
| 166 | const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, idTag); |
| 167 | this.connectorsStatus.get(connectorId).authorizeRequests++; |
| 168 | if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { |
| 169 | this.connectorsStatus.get(connectorId).acceptedAuthorizeRequests++; |
| 170 | logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag); |
| 171 | // Start transaction |
| 172 | startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag); |
| 173 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 174 | return startResponse; |
| 175 | } |
| 176 | this.connectorsStatus.get(connectorId).rejectedAuthorizeRequests++; |
| 177 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 178 | return authorizeResponse; |
| 179 | } |
| 180 | logger.info(this.logPrefix(connectorId) + ' start transaction for idTag ' + idTag); |
| 181 | // Start transaction |
| 182 | startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, idTag); |
| 183 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 184 | return startResponse; |
| 185 | } |
| 186 | logger.info(this.logPrefix(connectorId) + ' start transaction without an idTag'); |
| 187 | startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId); |
| 188 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 189 | return startResponse; |
| 190 | } |
| 191 | |
| 192 | private async stopTransaction(connectorId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> { |
| 193 | const measureId = 'StopTransaction with ATG'; |
| 194 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 195 | let transactionId = 0; |
| 196 | let stopResponse: StopTransactionResponse; |
| 197 | if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) { |
| 198 | transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId; |
| 199 | stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, |
| 200 | this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId), |
| 201 | this.chargingStation.getTransactionIdTag(transactionId), |
| 202 | reason); |
| 203 | this.connectorsStatus.get(connectorId).stopTransactionRequests++; |
| 204 | } else { |
| 205 | logger.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction${transactionId ? ' ' + transactionId.toString() : ''}`); |
| 206 | } |
| 207 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 208 | return stopResponse; |
| 209 | } |
| 210 | |
| 211 | private logPrefix(connectorId?: number): string { |
| 212 | if (connectorId) { |
| 213 | return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG on connector #' + connectorId.toString() + ':'); |
| 214 | } |
| 215 | return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:'); |
| 216 | } |
| 217 | } |