@geastack/host 0.1.14 → 0.1.15
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.
- package/audio_runtime.cpp +183 -98
- package/host/audio.cpp +47 -24
- package/host/audio_buffer_runtime.cpp +117 -0
- package/host/audio_worklet.cpp +29 -17
- package/host/camera.cpp +34 -1
- package/host/device.cpp +36 -0
- package/host/http.cpp +155 -56
- package/host/image.cpp +188 -97
- package/host/media.cpp +18 -6
- package/host/mjpeg.cpp +1 -1
- package/host/rtc.cpp +1 -1
- package/host/rtc_esp.cpp +2 -2
- package/host/timers.cpp +2 -2
- package/host/wifi.cpp +30 -32
- package/include/gea/audio-worklet-runtime.h +4 -3
- package/include/gea/http-native-runtime.h +127 -0
- package/include/host/audio.h +84 -13
- package/include/host/backends.h +88 -51
- package/include/host/battery.h +10 -0
- package/include/host/camera.h +1 -0
- package/include/host/camera_frame.h +69 -0
- package/include/host/clock.h +6 -0
- package/include/host/http.h +80 -20
- package/include/host/image.h +1 -0
- package/include/host/navigator.h +238 -89
- package/include/host/storage.h +9 -6
- package/include/host/timers.h +2 -5
- package/include/platform/internal_stack.h +89 -0
- package/input.cpp +57 -33
- package/package.json +1 -1
- package/wifi.cpp +140 -121
package/host/audio_worklet.cpp
CHANGED
|
@@ -45,7 +45,7 @@ struct NodeControl {
|
|
|
45
45
|
};
|
|
46
46
|
|
|
47
47
|
struct NodeState {
|
|
48
|
-
explicit NodeState(int rate) : capture(
|
|
48
|
+
explicit NodeState(int rate) : capture(gea::platform::audio::deviceSampleRate, rate) {}
|
|
49
49
|
std::weak_ptr<ContextState> context;
|
|
50
50
|
std::shared_ptr<AudioWorkletProcessor> processor;
|
|
51
51
|
MessagePort processorPort;
|
|
@@ -63,10 +63,13 @@ struct NodeState {
|
|
|
63
63
|
std::uint64_t captureDropped = 0;
|
|
64
64
|
bool connected = false, alive = true;
|
|
65
65
|
unsigned numberOfInputs = 1;
|
|
66
|
+
bool processingActive() const {
|
|
67
|
+
return alive && (connected || (outputs.empty() && reader && inputTrack.readyState() == "live"));
|
|
68
|
+
}
|
|
66
69
|
};
|
|
67
70
|
|
|
68
71
|
struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
69
|
-
explicit ContextState(int rate) : rate(rate), playback(rate,
|
|
72
|
+
explicit ContextState(int rate) : rate(rate), playback(rate, gea::platform::audio::deviceSampleRate) {}
|
|
70
73
|
~ContextState() {
|
|
71
74
|
if (output) gea::platform::audio::AudioSystem::stopPcmStream(output);
|
|
72
75
|
if (realm) realm->stop();
|
|
@@ -171,7 +174,7 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
171
174
|
// Reserve a whole hardware quantum before process() advances playback
|
|
172
175
|
// or capture. Codec startup and mixer scheduling may temporarily fill
|
|
173
176
|
// this queue; yield until the consumer pulls, without dropping samples.
|
|
174
|
-
const auto required = (renderQuantum *
|
|
177
|
+
const auto required = (renderQuantum * gea::platform::audio::deviceSampleRate + rate - 1) / rate;
|
|
175
178
|
std::lock_guard lock(outputMutex);
|
|
176
179
|
if (required > outputPcm.size() - outputCount) {
|
|
177
180
|
#ifdef ESP_PLATFORM
|
|
@@ -187,7 +190,7 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
187
190
|
bool waitingForInput = false;
|
|
188
191
|
inputClockActive = false;
|
|
189
192
|
for (const auto& node : nodes) {
|
|
190
|
-
if (!node->
|
|
193
|
+
if (!node->processingActive() || !node->reader) continue;
|
|
191
194
|
node->captureInputLive = node->inputTrack.enabled() && node->inputTrack.readyState() == "live";
|
|
192
195
|
if (!node->captureInputLive) {
|
|
193
196
|
// Disabled/ended tracks represent silence, not a stalled device clock.
|
|
@@ -218,7 +221,7 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
218
221
|
while (node->inputCount < renderQuantum) {
|
|
219
222
|
std::array<std::int16_t, 128> pcm{};
|
|
220
223
|
const auto wanted = std::min<std::size_t>(pcm.size(),
|
|
221
|
-
((renderQuantum - node->inputCount) *
|
|
224
|
+
((renderQuantum - node->inputCount) * gea::platform::audio::deviceSampleRate + rate - 1) / rate);
|
|
222
225
|
const auto count = node->reader->read(pcm.data(), wanted);
|
|
223
226
|
if (!count) break;
|
|
224
227
|
#ifdef ESP_PLATFORM
|
|
@@ -241,8 +244,8 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
241
244
|
mix.fill(0);
|
|
242
245
|
bool hasDestination = false;
|
|
243
246
|
for (const auto& node : nodes) {
|
|
244
|
-
if (!node->
|
|
245
|
-
hasDestination
|
|
247
|
+
if (!node->processingActive()) continue;
|
|
248
|
+
hasDestination |= node->connected;
|
|
246
249
|
for (auto& output : node->outputs)
|
|
247
250
|
for (auto& channel : output) std::fill(channel.begin(), channel.end(), 0.0f);
|
|
248
251
|
if (node->reader) {
|
|
@@ -271,9 +274,11 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
271
274
|
processSumUs += processUs;
|
|
272
275
|
++processCalls;
|
|
273
276
|
#endif
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
+
if (!node->outputs.empty()) {
|
|
278
|
+
const auto& channel = node->outputs.at(0).at(0);
|
|
279
|
+
if (channel.size() != renderQuantum) throw std::runtime_error("AudioWorklet changed render quantum geometry");
|
|
280
|
+
for (std::size_t i = 0; i < renderQuantum; ++i) mix[i] += channel[i];
|
|
281
|
+
}
|
|
277
282
|
if (!keep) node->alive = false;
|
|
278
283
|
} catch (const std::exception& error) { fail(node, error.what()); }
|
|
279
284
|
catch (...) { fail(node, "AudioWorklet processor failed"); }
|
|
@@ -336,12 +341,14 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
336
341
|
{ std::lock_guard lock(self->readyMutex); self->ready = true; }
|
|
337
342
|
self->readySignal.notify_all();
|
|
338
343
|
const auto quantum = std::chrono::nanoseconds(128000000000LL / self->rate);
|
|
344
|
+
constexpr unsigned maxCatchupQuanta = 4;
|
|
345
|
+
const auto batchBudget = quantum * maxCatchupQuanta;
|
|
339
346
|
auto next = Clock::now();
|
|
340
347
|
while (!self->closed && !self->realm->stopped()) {
|
|
341
348
|
self->realm->runPending(0.5);
|
|
342
349
|
const auto now = Clock::now();
|
|
343
350
|
unsigned catchup = 0;
|
|
344
|
-
while ((self->inputClockActive || now >= next) && catchup++ <
|
|
351
|
+
while ((self->inputClockActive || Clock::now() >= next) && catchup++ < maxCatchupQuanta) {
|
|
345
352
|
#ifdef ESP_PLATFORM
|
|
346
353
|
const auto renderStart = esp_timer_get_time();
|
|
347
354
|
const auto framesBefore = self->frames.load();
|
|
@@ -362,9 +369,11 @@ struct ContextState : std::enable_shared_from_this<ContextState> {
|
|
|
362
369
|
// and the bounded loop still protect the DAC and lower-priority tasks.
|
|
363
370
|
if (self->inputClockActive) next = Clock::now() + quantum;
|
|
364
371
|
else next += quantum;
|
|
365
|
-
//
|
|
366
|
-
//
|
|
367
|
-
|
|
372
|
+
// FFT and other block processors alternate expensive and cheap
|
|
373
|
+
// quanta. Amortize the cooperative tick yield across a bounded batch
|
|
374
|
+
// instead of taxing every expensive quantum with another tick.
|
|
375
|
+
// Retain output deadlines if a batch exhausts its work budget.
|
|
376
|
+
if (Clock::now() - now >= batchBudget) break;
|
|
368
377
|
}
|
|
369
378
|
// Output-only graphs retain missed timer deadlines. Capture graphs
|
|
370
379
|
// resume with the next complete hardware quantum on a later wake.
|
|
@@ -429,7 +438,7 @@ std::shared_ptr<ContextState> createContext(double rate) {
|
|
|
429
438
|
// Report a conservative processing delay from the configured queue capacity.
|
|
430
439
|
// currentTime is a render clock; neither property claims a DAC timestamp.
|
|
431
440
|
double contextBaseLatency(const std::shared_ptr<ContextState>& context) {
|
|
432
|
-
return context ? double(outputCapacity) /
|
|
441
|
+
return context ? double(outputCapacity) / gea::platform::audio::deviceSampleRate + gea::platform::audio::AudioSystem::processingLatency() : 0;
|
|
433
442
|
}
|
|
434
443
|
double contextTime(const std::shared_ptr<ContextState>& context) {
|
|
435
444
|
// Legacy oscillator-only contexts retain their platform scheduler's clock.
|
|
@@ -511,8 +520,9 @@ void AudioWorklet::addModule(const std::string& url) const {
|
|
|
511
520
|
AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::string& name)
|
|
512
521
|
: AudioWorkletNode(context, name, AudioWorkletNodeOptions{}) {}
|
|
513
522
|
AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::string& name, const AudioWorkletNodeOptions& options) {
|
|
514
|
-
if (options.numberOfInputs > 1 || options.numberOfOutputs
|
|
515
|
-
|
|
523
|
+
if (options.numberOfInputs > 1 || options.numberOfOutputs > 1 || options.channelCount != 1 ||
|
|
524
|
+
(!options.numberOfInputs && !options.numberOfOutputs))
|
|
525
|
+
throw std::invalid_argument("Embedded AudioWorklet requires at least one mono input or output, at most one of each");
|
|
516
526
|
const auto owner = context.workletContext();
|
|
517
527
|
workers::MessageChannel channel;
|
|
518
528
|
port = channel.port1;
|
|
@@ -525,6 +535,7 @@ AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::strin
|
|
|
525
535
|
node->processorPort = channel.port2.transfer();
|
|
526
536
|
node->numberOfInputs = options.numberOfInputs;
|
|
527
537
|
if (!options.numberOfInputs) node->inputs.clear();
|
|
538
|
+
if (!options.numberOfOutputs) node->outputs.clear();
|
|
528
539
|
owner->invoke([owner, node, name] {
|
|
529
540
|
if (owner->nodes.size() >= audio_worklet::maxNodes) throw std::runtime_error("AudioContext node limit exceeded");
|
|
530
541
|
const auto factory = owner->factories.find(name);
|
|
@@ -541,6 +552,7 @@ AudioWorkletNode::AudioWorkletNode(const AudioContext& context, const std::strin
|
|
|
541
552
|
}
|
|
542
553
|
AudioDestinationNode AudioWorkletNode::connect(AudioDestinationNode destination) const {
|
|
543
554
|
if (!state_) throw std::logic_error("Null AudioWorkletNode");
|
|
555
|
+
if (state_->outputs.empty()) throw std::invalid_argument("AudioWorkletNode has no outputs");
|
|
544
556
|
auto context = state_->context.lock();
|
|
545
557
|
if (!context || context != destination.context) throw std::invalid_argument("Audio nodes belong to different contexts");
|
|
546
558
|
const auto node = state_;
|
package/host/camera.cpp
CHANGED
|
@@ -2,11 +2,19 @@
|
|
|
2
2
|
#include "camera.h"
|
|
3
3
|
#include "gea/embedded-host.h"
|
|
4
4
|
#include "ui/camera_element.h"
|
|
5
|
+
#include "host/worker.h"
|
|
5
6
|
|
|
7
|
+
#include <cstdint>
|
|
8
|
+
#include <mutex>
|
|
6
9
|
#include <string>
|
|
7
10
|
|
|
8
11
|
namespace gea::framework::camera {
|
|
9
12
|
|
|
13
|
+
namespace {
|
|
14
|
+
std::mutex cameraOwnershipMutex;
|
|
15
|
+
std::uint64_t cameraGeneration = 0;
|
|
16
|
+
}
|
|
17
|
+
|
|
10
18
|
bool CameraBackend::isAvailable() {
|
|
11
19
|
return gea::platform::camera::Camera::isAvailable();
|
|
12
20
|
}
|
|
@@ -20,10 +28,31 @@ bool CameraBackend::requestPermission() {
|
|
|
20
28
|
}
|
|
21
29
|
|
|
22
30
|
bool CameraBackend::open(const std::string &facing, double preferredWidth, double preferredHeight) {
|
|
23
|
-
|
|
31
|
+
std::lock_guard guard(cameraOwnershipMutex);
|
|
32
|
+
if (!gea::platform::camera::Camera::open(facing, static_cast<int>(preferredWidth), static_cast<int>(preferredHeight))) return false;
|
|
33
|
+
const auto generation = ++cameraGeneration;
|
|
34
|
+
const auto owner = gea::host::workers::Context::current();
|
|
35
|
+
if (!owner->isMain()) {
|
|
36
|
+
try {
|
|
37
|
+
owner->addCleanup([generation] {
|
|
38
|
+
std::lock_guard cleanupGuard(cameraOwnershipMutex);
|
|
39
|
+
// An old realm must not shut down a camera reopened by its successor.
|
|
40
|
+
if (cameraGeneration != generation) return;
|
|
41
|
+
++cameraGeneration;
|
|
42
|
+
gea::platform::camera::Camera::close();
|
|
43
|
+
});
|
|
44
|
+
} catch (...) {
|
|
45
|
+
++cameraGeneration;
|
|
46
|
+
gea::platform::camera::Camera::close();
|
|
47
|
+
throw;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
24
51
|
}
|
|
25
52
|
|
|
26
53
|
void CameraBackend::close() {
|
|
54
|
+
std::lock_guard guard(cameraOwnershipMutex);
|
|
55
|
+
++cameraGeneration;
|
|
27
56
|
gea::platform::camera::Camera::close();
|
|
28
57
|
}
|
|
29
58
|
|
|
@@ -78,6 +107,10 @@ double CameraBackend::captureMirrored() {
|
|
|
78
107
|
return static_cast<double>(gea::platform::camera::Camera::capture(true));
|
|
79
108
|
}
|
|
80
109
|
|
|
110
|
+
std::string CameraBackend::captureFrame() {
|
|
111
|
+
return gea::platform::camera::Camera::captureFrame();
|
|
112
|
+
}
|
|
113
|
+
|
|
81
114
|
void CameraBackend::setFlash(const std::string &mode) {
|
|
82
115
|
gea::platform::camera::Camera::setFlash(mode);
|
|
83
116
|
}
|
package/host/device.cpp
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
#include "host/clock.h"
|
|
3
|
+
#include "power.h"
|
|
4
|
+
|
|
5
|
+
#include <cmath>
|
|
6
|
+
|
|
7
|
+
#if defined(__GNUC__)
|
|
8
|
+
#define GEA_WEAK_DEVICE __attribute__((weak))
|
|
9
|
+
#else
|
|
10
|
+
#define GEA_WEAK_DEVICE
|
|
11
|
+
#endif
|
|
12
|
+
|
|
13
|
+
namespace gea::platform::power {
|
|
14
|
+
|
|
15
|
+
GEA_WEAK_DEVICE bool Power::charging() { return false; }
|
|
16
|
+
|
|
17
|
+
GEA_WEAK_DEVICE bool Power::vibrate(double, int) { return false; }
|
|
18
|
+
|
|
19
|
+
} // namespace gea::platform::power
|
|
20
|
+
|
|
21
|
+
namespace gea::platform::clock {
|
|
22
|
+
|
|
23
|
+
GEA_WEAK_DEVICE bool setEpochMs(double timestamp) {
|
|
24
|
+
if (!std::isfinite(timestamp) || timestamp < 0) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
#if defined(_WIN32)
|
|
28
|
+
return false;
|
|
29
|
+
#else
|
|
30
|
+
const auto seconds = static_cast<time_t>(timestamp / 1000);
|
|
31
|
+
timeval now{seconds, static_cast<suseconds_t>((timestamp - seconds * 1000.0) * 1000)};
|
|
32
|
+
return settimeofday(&now, nullptr) == 0;
|
|
33
|
+
#endif
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
} // namespace gea::platform::clock
|
package/host/http.cpp
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
// facade (register_handler, runRequests, platform_listen). The gea_cpp_value
|
|
4
4
|
// reply-parsing `create_server` is header-inline and compiled in the geatsc app
|
|
5
5
|
// TU, where the full runtime value type exists. The native test harness defines
|
|
6
|
-
// GEA_CPP_VALUE_AVAILABLE globally, so disable it here (matching
|
|
7
|
-
// to keep that value-dependent block out of this TU, which
|
|
6
|
+
// GEA_CPP_VALUE_AVAILABLE globally, so disable it here (matching
|
|
7
|
+
// host/fetch.cpp) to keep that value-dependent block out of this TU, which
|
|
8
|
+
// lacks the type.
|
|
8
9
|
#ifdef GEA_CPP_VALUE_AVAILABLE
|
|
9
10
|
#define GEA_HTTP_RESTORE_CPP_VALUE_AVAILABLE 1
|
|
10
11
|
#undef GEA_CPP_VALUE_AVAILABLE
|
|
@@ -57,8 +58,9 @@ NativeHttpServerHandle nextHandle() {
|
|
|
57
58
|
|
|
58
59
|
// Post a request and block until the frame task has produced a reply (or the
|
|
59
60
|
// deadline passes). Returns the filled reply. Called on the server worker task.
|
|
60
|
-
HttpReply dispatchAndWait(NativeHttpServerHandle server, HttpRequest req,
|
|
61
|
-
int
|
|
61
|
+
HttpReply dispatchAndWait(NativeHttpServerHandle server, HttpRequest req,
|
|
62
|
+
int timeoutMs, int pollMs,
|
|
63
|
+
const std::function<void(int)> &sleep) {
|
|
62
64
|
auto pending = std::make_shared<PendingRequest>();
|
|
63
65
|
pending->server = server;
|
|
64
66
|
pending->req = std::move(req);
|
|
@@ -83,7 +85,7 @@ HttpReply dispatchAndWait(NativeHttpServerHandle server, HttpRequest req, int ti
|
|
|
83
85
|
return pending->reply;
|
|
84
86
|
}
|
|
85
87
|
|
|
86
|
-
}
|
|
88
|
+
} // namespace
|
|
87
89
|
|
|
88
90
|
std::unordered_map<NativeHttpServerHandle, RequestHandler> &handlerTable() {
|
|
89
91
|
static std::unordered_map<NativeHttpServerHandle, RequestHandler> table;
|
|
@@ -106,7 +108,8 @@ void runRequests() {
|
|
|
106
108
|
std::vector<std::shared_ptr<PendingRequest>> drained;
|
|
107
109
|
{
|
|
108
110
|
std::lock_guard<std::mutex> lock(queueMutex());
|
|
109
|
-
if (requestQueue().empty())
|
|
111
|
+
if (requestQueue().empty())
|
|
112
|
+
return;
|
|
110
113
|
drained.swap(requestQueue());
|
|
111
114
|
}
|
|
112
115
|
for (const auto &pending : drained) {
|
|
@@ -114,7 +117,8 @@ void runRequests() {
|
|
|
114
117
|
{
|
|
115
118
|
std::lock_guard<std::mutex> lock(handlerMutex());
|
|
116
119
|
auto it = handlerTable().find(pending->server);
|
|
117
|
-
if (it != handlerTable().end())
|
|
120
|
+
if (it != handlerTable().end())
|
|
121
|
+
handler = it->second;
|
|
118
122
|
}
|
|
119
123
|
if (handler) {
|
|
120
124
|
pending->reply = handler(pending->req);
|
|
@@ -127,13 +131,15 @@ void runRequests() {
|
|
|
127
131
|
}
|
|
128
132
|
}
|
|
129
133
|
|
|
130
|
-
HttpReply test_dispatch(NativeHttpServerHandle handle,
|
|
131
|
-
const std::string &
|
|
134
|
+
HttpReply test_dispatch(NativeHttpServerHandle handle,
|
|
135
|
+
const std::string &method, const std::string &path,
|
|
136
|
+
const std::string &query) {
|
|
132
137
|
RequestHandler handler;
|
|
133
138
|
{
|
|
134
139
|
std::lock_guard<std::mutex> lock(handlerMutex());
|
|
135
140
|
auto it = handlerTable().find(handle);
|
|
136
|
-
if (it != handlerTable().end())
|
|
141
|
+
if (it != handlerTable().end())
|
|
142
|
+
handler = it->second;
|
|
137
143
|
}
|
|
138
144
|
HttpReply reply;
|
|
139
145
|
if (!handler) {
|
|
@@ -145,15 +151,17 @@ HttpReply test_dispatch(NativeHttpServerHandle handle, const std::string &method
|
|
|
145
151
|
req.method = method;
|
|
146
152
|
req.path = path;
|
|
147
153
|
req.query = query;
|
|
154
|
+
|
|
148
155
|
return handler(req);
|
|
149
156
|
}
|
|
150
157
|
|
|
151
|
-
}
|
|
158
|
+
} // namespace gea::host::http
|
|
152
159
|
|
|
153
160
|
#if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
|
|
154
161
|
|
|
155
|
-
#include "esp_http_server.h"
|
|
156
162
|
#include "esp_heap_caps.h"
|
|
163
|
+
#include "esp_http_server.h"
|
|
164
|
+
#include "esp_idf_version.h"
|
|
157
165
|
#include "esp_log.h"
|
|
158
166
|
|
|
159
167
|
#include "freertos/FreeRTOS.h"
|
|
@@ -181,25 +189,41 @@ std::unordered_map<NativeHttpServerHandle, httpd_handle_t> &espServers() {
|
|
|
181
189
|
|
|
182
190
|
std::string methodName(int method) {
|
|
183
191
|
switch (method) {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
192
|
+
case HTTP_POST:
|
|
193
|
+
return "POST";
|
|
194
|
+
case HTTP_PUT:
|
|
195
|
+
return "PUT";
|
|
196
|
+
case HTTP_DELETE:
|
|
197
|
+
return "DELETE";
|
|
198
|
+
case HTTP_HEAD:
|
|
199
|
+
return "HEAD";
|
|
200
|
+
case HTTP_PATCH:
|
|
201
|
+
return "PATCH";
|
|
202
|
+
default:
|
|
203
|
+
return "GET";
|
|
190
204
|
}
|
|
191
205
|
}
|
|
192
206
|
|
|
193
207
|
const char *statusLine(int status) {
|
|
194
208
|
switch (status) {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
209
|
+
case 200:
|
|
210
|
+
return "200 OK";
|
|
211
|
+
case 204:
|
|
212
|
+
return "204 No Content";
|
|
213
|
+
case 302:
|
|
214
|
+
return "302 Found";
|
|
215
|
+
case 303:
|
|
216
|
+
return "303 See Other";
|
|
217
|
+
case 400:
|
|
218
|
+
return "400 Bad Request";
|
|
219
|
+
case 404:
|
|
220
|
+
return "404 Not Found";
|
|
221
|
+
case 500:
|
|
222
|
+
return "500 Internal Server Error";
|
|
223
|
+
case 504:
|
|
224
|
+
return "504 Gateway Timeout";
|
|
225
|
+
default:
|
|
226
|
+
return "200 OK";
|
|
203
227
|
}
|
|
204
228
|
}
|
|
205
229
|
|
|
@@ -215,8 +239,13 @@ esp_err_t sendFile(httpd_req_t *r, const HttpReply &reply) {
|
|
|
215
239
|
}
|
|
216
240
|
httpd_resp_set_status(r, statusLine(reply.status));
|
|
217
241
|
httpd_resp_set_type(r, reply.contentType.c_str());
|
|
242
|
+
for (const auto &header : reply.headers) {
|
|
243
|
+
if (validHttpHeader(header))
|
|
244
|
+
httpd_resp_set_hdr(r, header.name.c_str(), header.value.c_str());
|
|
245
|
+
}
|
|
218
246
|
if (!reply.download.empty()) {
|
|
219
|
-
const std::string disposition =
|
|
247
|
+
const std::string disposition =
|
|
248
|
+
"attachment; filename=\"" + reply.download + "\"";
|
|
220
249
|
httpd_resp_set_hdr(r, "Content-Disposition", disposition.c_str());
|
|
221
250
|
}
|
|
222
251
|
auto *buffer = static_cast<char *>(std::malloc(kStreamChunkBytes));
|
|
@@ -232,20 +261,24 @@ esp_err_t sendFile(httpd_req_t *r, const HttpReply &reply) {
|
|
|
232
261
|
result = ESP_FAIL;
|
|
233
262
|
break;
|
|
234
263
|
}
|
|
235
|
-
if (read < kStreamChunkBytes)
|
|
264
|
+
if (read < kStreamChunkBytes)
|
|
265
|
+
break; // EOF (short read)
|
|
236
266
|
}
|
|
237
267
|
std::free(buffer);
|
|
238
268
|
std::fclose(f);
|
|
239
|
-
if (result == ESP_OK)
|
|
269
|
+
if (result == ESP_OK)
|
|
270
|
+
httpd_resp_send_chunk(r, nullptr, 0); // terminate
|
|
240
271
|
return result;
|
|
241
272
|
}
|
|
242
273
|
|
|
243
274
|
esp_err_t wildcardHandler(httpd_req_t *r) {
|
|
244
|
-
const auto server = static_cast<NativeHttpServerHandle>(
|
|
275
|
+
const auto server = static_cast<NativeHttpServerHandle>(
|
|
276
|
+
reinterpret_cast<std::uintptr_t>(r->user_ctx));
|
|
245
277
|
|
|
246
278
|
// r->uri is a fixed char array (never null); construct directly to avoid a
|
|
247
279
|
// -Werror=address "address will never be NULL" warning.
|
|
248
|
-
std::string uri =
|
|
280
|
+
std::string uri =
|
|
281
|
+
(r->uri[0] != '\0') ? std::string(r->uri) : std::string("/");
|
|
249
282
|
std::string path = uri;
|
|
250
283
|
std::string query;
|
|
251
284
|
const std::size_t q = uri.find('?');
|
|
@@ -258,27 +291,72 @@ esp_err_t wildcardHandler(httpd_req_t *r) {
|
|
|
258
291
|
req.method = methodName(r->method);
|
|
259
292
|
req.path = path;
|
|
260
293
|
req.query = query;
|
|
294
|
+
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
|
|
295
|
+
const auto rawLength = httpd_get_raw_req_data_len(r);
|
|
296
|
+
std::string raw(rawLength, '\0');
|
|
297
|
+
if (rawLength && httpd_get_raw_req_data(r, raw.data(), rawLength) == ESP_OK) {
|
|
298
|
+
req.headers = parseHttpHeaders(raw);
|
|
299
|
+
}
|
|
300
|
+
#else
|
|
301
|
+
// Older IDF does not expose header enumeration; retain the standard fields
|
|
302
|
+
// needed by device upload handlers without using private httpd structures.
|
|
303
|
+
for (const char *name : {"Host", "Content-Type", "Content-Length",
|
|
304
|
+
"X-File-Name", "Authorization", "Origin"}) {
|
|
305
|
+
const auto length = httpd_req_get_hdr_value_len(r, name);
|
|
306
|
+
if (!length)
|
|
307
|
+
continue;
|
|
308
|
+
std::string value(length + 1, '\0');
|
|
309
|
+
if (httpd_req_get_hdr_value_str(r, name, value.data(), value.size()) ==
|
|
310
|
+
ESP_OK) {
|
|
311
|
+
value.resize(length);
|
|
312
|
+
req.headers.push_back({name, std::move(value)});
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
#endif
|
|
316
|
+
|
|
317
|
+
constexpr int maxBodyBytes = 2 * 1024 * 1024;
|
|
318
|
+
if (r->content_len > maxBodyBytes) {
|
|
319
|
+
httpd_resp_set_status(r, "413 Content Too Large");
|
|
320
|
+
return httpd_resp_sendstr(r, "Request body exceeds 2 MiB");
|
|
321
|
+
}
|
|
322
|
+
req.body.resize(static_cast<std::size_t>(r->content_len));
|
|
323
|
+
std::size_t received = 0;
|
|
324
|
+
while (received < req.body.size()) {
|
|
325
|
+
const int count =
|
|
326
|
+
httpd_req_recv(r, reinterpret_cast<char *>(req.body.data() + received),
|
|
327
|
+
req.body.size() - received);
|
|
328
|
+
if (count <= 0)
|
|
329
|
+
return ESP_FAIL;
|
|
330
|
+
received += static_cast<std::size_t>(count);
|
|
331
|
+
}
|
|
261
332
|
|
|
262
333
|
const HttpReply reply = dispatchAndWait(
|
|
263
334
|
server, std::move(req), kRendezvousTimeoutMs, kRendezvousPollMs,
|
|
264
335
|
[](int ms) { vTaskDelay(pdMS_TO_TICKS(ms)); });
|
|
265
336
|
|
|
266
|
-
if (!reply.file.empty())
|
|
337
|
+
if (!reply.file.empty())
|
|
338
|
+
return sendFile(r, reply);
|
|
267
339
|
|
|
268
340
|
httpd_resp_set_status(r, statusLine(reply.status));
|
|
269
341
|
httpd_resp_set_type(r, reply.contentType.c_str());
|
|
342
|
+
for (const auto &header : reply.headers) {
|
|
343
|
+
if (validHttpHeader(header))
|
|
344
|
+
httpd_resp_set_hdr(r, header.name.c_str(), header.value.c_str());
|
|
345
|
+
}
|
|
270
346
|
if (!reply.download.empty()) {
|
|
271
|
-
const std::string disposition =
|
|
347
|
+
const std::string disposition =
|
|
348
|
+
"attachment; filename=\"" + reply.download + "\"";
|
|
272
349
|
httpd_resp_set_hdr(r, "Content-Disposition", disposition.c_str());
|
|
273
350
|
}
|
|
274
351
|
httpd_resp_send(r, reply.body.data(), reply.body.size());
|
|
275
352
|
return ESP_OK;
|
|
276
353
|
}
|
|
277
354
|
|
|
278
|
-
}
|
|
355
|
+
} // namespace
|
|
279
356
|
|
|
280
357
|
bool platform_listen(NativeHttpServerHandle handle, int port) {
|
|
281
|
-
if (espServers().count(handle))
|
|
358
|
+
if (espServers().count(handle))
|
|
359
|
+
return true; // already listening
|
|
282
360
|
|
|
283
361
|
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
|
284
362
|
config.server_port = static_cast<std::uint16_t>(port);
|
|
@@ -287,63 +365,84 @@ bool platform_listen(NativeHttpServerHandle handle, int port) {
|
|
|
287
365
|
// default) then fails httpd_start with ESP_FAIL. Derive a unique ctrl port
|
|
288
366
|
// from the listen port so the portal coexists with diagnostics/OTA servers.
|
|
289
367
|
config.ctrl_port = static_cast<std::uint16_t>(32768 + (port % 1000) + 1);
|
|
290
|
-
config.stack_size =
|
|
291
|
-
|
|
368
|
+
config.stack_size =
|
|
369
|
+
4096; // esp_http_server default; 8192 risked NO_MEM post-WiFi
|
|
370
|
+
config.max_uri_handlers = 6;
|
|
292
371
|
// A personal portal serves a page + an audio stream; a few sockets is plenty.
|
|
293
372
|
// The default (7) competes with the diagnostics/OTA servers for the limited
|
|
294
373
|
// LWIP socket pool, so keep this small.
|
|
295
374
|
config.max_open_sockets = 4;
|
|
296
375
|
config.lru_purge_enable = true;
|
|
297
376
|
config.uri_match_fn = httpd_uri_match_wildcard;
|
|
298
|
-
// Worker tasks block on the frame-task rendezvous; the recv/send timeouts
|
|
299
|
-
// exceed it so a slow frame doesn't drop the socket mid-request.
|
|
377
|
+
// Worker tasks block on the frame-task rendezvous; the recv/send timeouts
|
|
378
|
+
// must exceed it so a slow frame doesn't drop the socket mid-request.
|
|
300
379
|
config.recv_wait_timeout = 15;
|
|
301
380
|
config.send_wait_timeout = 15;
|
|
302
381
|
|
|
303
|
-
ESP_LOGI(
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
382
|
+
ESP_LOGI(
|
|
383
|
+
kTag,
|
|
384
|
+
"httpd_start :%d heap int8[free=%u largest=%u] dma[free=%u largest=%u]",
|
|
385
|
+
port,
|
|
386
|
+
static_cast<unsigned>(
|
|
387
|
+
heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
|
|
388
|
+
static_cast<unsigned>(heap_caps_get_largest_free_block(
|
|
389
|
+
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
|
|
390
|
+
static_cast<unsigned>(
|
|
391
|
+
heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)),
|
|
392
|
+
static_cast<unsigned>(heap_caps_get_largest_free_block(
|
|
393
|
+
MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)));
|
|
308
394
|
httpd_handle_t server = nullptr;
|
|
309
395
|
const esp_err_t startErr = httpd_start(&server, &config);
|
|
310
396
|
if (startErr != ESP_OK) {
|
|
311
|
-
ESP_LOGE(kTag, "httpd_start failed on port %d: %s", port,
|
|
397
|
+
ESP_LOGE(kTag, "httpd_start failed on port %d: %s", port,
|
|
398
|
+
esp_err_to_name(startErr));
|
|
312
399
|
return false;
|
|
313
400
|
}
|
|
314
401
|
|
|
315
402
|
httpd_uri_t wildcard = {};
|
|
316
403
|
wildcard.uri = "/*";
|
|
317
|
-
wildcard.method = HTTP_GET;
|
|
318
404
|
wildcard.handler = wildcardHandler;
|
|
319
|
-
wildcard.user_ctx =
|
|
320
|
-
|
|
405
|
+
wildcard.user_ctx =
|
|
406
|
+
reinterpret_cast<void *>(static_cast<std::uintptr_t>(handle));
|
|
407
|
+
for (const auto method :
|
|
408
|
+
{HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE, HTTP_HEAD, HTTP_PATCH}) {
|
|
409
|
+
wildcard.method = method;
|
|
410
|
+
if (httpd_register_uri_handler(server, &wildcard) != ESP_OK) {
|
|
411
|
+
httpd_stop(server);
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
321
415
|
|
|
322
416
|
espServers()[handle] = server;
|
|
323
|
-
ESP_LOGI(kTag, "listening on :%d (handle %u)", port,
|
|
417
|
+
ESP_LOGI(kTag, "listening on :%d (handle %u)", port,
|
|
418
|
+
static_cast<unsigned>(handle));
|
|
324
419
|
return true;
|
|
325
420
|
}
|
|
326
421
|
|
|
327
422
|
void platform_close(NativeHttpServerHandle handle) {
|
|
328
423
|
auto it = espServers().find(handle);
|
|
329
|
-
if (it == espServers().end())
|
|
330
|
-
|
|
424
|
+
if (it == espServers().end())
|
|
425
|
+
return;
|
|
426
|
+
if (it->second)
|
|
427
|
+
httpd_stop(it->second);
|
|
331
428
|
espServers().erase(it);
|
|
332
429
|
ESP_LOGI(kTag, "stopped (handle %u)", static_cast<unsigned>(handle));
|
|
333
430
|
}
|
|
334
431
|
|
|
335
|
-
}
|
|
432
|
+
} // namespace gea::host::http
|
|
336
433
|
|
|
337
|
-
#else
|
|
434
|
+
#else // no ESP network capability
|
|
338
435
|
|
|
339
436
|
namespace gea::host::http {
|
|
340
437
|
|
|
341
438
|
// Off-device (host tools, simulator, unit tests): no real socket. listen/close
|
|
342
439
|
// are no-ops; tests drive handlers through test_dispatch(). Weak so a platform
|
|
343
440
|
// can override with a real implementation.
|
|
344
|
-
__attribute__((weak)) bool platform_listen(NativeHttpServerHandle, int) {
|
|
441
|
+
__attribute__((weak)) bool platform_listen(NativeHttpServerHandle, int) {
|
|
442
|
+
return false;
|
|
443
|
+
}
|
|
345
444
|
__attribute__((weak)) void platform_close(NativeHttpServerHandle) {}
|
|
346
445
|
|
|
347
|
-
}
|
|
446
|
+
} // namespace gea::host::http
|
|
348
447
|
|
|
349
|
-
#endif
|
|
448
|
+
#endif // ESP_PLATFORM && network capability
|