@geastack/host 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +25 -0
  3. package/audio_runtime.cpp +807 -0
  4. package/bluetooth.cpp +125 -0
  5. package/geolocation.cpp +43 -0
  6. package/host/apps.cpp +20 -0
  7. package/host/audio.cpp +240 -0
  8. package/host/ble.cpp +239 -0
  9. package/host/camera.cpp +193 -0
  10. package/host/display.cpp +230 -0
  11. package/host/fetch.cpp +1060 -0
  12. package/host/geolocation.cpp +31 -0
  13. package/host/gpio.cpp +55 -0
  14. package/host/http.cpp +349 -0
  15. package/host/image.cpp +335 -0
  16. package/host/imu.cpp +51 -0
  17. package/host/input.cpp +12 -0
  18. package/host/media.cpp +579 -0
  19. package/host/memory.cpp +91 -0
  20. package/host/rtc.cpp +212 -0
  21. package/host/rtc_esp.cpp +291 -0
  22. package/host/tile_loader.cpp +478 -0
  23. package/host/timers.cpp +327 -0
  24. package/host/touch.cpp +25 -0
  25. package/host/websocket.cpp +279 -0
  26. package/host/wifi.cpp +99 -0
  27. package/include/gea/embedded-host.h +38 -0
  28. package/include/host/apps.h +15 -0
  29. package/include/host/audio.h +158 -0
  30. package/include/host/backends.h +455 -0
  31. package/include/host/battery.h +25 -0
  32. package/include/host/camera.h +236 -0
  33. package/include/host/clock.h +45 -0
  34. package/include/host/device_control.h +23 -0
  35. package/include/host/display.h +266 -0
  36. package/include/host/display_orientation.h +291 -0
  37. package/include/host/fetch.h +310 -0
  38. package/include/host/gpio.h +36 -0
  39. package/include/host/http.h +161 -0
  40. package/include/host/image.h +144 -0
  41. package/include/host/input.h +14 -0
  42. package/include/host/media.h +165 -0
  43. package/include/host/memory.h +44 -0
  44. package/include/host/navigator.h +283 -0
  45. package/include/host/notify.h +41 -0
  46. package/include/host/profiler.h +49 -0
  47. package/include/host/rtc.h +174 -0
  48. package/include/host/storage.h +141 -0
  49. package/include/host/tile_loader.h +59 -0
  50. package/include/host/timers.h +41 -0
  51. package/include/host/touch.h +20 -0
  52. package/include/host/websocket.h +179 -0
  53. package/include/host/window.h +31 -0
  54. package/input.cpp +68 -0
  55. package/package.json +27 -0
  56. package/services/app_state.cpp +19 -0
  57. package/services/battery_service.cpp +19 -0
  58. package/services/bluetooth_service.cpp +37 -0
  59. package/services/diagnostics.cpp +233 -0
  60. package/services/diagnostics_connection.cpp +231 -0
  61. package/services/diagnostics_internal.h +15 -0
  62. package/services/diagnostics_server.cpp +135 -0
  63. package/services/mirror.cpp +364 -0
  64. package/services/network_services.cpp +62 -0
  65. package/services/runtime_log.cpp +23 -0
  66. package/services/settings_surface.h +221 -0
  67. package/wifi.cpp +185 -0
