-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_api.cpp
More file actions
290 lines (229 loc) · 9.42 KB
/
http_api.cpp
File metadata and controls
290 lines (229 loc) · 9.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <WiFi.h>
#include <SPIFFS.h>
#include "http_api.h"
#include "spiffs_api.h"
#include "download_engine.h"
#include "performance_monitor.h"
#include "network_optimizer.h"
#include "buffer_manager.h"
// Remove this line causing the error:
// extern const uint8_t rootca_crt_bundle_start[] asm("_binary_data_cert_x509_crt_bundle_start");
extern const uint8_t rootca_crt_bundle_end[] asm("_binary_data_cert_x509_crt_bundle_end");
// Global download engine instance - This is the key to high performance.
// It will be created once and reused for all downloads.
static DownloadEngine* globalEngine = nullptr;
// ===== MAIN DOWNLOAD FUNCTION =====
DownloadResult downloadFileToSPIFFS(const String& url, const String& filename) {
DownloadResult result;
if (!validateHttpsUrl(url)) {
result.errorMessage = "Invalid URL: Must use HTTPS protocol";
return result;
}
WiFiClientSecure* client = new WiFiClientSecure;
if (!client) {
result.errorMessage = "Failed to create secure client";
return result;
}
// Replace certificate bundle with setInsecure() for now
client->setInsecure(); // This allows any HTTPS connection
client->setTimeout(HTTP_TIMEOUT / 1000);
HTTPClient https;
if (!https.begin(*client, url)) {
result.errorMessage = "Failed to configure HTTPS client";
delete client;
return result;
}
Serial.println("Starting HTTPS GET request...");
unsigned long startTime = millis();
int httpCode = https.GET();
unsigned long connectTime = millis();
if (httpCode != HTTP_CODE_OK) {
result.errorMessage = "HTTP error code: " + String(httpCode);
https.end();
delete client;
return result;
}
int contentLength = https.getSize();
Serial.println("Content length: " + String(contentLength) + " bytes");
File file = SPIFFS.open(filename, FILE_WRITE);
if (!file) {
result.errorMessage = "Failed to create file: " + filename;
https.end();
delete client;
return result;
}
WiFiClient* stream = https.getStreamPtr();
uint8_t buffer[DOWNLOAD_BUFFER_SIZE];
size_t totalBytesRead = 0;
Serial.println("Starting file download and write...");
while (https.connected() && (contentLength == -1 || totalBytesRead < contentLength)) {
size_t availableData = stream->available();
if (availableData > 0) {
size_t bytesToRead = min(availableData, sizeof(buffer));
size_t bytesRead = stream->readBytes(buffer, bytesToRead);
if (bytesRead > 0) {
size_t bytesWritten = file.write(buffer, bytesRead);
if (bytesWritten != bytesRead) {
result.errorMessage = "File write error at byte " + String(totalBytesRead);
break;
}
totalBytesRead += bytesRead;
if (totalBytesRead % 10240 == 0) {
printDownloadProgress(totalBytesRead, contentLength);
}
}
} else {
delay(1);
}
}
unsigned long endTime = millis();
file.close();
https.end();
delete client;
if (result.errorMessage.length() == 0) {
result.success = true;
result.totalBytes = totalBytesRead;
result.downloadTimeMs = endTime - startTime;
result.connectionSetupMs = connectTime - startTime;
result.transferOnlyMs = endTime - connectTime;
if (result.transferOnlyMs > 0) {
result.pureTransferSpeedKBps = (totalBytesRead / 1024.0) / (result.transferOnlyMs / 1000.0);
}
if (result.downloadTimeMs > 0) {
result.transferEfficiencyPercent = ((float)result.transferOnlyMs / result.downloadTimeMs) * 100.0;
}
Serial.println("\nDownload completed successfully!");
Serial.printf("Speed: %.2f KB/s\n", result.pureTransferSpeedKBps);
}
return result;
}
// ===== ADVANCED DOWNLOAD FUNCTIONS =====
DownloadResult downloadFileWithRetry(const String& url, const String& filename, int maxRetries) {
// CRITICAL FIX: Use the GLOBAL download engine.
if (!globalEngine) {
Serial.println("Error: High-speed download system not initialized.");
DownloadResult result;
result.errorMessage = "Engine not initialized";
return result;
}
return globalEngine->downloadWithRetry(url, filename, maxRetries);
}
DownloadResult downloadFileWithCustomBuffers(const String& url, const String& filename,
size_t downloadBufferSize, size_t writeBufferSize) {
// CRITICAL FIX: Use the GLOBAL download engine.
if (!globalEngine) {
Serial.println("Error: High-speed download system not initialized.");
DownloadResult result;
result.errorMessage = "Engine not initialized";
return result;
}
// This function will now use the global engine's buffers.
// For a true custom buffer implementation, the engine would need a 'reconfigure' method.
globalEngine->setBufferSizes(downloadBufferSize, writeBufferSize);
return globalEngine->downloadToSPIFFS(url, filename);
}
// ===== UTILITY FUNCTIONS =====
bool validateHttpsUrl(const String& url) {
return url.startsWith("https://") && url.length() > 10;
}
void printDownloadProgress(size_t current, size_t total) {
if (total > 0) {
float percentage = (current * 100.0) / total;
Serial.printf("Progress: %d/%d bytes (%.1f%%)\n", current, total, percentage);
} else {
Serial.printf("Downloaded: %d bytes\n", current);
}
}
String httpGet(const String& url) {
WiFiClientSecure* client = new WiFiClientSecure;
if (!client) return "";
client->setInsecure();
HTTPClient https;
https.begin(*client, url);
https.setTimeout(HTTP_TIMEOUT);
int httpCode = https.GET();
String payload;
if (httpCode == HTTP_CODE_OK) {
payload = https.getString();
}
https.end();
delete client;
return payload;
}
// ===== SYSTEM OPTIMIZATION FUNCTIONS =====
bool initializeHighSpeedDownload() {
Serial.println("High-speed download system initialized");
return true;
}
void shutdownHighSpeedDownload() {
Serial.println("Shutting down high-speed download system...");
if (globalEngine) {
destroyDownloadEngine(globalEngine);
globalEngine = nullptr;
}
Serial.println("System shutdown complete");
}
void printSystemConfiguration() {
Serial.println("=== HIGH-SPEED DOWNLOAD SYSTEM CONFIGURATION ===");
// Network configuration
NetworkOptimizer::printNetworkDiagnostics();
// Memory configuration
BufferManager::printMemoryDiagnostics();
// Performance configuration
Serial.println("--- Performance Settings ---");
Serial.println("Target speed: " + String(TARGET_SPEED_KBPS) + " KB/s");
Serial.println("Speed update interval: " + String(SPEED_UPDATE_INTERVAL_MS) + " ms");
Serial.println("Progress update interval: " + String(PROGRESS_UPDATE_INTERVAL_MS) + " ms");
Serial.println("Performance history size: " + String(PERFORMANCE_HISTORY_SIZE));
// Download engine configuration
if (globalEngine) {
globalEngine->printDownloadConfiguration();
} else {
Serial.println("--- Download Engine NOT INITIALIZED ---");
}
Serial.println("================================================");
}
// ===== PERFORMANCE TESTING FUNCTIONS =====
DownloadResult runSpeedTest(const String& testUrl) {
Serial.println("=== RUNNING SPEED TEST ===");
Serial.println("Test URL: " + testUrl);
// Ensure the system is initialized before running a test
if (!initializeHighSpeedDownload()) {
DownloadResult result;
result.errorMessage = "Failed to initialize system for speed test.";
return result;
}
DownloadResult result = downloadFileToSPIFFS(testUrl, "/speedtest.bin");
if (result.success) {
Serial.println("=== SPEED TEST RESULTS ===");
Serial.println("File size: " + PerformanceMonitor::formatBytes(result.totalBytes));
Serial.println("Download time: " + PerformanceMonitor::formatTime(result.downloadTimeMs));
float speedKBps = PerformanceMonitor::calculateSpeedKBps(result.totalBytes, result.downloadTimeMs);
Serial.println("Average speed: " + PerformanceMonitor::formatSpeed(speedKBps));
Serial.println("Target achieved: " + String(speedKBps >= TARGET_SPEED_KBPS ? "YES" : "NO"));
// Clean up test file
if (SPIFFS.exists("/speedtest.bin")) {
SPIFFS.remove("/speedtest.bin");
}
} else {
Serial.println("Speed test failed: " + result.errorMessage);
}
Serial.println("==========================");
return result;
}
void printPerformanceBenchmark() {
Serial.println("=== PERFORMANCE BENCHMARK ===");
String testUrls[] = {
"https://httpbin.org/bytes/102400", // 100KB
"https://httpbin.org/bytes/1048576" // 1MB
};
String testNames[] = {"100KB", "1MB"};
for (int i = 0; i < 2; i++) {
Serial.println("\nTesting " + testNames[i] + " download...");
runSpeedTest(testUrls[i]);
delay(1000); // Brief pause between tests
}
Serial.println("\n==============================");
}