Remove uneeded condition on transaction status in ATG
[e-mobility-charging-stations-simulator.git] / src / charging-station / AutomaticTransactionGenerator.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
c0560973 3import { AuthorizationStatus, AuthorizeResponse, StartTransactionResponse, StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction';
6af9012e
JB
4
5import ChargingStation from './ChargingStation';
6import Constants from '../utils/Constants';
a6b3c6c3 7import PerformanceStatistics from '../performance/PerformanceStatistics';
6af9012e
JB
8import Utils from '../utils/Utils';
9import logger from '../utils/Logger';
10
11export default class AutomaticTransactionGenerator {
265e4266 12 public started: boolean;
7d75bee1 13 private startDate!: Date;
265e4266 14 private lastRunDate!: Date;
7d75bee1 15 private stopDate!: Date;
ad2f27c3 16 private chargingStation: ChargingStation;
6af9012e
JB
17
18 constructor(chargingStation: ChargingStation) {
ad2f27c3 19 this.chargingStation = chargingStation;
265e4266 20 this.started = false;
6af9012e
JB
21 }
22
7d75bee1 23 public start(): void {
0045cef5 24 const previousRunDuration = (this?.startDate && this?.lastRunDate) ? (this.lastRunDate.getTime() - this.startDate.getTime()) : 0;
7d75bee1 25 this.startDate = new Date();
0045cef5 26 this.lastRunDate = this.startDate;
58fad749
JB
27 this.stopDate = new Date(this.startDate.getTime()
28 + (this.chargingStation.stationInfo?.AutomaticTransactionGenerator?.stopAfterHours ?? Constants.CHARGING_STATION_ATG_DEFAULT_STOP_AFTER_HOURS) * 3600 * 1000
0045cef5 29 - previousRunDuration);
265e4266 30 this.started = true;
ad2f27c3 31 for (const connector in this.chargingStation.connectors) {
6af9012e 32 if (Utils.convertToInt(connector) > 0) {
7d75bee1
JB
33 // Avoid hogging the event loop with a busy loop
34 setImmediate(() => {
35 this.startOnConnector(Utils.convertToInt(connector)).catch(() => { /* This is intentional */ });
36 });
6af9012e
JB
37 }
38 }
d7d1db72 39 logger.info(this.logPrefix() + ' started and will run for ' + Utils.formatDurationMilliSeconds(this.stopDate.getTime() - this.startDate.getTime()));
6af9012e
JB
40 }
41
0045cef5 42 public stop(): void {
265e4266
JB
43 if (!this.started) {
44 logger.error(`${this.logPrefix()} trying to stop while not started`);
45 return;
46 }
265e4266 47 this.started = false;
0045cef5 48 logger.info(`${this.logPrefix()} over and lasted for ${Utils.formatDurationMilliSeconds(this.lastRunDate.getTime() - this.startDate.getTime())}. Stopping all transactions`);
6af9012e
JB
49 }
50
7d75bee1
JB
51 private async startOnConnector(connectorId: number): Promise<void> {
52 logger.info(this.logPrefix(connectorId) + ' started on connector');
b322b8b4
JB
53 let skippedTransactions = 0;
54 let skippedTransactionsTotal = 0;
265e4266 55 while (this.started) {
7d75bee1 56 if ((new Date()) > this.stopDate) {
0045cef5 57 this.stop();
17991e8c
JB
58 break;
59 }
c0560973
JB
60 if (!this.chargingStation.isRegistered()) {
61 logger.error(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is not registered');
17991e8c
JB
62 break;
63 }
c0560973
JB
64 if (!this.chargingStation.isChargingStationAvailable()) {
65 logger.info(this.logPrefix(connectorId) + ' Entered in transaction loop while the charging station is unavailable');
0045cef5 66 this.stop();
ab5f4b03
JB
67 break;
68 }
c0560973
JB
69 if (!this.chargingStation.isConnectorAvailable(connectorId)) {
70 logger.info(`${this.logPrefix(connectorId)} Entered in transaction loop while the connector ${connectorId} is unavailable, stop it`);
17991e8c
JB
71 break;
72 }
c0560973
JB
73 if (!this.chargingStation?.ocppRequestService) {
74 logger.info(`${this.logPrefix(connectorId)} Transaction loop waiting for charging station service to be initialized`);
75 do {
a4cc42ea 76 await Utils.sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME);
c0560973
JB
77 } while (!this.chargingStation?.ocppRequestService);
78 }
ad2f27c3
JB
79 const wait = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDelayBetweenTwoTransactions,
80 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDelayBetweenTwoTransactions) * 1000;
d7d1db72 81 logger.info(this.logPrefix(connectorId) + ' waiting for ' + Utils.formatDurationMilliSeconds(wait));
6af9012e 82 await Utils.sleep(wait);
c37528f1 83 const start = Utils.secureRandom();
ad2f27c3 84 if (start < this.chargingStation.stationInfo.AutomaticTransactionGenerator.probabilityOfStart) {
b322b8b4 85 skippedTransactions = 0;
6af9012e 86 // Start transaction
aef1b33a 87 const startResponse = await this.startTransaction(connectorId);
ef6076c1 88 if (startResponse?.idTagInfo?.status !== AuthorizationStatus.ACCEPTED) {
54b1efe0 89 logger.warn(this.logPrefix(connectorId) + ' transaction rejected');
6af9012e
JB
90 await Utils.sleep(Constants.CHARGING_STATION_ATG_WAIT_TIME);
91 } else {
92 // Wait until end of transaction
ad2f27c3
JB
93 const waitTrxEnd = Utils.getRandomInt(this.chargingStation.stationInfo.AutomaticTransactionGenerator.maxDuration,
94 this.chargingStation.stationInfo.AutomaticTransactionGenerator.minDuration) * 1000;
d7d1db72 95 logger.info(this.logPrefix(connectorId) + ' transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString() + ' will stop in ' + Utils.formatDurationMilliSeconds(waitTrxEnd));
6af9012e
JB
96 await Utils.sleep(waitTrxEnd);
97 // Stop transaction
85d20667
JB
98 logger.info(this.logPrefix(connectorId) + ' stop transaction ' + this.chargingStation.getConnector(connectorId).transactionId.toString());
99 await this.stopTransaction(connectorId);
6af9012e
JB
100 }
101 } else {
b322b8b4
JB
102 skippedTransactions++;
103 skippedTransactionsTotal++;
104 logger.info(this.logPrefix(connectorId) + ' skipped transaction ' + skippedTransactions.toString() + '/' + skippedTransactionsTotal.toString());
6af9012e 105 }
265e4266 106 this.lastRunDate = new Date();
7d75bee1 107 }
0045cef5 108 await this.stopTransaction(connectorId);
7d75bee1 109 logger.info(this.logPrefix(connectorId) + ' stopped on connector');
6af9012e
JB
110 }
111
aef1b33a
JB
112 private async startTransaction(connectorId: number): Promise<StartTransactionResponse | AuthorizeResponse> {
113 const measureId = 'StartTransaction with ATG';
114 const beginId = PerformanceStatistics.beginMeasure(measureId);
115 let startResponse: StartTransactionResponse;
116 if (this.chargingStation.hasAuthorizedTags()) {
117 const tagId = this.chargingStation.getRandomTagId();
118 if (this.chargingStation.getAutomaticTransactionGeneratorRequireAuthorize()) {
5fdab605 119 // Authorize tagId
aef1b33a 120 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(connectorId, tagId);
5fdab605 121 if (authorizeResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
aef1b33a 122 logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
5fdab605 123 // Start transaction
aef1b33a
JB
124 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
125 PerformanceStatistics.endMeasure(measureId, beginId);
126 return startResponse;
5fdab605 127 }
aef1b33a 128 PerformanceStatistics.endMeasure(measureId, beginId);
4faad557 129 return authorizeResponse;
ef6076c1 130 }
aef1b33a 131 logger.info(this.logPrefix(connectorId) + ' start transaction for tagID ' + tagId);
5fdab605 132 // Start transaction
aef1b33a
JB
133 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId, tagId);
134 PerformanceStatistics.endMeasure(measureId, beginId);
135 return startResponse;
6af9012e 136 }
aef1b33a
JB
137 logger.info(this.logPrefix(connectorId) + ' start transaction without a tagID');
138 startResponse = await this.chargingStation.ocppRequestService.sendStartTransaction(connectorId);
139 PerformanceStatistics.endMeasure(measureId, beginId);
140 return startResponse;
6af9012e
JB
141 }
142
0045cef5 143 private async stopTransaction(connectorId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
aef1b33a
JB
144 const measureId = 'StopTransaction with ATG';
145 const beginId = PerformanceStatistics.beginMeasure(measureId);
146 const transactionId = this.chargingStation.getConnector(connectorId).transactionId;
0045cef5
JB
147 let stopResponse: StopTransactionResponse;
148 if (this.chargingStation.getConnector(connectorId)?.transactionStarted) {
149 stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
150 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
151 this.chargingStation.getTransactionIdTag(transactionId),
152 reason);
153 } else {
154 logger.warn(`${this.logPrefix(connectorId)} trying to stop a not started transaction ${transactionId}`);
155 }
aef1b33a
JB
156 PerformanceStatistics.endMeasure(measureId, beginId);
157 return stopResponse;
c0560973
JB
158 }
159
6e0964c8 160 private logPrefix(connectorId?: number): string {
c0560973 161 if (connectorId) {
54b1efe0 162 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG on connector #' + connectorId.toString() + ':');
c0560973 163 }
54b1efe0 164 return Utils.logPrefix(' ' + this.chargingStation.stationInfo.chargingStationId + ' | ATG:');
6af9012e
JB
165 }
166}