package/host/fetch.cpp ADDED
@@ -0,0 +1,1060 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #ifdef GEA_CPP_VALUE_AVAILABLE
3
+ #define GEA_FETCH_RESTORE_CPP_VALUE_AVAILABLE 1
4
+ #undef GEA_CPP_VALUE_AVAILABLE
5
+ #endif
6
+ #include "host/fetch.h"
7
+ #ifdef GEA_FETCH_RESTORE_CPP_VALUE_AVAILABLE
8
+ #define GEA_CPP_VALUE_AVAILABLE 1
9
+ #undef GEA_FETCH_RESTORE_CPP_VALUE_AVAILABLE
10
+ #endif
11
+
12
+ #include <cstdint>
13
+ #include <cstring>
14
+ #include <map>
15
+ #include <memory>
16
+ #include <mutex>
17
+
18
+ #ifdef __EMSCRIPTEN__
19
+ #include <emscripten/em_js.h>
20
+ #endif
21
+
22
+ #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
23
+
24
+ #include "gea/embedded-host.h"
25
+ #include "memory.h"
26
+ #include "wifi.h"
27
+
28
+ #include "esp_http_client.h"
29
+ #include "esp_log.h"
30
+ #include "esp_heap_caps.h"
31
+ #include "esp_timer.h"
32
+ #include "esp_tls.h"
33
+ #include "freertos/FreeRTOS.h"
34
+ #include "freertos/idf_additions.h"
35
+ #include "freertos/task.h"
36
+ #if GEA_EMBEDDED_ENABLE_HTTPS
37
+ #include "esp_crt_bundle.h"
38
+ #endif
39
+
40
+ #include <algorithm>
41
+ #include <cctype>
42
+ #include <cerrno>
43
+ #include <cstdio>
44
+ #include <cstdlib>
45
+ #include <string>
46
+
47
+ namespace gea::framework::host {
48
+
49
+ namespace {
50
+
51
+ // Keep-alive connection cache, ONE PER TASK (thread_local): each caller —
52
+ // the frame task, each async tile-loader worker — keeps its own
53
+ // esp_http_client, so sequential requests to the same scheme://host[:port]
54
+ // pay the TCP + TLS handshake once, while different tasks fetch fully in
55
+ // PARALLEL (no shared handle, no serializing mutex; esp_http_client handles
56
+ // are not thread-safe, which per-task ownership sidesteps entirely).
57
+ thread_local esp_http_client_handle_t g_client = nullptr;
58
+ thread_local std::string g_client_origin;
59
+ thread_local std::int64_t g_client_last_use_us = 0;
60
+
61
+ std::string originOf(const std::string &url) {
62
+ const std::size_t scheme = url.find("://");
63
+ if (scheme == std::string::npos) return url;
64
+ const std::size_t path = url.find('/', scheme + 3);
65
+ return path == std::string::npos ? url : url.substr(0, path);
66
+ }
67
+
68
+ void dropCachedClient() {
69
+ if (g_client) {
70
+ esp_http_client_cleanup(g_client); // closes the socket + frees the handle
71
+ g_client = nullptr;
72
+ }
73
+ g_client_origin.clear();
74
+ }
75
+
76
+ // Connection reuse (keep-alive) only works through esp_http_client_perform(),
77
+ // which delivers the body in chunks via HTTP_EVENT_ON_DATA. This accumulator
78
+ // collects those chunks. It is thread_local like the client: the event handler
79
+ // runs synchronously inside perform() on the calling task, so each task's
80
+ // accumulator only ever sees its own request.
81
+ struct BodyAccumulator {
82
+ static constexpr std::size_t kMaxBytes = 2u * 1024u * 1024u;
83
+ std::uint8_t *buffer = nullptr;
84
+ std::size_t capacity = 0;
85
+ std::size_t size = 0;
86
+
87
+ void reset() { size = 0; } // keep the buffer allocated for reuse across tiles
88
+
89
+ void append(const char *data, int len) {
90
+ if (len <= 0) return;
91
+ std::size_t need = size + static_cast<std::size_t>(len);
92
+ if (need > kMaxBytes) need = kMaxBytes;
93
+ if (need > capacity) {
94
+ std::size_t next = capacity ? capacity : 4096;
95
+ while (next < need) next *= 2;
96
+ if (next > kMaxBytes) next = kMaxBytes;
97
+ auto *grown = static_cast<std::uint8_t *>(
98
+ gea::framework::memory::Allocator::reallocatePreferSpiram(buffer, next));
99
+ if (!grown) return; // realloc failed — keep what we have
100
+ buffer = grown;
101
+ capacity = next;
102
+ }
103
+ const std::size_t room = capacity - size;
104
+ const std::size_t take = static_cast<std::size_t>(len) < room ? static_cast<std::size_t>(len) : room;
105
+ std::memcpy(buffer + size, data, take);
106
+ size += take;
107
+ }
108
+ };
109
+
110
+ thread_local BodyAccumulator g_body;
111
+
112
+ esp_err_t onHttpEvent(esp_http_client_event_t *evt) {
113
+ if (evt->event_id == HTTP_EVENT_ON_DATA && evt->data_len > 0) {
114
+ g_body.append(static_cast<const char *>(evt->data), evt->data_len);
115
+ }
116
+ return ESP_OK;
117
+ }
118
+
119
+ } // namespace
120
+
121
+ class FetchResponseBuilder {
122
+ public:
123
+ static constexpr std::size_t max_body_bytes = 2u * 1024u * 1024u;
124
+ static constexpr std::size_t initial_body_capacity = 4096;
125
+ static constexpr int timeout_ms = 30000;
126
+
127
+ FetchResponseBuilder(const std::string &url, const gea::host::FetchRequestInit &init)
128
+ : url_(url), init_(init) {}
129
+
130
+ gea::host::FetchResponse get() const {
131
+ gea::host::FetchResponse result{};
132
+ result.ok = false;
133
+ result.status = 0;
134
+
135
+ // WiFi/lwip is opt-in and only initialized during deferred WiFi bring-up
136
+ // (see docs/esp32-connectivity-and-ram.md). Calling esp_http_client before
137
+ // the TCP/IP stack is up triggers an lwip "Invalid mbox" assert that panics
138
+ // and reboots the whole device. Bail with a normal failed response instead,
139
+ // matching browser semantics where fetch rejects on network failure.
140
+ if (!gea::framework::network::wifi().connected()) {
141
+ ESP_LOGW(logTag(), "fetch(%s) skipped: WiFi not connected", url_.c_str());
142
+ return result;
143
+ }
144
+
145
+ // Acquire THIS TASK's connection: reuse the thread-local keep-alive client
146
+ // when the origin matches (skips the handshake), otherwise (re)create it.
147
+ // Keep-alive reuse requires esp_http_client_perform() (the manual open/read
148
+ // API always opens a fresh socket and never reuses), so the body arrives
149
+ // via onHttpEvent into the thread-local accumulator. No locking: every
150
+ // task owns its own client + accumulator, so fetches run in parallel.
151
+ g_body.reset();
152
+ const std::string origin = originOf(url_);
153
+ static std::mutex s_handshake_gate;
154
+ // Reuse the parked connection only while it's plausibly still open on the
155
+ // server side. Most servers (open-meteo's nginx front included) drop idle
156
+ // keep-alive sockets after a few seconds, and esp_http_client_perform() on
157
+ // a dead socket can block for up to the timeout before failing. Outside the
158
+ // window we reconnect proactively instead of gambling on the stall; inside
159
+ // it, ms-apart tile bursts ride the warm connection.
160
+ constexpr std::int64_t kReuseWindowUs = 8 * 1000 * 1000;
161
+ bool reuse = g_client && g_client_origin == origin &&
162
+ (esp_timer_get_time() - g_client_last_use_us) < kReuseWindowUs;
163
+ // Per-request timeout: callers (e.g. the tile loader) set a short timeout so
164
+ // a transient WiFi/TCP stall fails fast and is retried on a fresh socket,
165
+ // instead of waiting out lwip's multi-RTO retransmit (~15s). Default callers
166
+ // (weather, nominatim) leave it 0 and keep the full timeout_ms.
167
+ const int effective_timeout_ms = init_.timeout_ms > 0 ? init_.timeout_ms : timeout_ms;
168
+
169
+ for (int attempt = 0; attempt < 2; ++attempt) {
170
+ // Serialize COLD connections only: a TLS handshake needs ~50KB of INTERNAL
171
+ // ram (mbedTLS), and two at once during a tile burst exhausted the heap
172
+ // (operator-new abort on zoom-out). A request riding an already-warm
173
+ // keep-alive connection skips the gate entirely, so parallel tile
174
+ // downloads stay parallel after each worker's first fetch.
175
+ std::unique_lock<std::mutex> handshake_lock(s_handshake_gate, std::defer_lock);
176
+ if (!reuse) handshake_lock.lock();
177
+ esp_http_client_handle_t client = nullptr;
178
+ if (reuse) {
179
+ client = g_client;
180
+ esp_http_client_set_url(client, url_.c_str());
181
+ esp_http_client_set_method(client, methodFromInit());
182
+ // Apply the per-request timeout to the reused socket too, so a stalled
183
+ // reuse fails fast and the retry below re-inits a fresh connection.
184
+ esp_http_client_set_timeout_ms(client, effective_timeout_ms);
185
+ } else {
186
+ dropCachedClient();
187
+ esp_http_client_config_t config = {};
188
+ config.url = url_.c_str();
189
+ config.timeout_ms = effective_timeout_ms;
190
+ config.method = methodFromInit();
191
+ config.keep_alive_enable = true;
192
+ config.event_handler = onHttpEvent;
193
+ config.user_data = &g_body;
194
+ #if GEA_EMBEDDED_ENABLE_HTTPS
195
+ config.crt_bundle_attach = esp_crt_bundle_attach;
196
+ #endif
197
+ client = esp_http_client_init(&config);
198
+ if (!client) {
199
+ ESP_LOGE(logTag(), "init failed for %s", url_.c_str());
200
+ return result;
201
+ }
202
+ g_client = client;
203
+ g_client_origin = origin;
204
+ }
205
+
206
+ // OSM's tile usage policy (and other policy-bound APIs) throttle or block
207
+ // the generic esp_http_client default User-Agent ("ESP32 HTTP Client/1.0"),
208
+ // which manifests as intermittent multi-second tarpitted responses. Send an
209
+ // identifying UA on every request; caller headers below may override it.
210
+ esp_http_client_set_header(client, "User-Agent", "gea-embedded/1.0");
211
+ for (const auto &kv : init_.headers) {
212
+ esp_http_client_set_header(client, kv.first.c_str(), kv.second.c_str());
213
+ }
214
+ if (!init_.body.empty()) {
215
+ esp_http_client_set_post_field(client, reinterpret_cast<const char *>(init_.body.data()),
216
+ static_cast<int>(init_.body.size()));
217
+ }
218
+
219
+ const esp_err_t err = esp_http_client_perform(client);
220
+ if (err != ESP_OK) {
221
+ ESP_LOGE(logTag(), "perform failed for %s: %s%s", url_.c_str(), esp_err_to_name(err),
222
+ reuse ? " (reused connection went stale; retrying on a fresh one)" : "");
223
+ dropCachedClient();
224
+ if (reuse) {
225
+ // The parked socket died inside the reuse window — retry exactly once
226
+ // on a fresh connection so a server-side early close doesn't surface
227
+ // as a failed fetch to the app.
228
+ reuse = false;
229
+ g_body.reset();
230
+ continue;
231
+ }
232
+ return result;
233
+ }
234
+ g_client_last_use_us = esp_timer_get_time();
235
+
236
+ result.status = static_cast<double>(esp_http_client_get_status_code(client));
237
+ readResponseHeaders(result, client);
238
+ result.body.assign(g_body.buffer, g_body.buffer + g_body.size);
239
+ // No close/cleanup: keep_alive_enable parks the connection for the next
240
+ // same-origin request. dropCachedClient() runs on origin change or error.
241
+
242
+ result.ok = result.status >= 200.0 && result.status < 300.0;
243
+ ESP_LOGI(logTag(), "%s %s -> %.0f %u bytes", init_.method.c_str(), url_.c_str(), result.status,
244
+ static_cast<unsigned>(result.body.size()));
245
+ return result;
246
+ }
247
+ return result;
248
+ }
249
+
250
+ private:
251
+ esp_http_client_method_t methodFromInit() const {
252
+ const std::string &m = init_.method;
253
+ if (m == "POST") return HTTP_METHOD_POST;
254
+ if (m == "PUT") return HTTP_METHOD_PUT;
255
+ if (m == "DELETE") return HTTP_METHOD_DELETE;
256
+ if (m == "PATCH") return HTTP_METHOD_PATCH;
257
+ if (m == "HEAD") return HTTP_METHOD_HEAD;
258
+ return HTTP_METHOD_GET;
259
+ }
260
+
261
+ static const char *logTag() {
262
+ return "gea::host::fetch";
263
+ }
264
+
265
+ static std::string lowercase(const std::string &s) {
266
+ std::string out(s.size(), '\0');
267
+ std::transform(s.begin(), s.end(), out.begin(), [](unsigned char c) { return std::tolower(c); });
268
+ return out;
269
+ }
270
+
271
+ static void readResponseHeaders(gea::host::FetchResponse &result, esp_http_client_handle_t client) {
272
+ // esp_http_client doesn't expose a header iterator; sniff the common ones explicitly.
273
+ // Keys are stored lowercased for browser-parity case-insensitive lookup.
274
+ static constexpr const char *common_headers[] = {
275
+ "content-type", "content-length", "set-cookie", "location",
276
+ "www-authenticate", "cache-control",
277
+ };
278
+ for (const char *name : common_headers) {
279
+ char *value = nullptr;
280
+ if (esp_http_client_get_header(client, name, &value) == ESP_OK && value != nullptr) {
281
+ result.headers[lowercase(name)] = value;
282
+ }
283
+ }
284
+ }
285
+
286
+ static void *allocate(std::size_t size) {
287
+ return gea::framework::memory::Allocator::allocatePreferSpiram(size);
288
+ }
289
+
290
+ static void *reallocate(void *ptr, std::size_t size) {
291
+ return gea::framework::memory::Allocator::reallocatePreferSpiram(ptr, size);
292
+ }
293
+
294
+ static std::size_t initialCapacity(int content_length) {
295
+ std::size_t capacity = content_length > 0 ? static_cast<std::size_t>(content_length) : initial_body_capacity;
296
+ return capacity > max_body_bytes ? max_body_bytes : capacity;
297
+ }
298
+
299
+ static bool grow(std::uint8_t *&buffer, std::size_t &capacity) {
300
+ std::size_t next_capacity = capacity * 2u;
301
+ if (next_capacity > max_body_bytes) next_capacity = max_body_bytes;
302
+ if (next_capacity <= capacity) return false;
303
+
304
+ auto *grown = static_cast<std::uint8_t *>(reallocate(buffer, next_capacity));
305
+ if (!grown) {
306
+ ESP_LOGW(logTag(), "realloc(%u) failed; truncating", static_cast<unsigned>(next_capacity));
307
+ return false;
308
+ }
309
+
310
+ buffer = grown;
311
+ capacity = next_capacity;
312
+ return true;
313
+ }
314
+
315
+ static void readInto(gea::host::FetchResponse &result, esp_http_client_handle_t client) {
316
+ const int content_length = esp_http_client_fetch_headers(client);
317
+ result.status = static_cast<double>(esp_http_client_get_status_code(client));
318
+
319
+ std::size_t capacity = initialCapacity(content_length);
320
+ std::uint8_t *buffer = static_cast<std::uint8_t *>(allocate(capacity));
321
+ if (!buffer) {
322
+ ESP_LOGE(logTag(), "body allocation failed (%u bytes)", static_cast<unsigned>(capacity));
323
+ return;
324
+ }
325
+
326
+ std::size_t total = 0;
327
+ while (total < max_body_bytes) {
328
+ if (total == capacity && !grow(buffer, capacity)) break;
329
+
330
+ const int to_read = static_cast<int>(capacity - total);
331
+ const int read_len = esp_http_client_read(client, reinterpret_cast<char *>(buffer) + total, to_read);
332
+ if (read_len <= 0) {
333
+ break;
334
+ }
335
+ total += static_cast<std::size_t>(read_len);
336
+ }
337
+
338
+ result.body.assign(buffer, buffer + total);
339
+ gea::framework::memory::Allocator::free(buffer);
340
+ }
341
+
342
+ const std::string &url_;
343
+ const gea::host::FetchRequestInit &init_;
344
+ };
345
+
346
+ class FetchHost {
347
+ public:
348
+ static gea::host::FetchResponse fetch(const std::string &url) {
349
+ return fetch(url, gea::host::FetchRequestInit{});
350
+ }
351
+ static gea::host::FetchResponse fetch(const std::string &url, const gea::host::FetchRequestInit &init) {
352
+ return FetchResponseBuilder(url, init).get();
353
+ }
354
+ };
355
+
356
+ // Streaming multipart upload over a RAW TLS socket (esp_tls), NOT esp_http_client:
357
+ // its manual open/write streaming-POST path leaves the socket stuck in EINPROGRESS
358
+ // on this IDF/board (every write poll-fails "Connection already in progress"). This
359
+ // mirrors the proven pala_note reference (WiFiClientSecure): connect, write the
360
+ // request line + headers + `prefix` + the file streamed in 4 KB chunks off disk +
361
+ // `suffix`, then read + de-chunk the response. The file never sits in RAM.
362
+ class UploadStreamer {
363
+ public:
364
+ // Write all `len` bytes, tolerating partial writes and TLS WANT_READ/WANT_WRITE
365
+ // (slow link) by briefly waiting and retrying. False only after a long stall.
366
+ static bool tlsWriteAll(esp_tls_t *tls, const char *data, std::size_t len) {
367
+ std::size_t sent = 0;
368
+ int stalls = 0;
369
+ while (sent < len) {
370
+ const ssize_t w = esp_tls_conn_write(tls, data + sent, len - sent);
371
+ if (w > 0) {
372
+ sent += static_cast<std::size_t>(w);
373
+ stalls = 0;
374
+ continue;
375
+ }
376
+ if (w == ESP_TLS_ERR_SSL_WANT_WRITE || w == ESP_TLS_ERR_SSL_WANT_READ || w == 0) {
377
+ if (++stalls > 6000) {
378
+ std::printf("[upload-diag] write STALL-timeout sent=%u internal_free=%u\n",
379
+ static_cast<unsigned>(sent),
380
+ static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
381
+ return false; // ~60 s with no progress -> give up
382
+ }
383
+ vTaskDelay(pdMS_TO_TICKS(10));
384
+ continue;
385
+ }
386
+ std::printf("[upload-diag] write HARD-ERR esp_tls=%d (-0x%04X) sent=%u internal_free=%u\n",
387
+ static_cast<int>(w), static_cast<unsigned>(-w), static_cast<unsigned>(sent),
388
+ static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
389
+ return false; // hard TLS/socket error
390
+ }
391
+ return true;
392
+ }
393
+
394
+ // Strip HTTP/1.1 chunked transfer-encoding framing from a body (raw TLS gives
395
+ // us the framing that esp_http_client would otherwise remove).
396
+ static std::string dechunk(const std::string &body) {
397
+ std::string out;
398
+ std::size_t i = 0;
399
+ while (i < body.size()) {
400
+ const std::size_t eol = body.find("\r\n", i);
401
+ if (eol == std::string::npos) break;
402
+ const long size = std::strtol(body.substr(i, eol - i).c_str(), nullptr, 16);
403
+ if (size <= 0) break;
404
+ const std::size_t start = eol + 2;
405
+ if (start + static_cast<std::size_t>(size) > body.size()) {
406
+ out.append(body, start, body.size() - start);
407
+ break;
408
+ }
409
+ out.append(body, start, static_cast<std::size_t>(size));
410
+ i = start + static_cast<std::size_t>(size) + 2; // skip chunk + trailing CRLF
411
+ }
412
+ return out;
413
+ }
414
+
415
+ static gea::host::FetchResponse upload(const std::string &url, const std::string &authorization,
416
+ const std::string &contentType, const std::string &prefix,
417
+ const std::string &filePath, const std::string &suffix) {
418
+ gea::host::FetchResponse result{};
419
+ result.ok = false;
420
+ result.status = 0;
421
+ if (!gea::framework::network::wifi().connected()) {
422
+ ESP_LOGW("gea::host::fetch", "uploadFile(%s) skipped: WiFi not connected", url.c_str());
423
+ result.status = -10; // WiFi link down (e.g. dropped during a prior upload)
424
+ return result;
425
+ }
426
+
427
+ // Split url -> host + path (https://host/path...).
428
+ const std::size_t scheme = url.find("://");
429
+ const std::size_t hostStart = scheme == std::string::npos ? 0 : scheme + 3;
430
+ const std::size_t pathStart = url.find('/', hostStart);
431
+ const std::string host =
432
+ url.substr(hostStart, pathStart == std::string::npos ? std::string::npos : pathStart - hostStart);
433
+ const std::string path = pathStart == std::string::npos ? "/" : url.substr(pathStart);
434
+
435
+ FILE *f = std::fopen(filePath.c_str(), "rb");
436
+ if (!f) {
437
+ ESP_LOGE("gea::host::fetch", "uploadFile: cannot open %s", filePath.c_str());
438
+ result.status = -11; // SD open failed
439
+ return result;
440
+ }
441
+ std::fseek(f, 0, SEEK_END);
442
+ const long fileSize = std::ftell(f);
443
+ std::fseek(f, 0, SEEK_SET);
444
+ if (fileSize < 0) {
445
+ std::fclose(f);
446
+ return result;
447
+ }
448
+ const long contentLength =
449
+ static_cast<long>(prefix.size()) + fileSize + static_cast<long>(suffix.size());
450
+ // Reset progress to this upload's body size so the Sync screen bar reflects
451
+ // bytes streamed (prefix + file + suffix). The HTTP head is tiny and not
452
+ // counted. One upload runs at a time, so a single global counter suffices.
453
+ gea::host::uploadProgressReset(contentLength);
454
+
455
+ esp_tls_cfg_t cfg = {};
456
+ #if GEA_EMBEDDED_ENABLE_HTTPS
457
+ cfg.crt_bundle_attach = esp_crt_bundle_attach;
458
+ #endif
459
+ cfg.timeout_ms = 300000;
460
+ esp_tls_t *tls = esp_tls_init();
461
+ if (!tls) {
462
+ std::fclose(f);
463
+ return result;
464
+ }
465
+ if (esp_tls_conn_new_sync(host.c_str(), static_cast<int>(host.size()), 443, &cfg, tls) != 1) {
466
+ ESP_LOGE("gea::host::fetch", "uploadFile: TLS connect to %s failed", host.c_str());
467
+ esp_tls_conn_destroy(tls);
468
+ std::fclose(f);
469
+ result.status = -12; // TLS/TCP connect failed (link up but couldn't reach host)
470
+ return result;
471
+ }
472
+
473
+ std::string head = "POST " + path + " HTTP/1.1\r\nHost: " + host + "\r\n";
474
+ // Match the headers esp_http_client sends automatically — OpenAI/Cloudflare
475
+ // can reject a request that omits User-Agent/Accept.
476
+ head += "User-Agent: gea-embedded/1.0\r\nAccept: */*\r\n";
477
+ if (!authorization.empty()) head += "Authorization: " + authorization + "\r\n";
478
+ if (!contentType.empty()) head += "Content-Type: " + contentType + "\r\n";
479
+ head += "Content-Length: " + std::to_string(contentLength) + "\r\nConnection: close\r\n\r\n";
480
+
481
+ bool writeOk = tlsWriteAll(tls, head.data(), head.size()) &&
482
+ (prefix.empty() || tlsWriteAll(tls, prefix.data(), prefix.size()));
483
+ if (writeOk && !prefix.empty()) gea::host::uploadProgressAdd(static_cast<long long>(prefix.size()));
484
+ long bytesStreamed = 0;
485
+ // Diagnostic failure code surfaced as result.status (negative) so the Sync
486
+ // screen distinguishes WHY the body write failed without needing serial:
487
+ // -7 = buffer alloc, -8 = SD short-read (RAM/SD), -9 = TLS/socket write error.
488
+ int failKind = 0;
489
+ if (writeOk) {
490
+ // Read SD -> a DMA-capable INTERNAL buffer so the SDMMC driver streams
491
+ // directly into it. A PSRAM (or otherwise non-DMA) read target forces
492
+ // sdmmc to allocate a same-sized internal bounce buffer PER read. With
493
+ // WiFi up, internal DMA RAM is nearly exhausted (a few KB free) and
494
+ // fragments under sustained TLS load, so a large bounce alloc fails
495
+ // partway through a multi-MB upload (allocate_dma_buf NO_MEM); fread then
496
+ // returns 0 (indistinguishable from EOF) and we ship a body shorter than
497
+ // Content-Length -> the server waits for the rest -> no response ->
498
+ // "upload HTTP 0", consistently near the end. One small persistent
499
+ // internal buffer (read straight into it, no bounce) avoids that.
500
+ constexpr std::size_t kUploadChunk = 2048;
501
+ char *buffer = static_cast<char *>(heap_caps_malloc(kUploadChunk, MALLOC_CAP_DMA | MALLOC_CAP_8BIT));
502
+ if (buffer) {
503
+ std::size_t n;
504
+ while ((n = std::fread(buffer, 1, kUploadChunk, f)) > 0) {
505
+ if (!tlsWriteAll(tls, buffer, n)) {
506
+ writeOk = false;
507
+ failKind = -9;
508
+ break;
509
+ }
510
+ bytesStreamed += static_cast<long>(n);
511
+ gea::host::uploadProgressAdd(static_cast<long long>(n));
512
+ }
513
+ // A short read (SD error, or fewer bytes than the file) truncates the
514
+ // body; fail loudly instead of shipping a partial upload that the
515
+ // server hangs waiting to complete.
516
+ if (writeOk && (std::ferror(f) || bytesStreamed != fileSize)) {
517
+ std::printf("[upload-diag] SHORT-READ %ld/%ld bytes ferror=%d internal_free=%u\n",
518
+ bytesStreamed, fileSize, std::ferror(f),
519
+ static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
520
+ writeOk = false;
521
+ failKind = -8;
522
+ }
523
+ heap_caps_free(buffer);
524
+ } else {
525
+ writeOk = false;
526
+ failKind = -7;
527
+ }
528
+ }
529
+ std::fclose(f);
530
+ if (writeOk && !suffix.empty()) {
531
+ writeOk = tlsWriteAll(tls, suffix.data(), suffix.size());
532
+ if (writeOk) gea::host::uploadProgressAdd(static_cast<long long>(suffix.size()));
533
+ else failKind = -9;
534
+ }
535
+ if (!writeOk) {
536
+ ESP_LOGE("gea::host::fetch", "uploadFile TLS write failed for %s", url.c_str());
537
+ esp_tls_conn_destroy(tls);
538
+ // -9 default covers head/prefix write failures (the only other writeOk path).
539
+ result.status = failKind ? failKind : -9;
540
+ return result;
541
+ }
542
+
543
+ // Read the whole response (Connection: close).
544
+ std::string resp;
545
+ char rbuf[1024];
546
+ for (;;) {
547
+ const ssize_t r = esp_tls_conn_read(tls, rbuf, sizeof(rbuf));
548
+ if (r == ESP_TLS_ERR_SSL_WANT_READ || r == ESP_TLS_ERR_SSL_WANT_WRITE) {
549
+ vTaskDelay(pdMS_TO_TICKS(10));
550
+ continue;
551
+ }
552
+ if (r <= 0) break; // 0 = closed, <0 = error/EOF
553
+ resp.append(rbuf, static_cast<std::size_t>(r));
554
+ if (resp.size() > 256u * 1024u) break;
555
+ }
556
+ esp_tls_conn_destroy(tls);
557
+
558
+ const std::size_t statusSp = resp.find(' ');
559
+ if (statusSp != std::string::npos) result.status = std::strtod(resp.c_str() + statusSp + 1, nullptr);
560
+ const std::size_t bodyStart = resp.find("\r\n\r\n");
561
+ if (bodyStart != std::string::npos) {
562
+ std::string headers = resp.substr(0, bodyStart);
563
+ std::transform(headers.begin(), headers.end(), headers.begin(),
564
+ [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
565
+ std::string body = resp.substr(bodyStart + 4);
566
+ if (headers.find("transfer-encoding: chunked") != std::string::npos) body = dechunk(body);
567
+ result.body.assign(body.begin(), body.end());
568
+ }
569
+ // The body was fully written (the !writeOk early-return above is the only
570
+ // path that keeps status 0), so a still-zero status here means the response
571
+ // never arrived — the connection dropped/timed out after the upload. Surface
572
+ // it as -4 to distinguish from a write failure (0).
573
+ if (result.status == 0.0) result.status = -4;
574
+ result.ok = result.status >= 200.0 && result.status < 300.0;
575
+ std::printf("[upload-diag] DONE status=%.0f resp_bytes=%u body_bytes=%u internal_free=%u\n",
576
+ result.status, static_cast<unsigned>(resp.size()),
577
+ static_cast<unsigned>(result.body.size()),
578
+ static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)));
579
+ ESP_LOGI("gea::host::fetch", "upload %s -> %.0f (body=%u total=%u file=%ld)", url.c_str(),
580
+ result.status, static_cast<unsigned>(result.body.size()),
581
+ static_cast<unsigned>(resp.size()), fileSize);
582
+ if (!result.ok) {
583
+ ESP_LOGW("gea::host::fetch", "upload error resp: %.300s", resp.c_str());
584
+ }
585
+ return result;
586
+ }
587
+ };
588
+
589
+ } // namespace gea::framework::host
590
+
591
+ gea::host::FetchResponse gea::host::fetch(const std::string &url) {
592
+ return gea::framework::host::FetchHost::fetch(url, FetchRequestInit{});
593
+ }
594
+
595
+ gea::host::FetchResponse gea::host::fetch(const std::string &url, const FetchRequestInit &init) {
596
+ return gea::framework::host::FetchHost::fetch(url, init);
597
+ }
598
+
599
+ gea::host::FetchResponse gea::host::uploadFile(const std::string &url, const std::string &authorization,
600
+ const std::string &contentType, const std::string &prefix,
601
+ const std::string &filePath, const std::string &suffix) {
602
+ return gea::framework::host::UploadStreamer::upload(url, authorization, contentType, prefix, filePath, suffix);
603
+ }
604
+
605
+ // Streaming GET -> SD file. Uses esp_http_client's manual open/read so the body
606
+ // is written to `destPath` chunk-by-chunk (PSRAM scratch), never buffered whole
607
+ // in RAM (unlike the perform()-based FetchHost path, which caps at 2 MB). The SD
608
+ // is a separate peripheral, so these PSRAM writes never hit a flash-cache-disable
609
+ // window. Runs on the async worker; one transfer at a time shares the progress
610
+ // byte counters.
611
+ gea::host::FetchResponse gea::host::downloadFile(const std::string &url, const std::string &authorization,
612
+ const std::string &destPath) {
613
+ gea::host::FetchResponse result{};
614
+ result.ok = false;
615
+ result.status = 0;
616
+ if (!gea::framework::network::wifi().connected()) {
617
+ ESP_LOGW("gea::host::fetch", "downloadFile(%s) skipped: WiFi not connected", url.c_str());
618
+ return result;
619
+ }
620
+
621
+ esp_http_client_config_t config = {};
622
+ config.url = url.c_str();
623
+ config.timeout_ms = 300000;
624
+ config.method = HTTP_METHOD_GET;
625
+ #if GEA_EMBEDDED_ENABLE_HTTPS
626
+ config.crt_bundle_attach = esp_crt_bundle_attach;
627
+ #endif
628
+ esp_http_client_handle_t client = esp_http_client_init(&config);
629
+ if (!client) {
630
+ ESP_LOGE("gea::host::fetch", "downloadFile: init failed for %s", url.c_str());
631
+ return result;
632
+ }
633
+ if (!authorization.empty()) esp_http_client_set_header(client, "Authorization", authorization.c_str());
634
+ esp_http_client_set_header(client, "User-Agent", "gea-embedded/1.0");
635
+ esp_http_client_set_header(client, "Accept", "*/*");
636
+
637
+ if (esp_http_client_open(client, 0) != ESP_OK) { // 0 = no request body (GET)
638
+ ESP_LOGE("gea::host::fetch", "downloadFile: open failed for %s", url.c_str());
639
+ esp_http_client_cleanup(client);
640
+ return result;
641
+ }
642
+ const int64_t contentLength = esp_http_client_fetch_headers(client); // -1 if chunked/unknown
643
+ result.status = static_cast<double>(esp_http_client_get_status_code(client));
644
+ result.ok = result.status >= 200.0 && result.status < 300.0;
645
+ if (!result.ok) {
646
+ ESP_LOGW("gea::host::fetch", "downloadFile %s -> %.0f", url.c_str(), result.status);
647
+ esp_http_client_close(client);
648
+ esp_http_client_cleanup(client);
649
+ return result;
650
+ }
651
+
652
+ FILE *f = std::fopen(destPath.c_str(), "wb");
653
+ if (!f) {
654
+ ESP_LOGE("gea::host::fetch", "downloadFile: cannot open %s for write", destPath.c_str());
655
+ result.ok = false;
656
+ esp_http_client_close(client);
657
+ esp_http_client_cleanup(client);
658
+ return result;
659
+ }
660
+
661
+ gea::host::uploadProgressReset(contentLength > 0 ? static_cast<long long>(contentLength) : 0);
662
+
663
+ constexpr std::size_t kChunk = 16384;
664
+ char *buffer = static_cast<char *>(heap_caps_malloc(kChunk, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
665
+ if (!buffer) buffer = static_cast<char *>(heap_caps_malloc(kChunk, MALLOC_CAP_8BIT));
666
+ bool ok = buffer != nullptr;
667
+ long long received = 0;
668
+ if (ok) {
669
+ while (true) {
670
+ const int r = esp_http_client_read(client, buffer, kChunk);
671
+ if (r < 0) { // read error
672
+ ok = false;
673
+ break;
674
+ }
675
+ if (r == 0) break; // EOF / connection closed
676
+ if (std::fwrite(buffer, 1, static_cast<std::size_t>(r), f) != static_cast<std::size_t>(r)) {
677
+ ok = false; // SD write failed (full?)
678
+ break;
679
+ }
680
+ received += r;
681
+ gea::host::uploadProgressAdd(static_cast<long long>(r));
682
+ }
683
+ heap_caps_free(buffer);
684
+ }
685
+ std::fclose(f);
686
+ // A short read against a known Content-Length means the transfer was truncated.
687
+ if (ok && contentLength > 0 && received != contentLength) ok = false;
688
+ esp_http_client_close(client);
689
+ esp_http_client_cleanup(client);
690
+ result.ok = result.ok && ok;
691
+ ESP_LOGI("gea::host::fetch", "download %s -> %.0f (%lld bytes -> %s)", url.c_str(), result.status,
692
+ received, destPath.c_str());
693
+ return result;
694
+ }
695
+
696
+ #else // ESP_PLATFORM
697
+
698
+ #include <algorithm>
699
+ #include <cctype>
700
+ #include <cstdlib>
701
+ #include <sstream>
702
+ #ifndef __EMSCRIPTEN__
703
+ #include <thread>
704
+ #endif
705
+
706
+ #ifdef __EMSCRIPTEN__
707
+ #include <emscripten/emscripten.h>
708
+ #endif
709
+
710
+ namespace gea::framework::host {
711
+
712
+ #ifdef __EMSCRIPTEN__
713
+
714
+ namespace {
715
+
716
+ EM_ASYNC_JS(char *, gea_web_fetch_bridge, (const char *url_ptr, int url_len, const char *method_ptr, int method_len,
717
+ const char *body_ptr, int body_len, const char *headers_ptr, int headers_len), {
718
+ const url = UTF8ToString(url_ptr, url_len);
719
+ const method = UTF8ToString(method_ptr, method_len) || "GET";
720
+ const requestBody = body_len > 0 ? HEAPU8.slice(body_ptr, body_ptr + body_len) : new Uint8Array(0);
721
+ const headerText = UTF8ToString(headers_ptr, headers_len);
722
+
723
+ // Pack [int32 headerLen][int32 bodyLen][header utf8][raw body bytes] so binary
724
+ // bodies (e.g. PNG tiles) survive the JS->WASM boundary intact. The header is
725
+ // "status\nstatusText\nname: value\n...".
726
+ function pack(status, statusText, responseHeaders, bodyU8) {
727
+ const headerU8 = new TextEncoder().encode(status + "\n" + statusText + "\n" + responseHeaders);
728
+ const out = _malloc(8 + headerU8.length + bodyU8.length);
729
+ const view = new DataView(HEAPU8.buffer, out, 8);
730
+ view.setInt32(0, headerU8.length, true);
731
+ view.setInt32(4, bodyU8.length, true);
732
+ HEAPU8.set(headerU8, out + 8);
733
+ HEAPU8.set(bodyU8, out + 8 + headerU8.length);
734
+ return out;
735
+ }
736
+
737
+ try {
738
+ const headers = {};
739
+ if (headerText.length > 0) {
740
+ const parts = headerText.split("\n");
741
+ for (let i = 0; i + 1 < parts.length; i += 2) {
742
+ if (parts[i].length > 0) headers[parts[i]] = parts[i + 1];
743
+ }
744
+ }
745
+
746
+ const init = { method, headers };
747
+ if (requestBody.length > 0 && method !== "GET" && method !== "HEAD") init.body = requestBody;
748
+
749
+ const response = await fetch(url, init);
750
+ let responseHeaders = "";
751
+ response.headers.forEach((value, key) => {
752
+ responseHeaders += key + ": " + value + "\n";
753
+ });
754
+ const bytes = new Uint8Array(await response.arrayBuffer());
755
+ return pack(String(response.status), String(response.statusText), responseHeaders, bytes);
756
+ } catch (error) {
757
+ const message = error && error.message ? error.message : String(error);
758
+ return pack("0", message, "", new Uint8Array(0));
759
+ }
760
+ });
761
+
762
+ } // namespace
763
+
764
+ class BrowserFetchBridge {
765
+ public:
766
+ static gea::host::FetchResponse fetch(const std::string &url, const gea::host::FetchRequestInit &init) {
767
+ gea::host::FetchResponse result{};
768
+ std::string headers = serializeHeaders(init.headers);
769
+
770
+ auto *raw = gea_web_fetch_bridge(url.data(), static_cast<int>(url.size()),
771
+ init.method.data(), static_cast<int>(init.method.size()),
772
+ init.body.data(), static_cast<int>(init.body.size()),
773
+ headers.data(), static_cast<int>(headers.size()));
774
+
775
+ if (!raw) return result;
776
+ const auto *p = reinterpret_cast<const std::uint8_t *>(raw);
777
+ std::int32_t header_len = 0;
778
+ std::int32_t body_len = 0;
779
+ std::memcpy(&header_len, p, sizeof(header_len));
780
+ std::memcpy(&body_len, p + 4, sizeof(body_len));
781
+ if (header_len < 0) header_len = 0;
782
+ if (body_len < 0) body_len = 0;
783
+ std::string header(reinterpret_cast<const char *>(p + 8), static_cast<std::size_t>(header_len));
784
+ const std::uint8_t *body_ptr = p + 8 + header_len;
785
+ result.body.assign(body_ptr, body_ptr + body_len);
786
+ std::free(raw);
787
+
788
+ parseHeaderBlock(header, result);
789
+ result.ok = result.status >= 200.0 && result.status < 300.0;
790
+ return result;
791
+ }
792
+
793
+ private:
794
+ static std::string serializeHeaders(const gea::host::FetchHeaderMap &headers) {
795
+ std::string out;
796
+ for (const auto &kv : headers) {
797
+ out += kv.first;
798
+ out += '\n';
799
+ out += kv.second;
800
+ out += '\n';
801
+ }
802
+ return out;
803
+ }
804
+
805
+ static void trimTrailingCarriageReturn(std::string &line) {
806
+ if (!line.empty() && line.back() == '\r') line.pop_back();
807
+ }
808
+
809
+ static void parseHeaders(const std::string &header_block, gea::host::FetchResponse &result) {
810
+ std::istringstream stream(header_block);
811
+ std::string line;
812
+ while (std::getline(stream, line)) {
813
+ trimTrailingCarriageReturn(line);
814
+ const std::size_t colon = line.find(':');
815
+ if (colon == std::string::npos) continue;
816
+
817
+ std::string name = line.substr(0, colon);
818
+ std::string value = line.substr(colon + 1);
819
+ while (!value.empty() && value.front() == ' ') value.erase(value.begin());
820
+ std::transform(name.begin(), name.end(), name.begin(),
821
+ [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
822
+ if (!name.empty()) result.headers[name] = value;
823
+ }
824
+ }
825
+
826
+ // Parses the text metadata block "status\nstatusText\nname: value\n..."; the
827
+ // raw body is read separately from the length-prefixed binary payload.
828
+ static void parseHeaderBlock(const std::string &header, gea::host::FetchResponse &result) {
829
+ const std::size_t status_end = header.find('\n');
830
+ if (status_end == std::string::npos) {
831
+ result.status = std::strtod(header.c_str(), nullptr);
832
+ return;
833
+ }
834
+ result.status = std::strtod(header.substr(0, status_end).c_str(), nullptr);
835
+
836
+ const std::size_t text_end = header.find('\n', status_end + 1);
837
+ if (text_end == std::string::npos) {
838
+ result.status_text = header.substr(status_end + 1);
839
+ trimTrailingCarriageReturn(result.status_text);
840
+ return;
841
+ }
842
+ result.status_text = header.substr(status_end + 1, text_end - status_end - 1);
843
+ trimTrailingCarriageReturn(result.status_text);
844
+ parseHeaders(header.substr(text_end + 1), result);
845
+ }
846
+ };
847
+
848
+ #else
849
+
850
+ // Test hooks — symbols defined in packages/core/test/fake_esp_http_client.cpp.
851
+ // In real non-ESP builds (e.g. the simulator's WASM build) these are weak no-ops.
852
+ __attribute__((weak)) void test_record_request(const std::string &, const gea::host::FetchRequestInit &) {}
853
+ __attribute__((weak)) gea::host::FetchResponse test_canned_response(const std::string &) {
854
+ return {};
855
+ }
856
+
857
+ #endif
858
+
859
+ class FetchHost {
860
+ public:
861
+ static gea::host::FetchResponse fetch(const std::string &url) {
862
+ return fetch(url, gea::host::FetchRequestInit{});
863
+ }
864
+ static gea::host::FetchResponse fetch(const std::string &url, const gea::host::FetchRequestInit &init) {
865
+ #ifdef __EMSCRIPTEN__
866
+ return BrowserFetchBridge::fetch(url, init);
867
+ #else
868
+ test_record_request(url, init);
869
+ return test_canned_response(url);
870
+ #endif
871
+ }
872
+ };
873
+
874
+ } // namespace gea::framework::host
875
+
876
+ gea::host::FetchResponse gea::host::fetch(const std::string &url) {
877
+ return gea::framework::host::FetchHost::fetch(url, FetchRequestInit{});
878
+ }
879
+
880
+ gea::host::FetchResponse gea::host::fetch(const std::string &url, const FetchRequestInit &init) {
881
+ return gea::framework::host::FetchHost::fetch(url, init);
882
+ }
883
+
884
+ // Off-device (browser/sim/tests): no streaming upload from a device file path.
885
+ gea::host::FetchResponse gea::host::uploadFile(const std::string &, const std::string &,
886
+ const std::string &, const std::string &,
887
+ const std::string &, const std::string &) {
888
+ return gea::host::FetchResponse{};
889
+ }
890
+
891
+ // Off-device: no streaming download to a device file path.
892
+ gea::host::FetchResponse gea::host::downloadFile(const std::string &, const std::string &,
893
+ const std::string &) {
894
+ return gea::host::FetchResponse{};
895
+ }
896
+
897
+ #endif // ESP_PLATFORM && network capability
898
+
899
+ namespace gea::host {
900
+ namespace {
901
+
902
+ struct AsyncFetchJob {
903
+ std::string url;
904
+ FetchRequestInit init;
905
+ FetchResponse response;
906
+ bool ready = false;
907
+ // Streaming-upload mode (fetchUploadFileAsync): when is_upload is set, the job
908
+ // runs uploadFile(...) instead of fetch(...), streaming up_path off disk.
909
+ bool is_upload = false;
910
+ std::string up_auth;
911
+ std::string up_ctype;
912
+ std::string up_prefix;
913
+ std::string up_path;
914
+ std::string up_suffix;
915
+ // Streaming-download mode (fetchDownloadFileAsync): GET `url` -> `dl_path` on
916
+ // disk, streamed in chunks (never buffered whole in RAM).
917
+ bool is_download = false;
918
+ std::string dl_auth;
919
+ std::string dl_path;
920
+ };
921
+
922
+ std::mutex &asyncFetchMutex() {
923
+ static std::mutex mutex;
924
+ return mutex;
925
+ }
926
+
927
+ std::map<int, std::shared_ptr<AsyncFetchJob>> &asyncFetchJobs() {
928
+ static std::map<int, std::shared_ptr<AsyncFetchJob>> jobs;
929
+ return jobs;
930
+ }
931
+
932
+ int nextAsyncFetchId() {
933
+ static int next = 1;
934
+ return next++;
935
+ }
936
+
937
+ void runAsyncFetchJob(const std::shared_ptr<AsyncFetchJob> &job) {
938
+ FetchResponse response =
939
+ job->is_download ? downloadFile(job->url, job->dl_auth, job->dl_path)
940
+ : job->is_upload ? uploadFile(job->url, job->up_auth, job->up_ctype, job->up_prefix, job->up_path, job->up_suffix)
941
+ : fetch(job->url, job->init);
942
+ std::lock_guard<std::mutex> lock(asyncFetchMutex());
943
+ job->response = response;
944
+ job->ready = true;
945
+ }
946
+
947
+ #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
948
+ void asyncFetchTask(void *raw) {
949
+ std::unique_ptr<std::shared_ptr<AsyncFetchJob>> holder(static_cast<std::shared_ptr<AsyncFetchJob> *>(raw));
950
+ runAsyncFetchJob(*holder);
951
+ vTaskDeleteWithCaps(nullptr);
952
+ }
953
+ #endif
954
+
955
+ double spawnAsyncJob(const std::shared_ptr<AsyncFetchJob> &job) {
956
+ int id = 0;
957
+ {
958
+ std::lock_guard<std::mutex> lock(asyncFetchMutex());
959
+ id = nextAsyncFetchId();
960
+ asyncFetchJobs()[id] = job;
961
+ }
962
+
963
+ #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
964
+ auto *payload = new std::shared_ptr<AsyncFetchJob>(job);
965
+ const BaseType_t ok = xTaskCreateWithCaps(
966
+ asyncFetchTask, "gea_fetch", 32768, payload, 5, nullptr, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
967
+ if (ok != pdPASS) {
968
+ delete payload;
969
+ std::lock_guard<std::mutex> lock(asyncFetchMutex());
970
+ asyncFetchJobs().erase(id);
971
+ ESP_LOGE("gea::host::fetch", "async fetch task create failed; internal largest=%u psram largest=%u",
972
+ static_cast<unsigned>(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
973
+ static_cast<unsigned>(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)));
974
+ return 0;
975
+ }
976
+ #elif defined(__EMSCRIPTEN__)
977
+ runAsyncFetchJob(job);
978
+ #else
979
+ std::thread([job]() {
980
+ runAsyncFetchJob(job);
981
+ }).detach();
982
+ #endif
983
+
984
+ return static_cast<double>(id);
985
+ }
986
+
987
+ double enqueueAsyncFetch(const std::string &url, const FetchRequestInit &init) {
988
+ auto job = std::make_shared<AsyncFetchJob>();
989
+ job->url = url;
990
+ job->init = init;
991
+ return spawnAsyncJob(job);
992
+ }
993
+
994
+ double enqueueAsyncUpload(const std::string &url, const std::string &authorization,
995
+ const std::string &contentType, const std::string &prefix,
996
+ const std::string &filePath, const std::string &suffix) {
997
+ auto job = std::make_shared<AsyncFetchJob>();
998
+ job->is_upload = true;
999
+ job->url = url;
1000
+ job->up_auth = authorization;
1001
+ job->up_ctype = contentType;
1002
+ job->up_prefix = prefix;
1003
+ job->up_path = filePath;
1004
+ job->up_suffix = suffix;
1005
+ return spawnAsyncJob(job);
1006
+ }
1007
+
1008
+ double enqueueAsyncDownload(const std::string &url, const std::string &authorization,
1009
+ const std::string &destPath) {
1010
+ auto job = std::make_shared<AsyncFetchJob>();
1011
+ job->is_download = true;
1012
+ job->url = url;
1013
+ job->dl_auth = authorization;
1014
+ job->dl_path = destPath;
1015
+ return spawnAsyncJob(job);
1016
+ }
1017
+
1018
+ int fetchId(double id) {
1019
+ return static_cast<int>(id);
1020
+ }
1021
+
1022
+ } // namespace
1023
+
1024
+ double fetchAsync(const std::string &url) {
1025
+ return fetchAsync(url, FetchRequestInit{});
1026
+ }
1027
+
1028
+ double fetchAsync(const std::string &url, const FetchRequestInit &init) {
1029
+ return enqueueAsyncFetch(url, init);
1030
+ }
1031
+
1032
+ double fetchUploadFileAsync(const std::string &url, const std::string &authorization,
1033
+ const std::string &contentType, const std::string &prefix,
1034
+ const std::string &filePath, const std::string &suffix) {
1035
+ return enqueueAsyncUpload(url, authorization, contentType, prefix, filePath, suffix);
1036
+ }
1037
+
1038
+ double fetchDownloadFileAsync(const std::string &url, const std::string &authorization,
1039
+ const std::string &destPath) {
1040
+ return enqueueAsyncDownload(url, authorization, destPath);
1041
+ }
1042
+
1043
+ bool fetchReady(double id) {
1044
+ std::lock_guard<std::mutex> lock(asyncFetchMutex());
1045
+ const auto it = asyncFetchJobs().find(fetchId(id));
1046
+ return it != asyncFetchJobs().end() && it->second->ready;
1047
+ }
1048
+
1049
+ FetchResponse fetchResult(double id) {
1050
+ std::lock_guard<std::mutex> lock(asyncFetchMutex());
1051
+ const auto it = asyncFetchJobs().find(fetchId(id));
1052
+ return it == asyncFetchJobs().end() ? FetchResponse{} : it->second->response;
1053
+ }
1054
+
1055
+ void fetchRelease(double id) {
1056
+ std::lock_guard<std::mutex> lock(asyncFetchMutex());
1057
+ asyncFetchJobs().erase(fetchId(id));
1058
+ }
1059
+
1060
+ } // namespace gea::host