-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathref_CameraServer.cpp
More file actions
319 lines (278 loc) · 10.7 KB
/
Copy pathref_CameraServer.cpp
File metadata and controls
319 lines (278 loc) · 10.7 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// CameraServer.cpp
#include "WiFiManager.h"
#include "CameraServer.h"
#include "OTAHandler.h"
#include "Utils.h"
#include "esp_camera.h"
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESP32Servo.h>
#include <Preferences.h>
#include <vector>
#include "StreamServer.h"
// ===== PTZ pins =====
#define SERVO_1 14
#define SERVO_2 15
// ===== PTZ state (servo objects must be global to match Utils.cpp's externs) =====
Servo servo1;
Servo servo2;
static int servo1Pos = 90;
static int servo2Pos = 90;
// ===== Resolution options with actual pixel sizes =====
struct ResolutionOption {
framesize_t size;
const char* name;
uint16_t w;
uint16_t h;
};
// From highest to lowest (safe set for OV2640)
static const std::vector<ResolutionOption> resolutionOptions = {
{FRAMESIZE_UXGA, "UXGA", 1600,1200},
{FRAMESIZE_SXGA, "SXGA", 1280,1024},
{FRAMESIZE_XGA, "XGA", 1024,768},
{FRAMESIZE_SVGA, "SVGA", 800, 600},
{FRAMESIZE_VGA, "VGA", 640, 480},
{FRAMESIZE_CIF, "CIF", 352, 288},
{FRAMESIZE_QVGA, "QVGA", 320, 240},
{FRAMESIZE_HQVGA, "HQVGA", 240, 176},
{FRAMESIZE_QQVGA, "QQVGA", 160, 120},
};
static inline int clamp180(int v) {
if (v < 0) return 0;
if (v > 180) return 180;
return v;
}
// ===== Persistence =====
static Preferences camPrefs;
static const char* CAM_NS = "camera";
static const char* KEY_RES = "res"; // framesize_t stored as uint8_t
static const ResolutionOption* findOptionByName(const String& n) {
for (const auto& o : resolutionOptions) {
if (n.equalsIgnoreCase(o.name)) return &o;
}
return nullptr;
}
static const ResolutionOption* findOptionBySize(framesize_t fs) {
for (const auto& o : resolutionOptions) if (o.size == fs) return &o;
return nullptr;
}
// ===== Simple pale-blue UI theme (CSS only; no stream changes) =====
static const char* kStyle = R"CSS(
<style>
:root{
--bg:#eaf4ff; --panel:#ffffff; --text:#102a43; --muted:#486581; --accent:#2b6cb0;
--line:#cfe3ff; --shadow:0 1px 4px rgba(16,42,67,.08);
}
*{box-sizing:border-box}
html,body{margin:0;padding:0;background:var(--bg);color:var(--text);
font-family:system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Helvetica Neue",Arial,sans-serif}
.wrap{max-width:980px;margin:20px auto;padding:0 12px}
.nav{display:flex;gap:8px;justify-content:flex-end;margin:6px 0 16px 0}
.btn{appearance:none;border:1px solid var(--line);padding:8px 12px;border-radius:8px;
background:#d9ebff;cursor:pointer;font-weight:600;box-shadow:var(--shadow);text-decoration:none;color:inherit}
.btn:hover{background:#cfe3ff}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;
box-shadow:var(--shadow);padding:14px 14px 16px 14px;margin:14px 0}
.panel h3{margin:0 0 10px 0;color:var(--accent)}
.row{margin:8px 0}
select,button{font-size:1rem;padding:6px 10px;border-radius:8px;border:1px solid var(--line)}
img.stream{max-width:100%;height:auto;border:1px solid var(--line);border-radius:10px}
pre{background:#f7fbff;border:1px solid var(--line);border-radius:8px;padding:8px;display:block}
label{color:var(--muted);margin-right:6px}
</style>
)CSS";
// ===== Web UI & API =====
static void renderCameraPage(AsyncWebServerRequest* request) {
sensor_t* s = esp_camera_sensor_get();
framesize_t cur = s ? s->status.framesize : FRAMESIZE_VGA;
String html;
html.reserve(7000);
html += "<!doctype html><html><head><meta charset='utf-8'><title>ESP32‑CAM</title>";
html += kStyle;
html += "</head><body><div class='wrap'>";
// Small nav: Wi‑Fi Settings
html += "<div class='nav'>"
"<a class='btn' href='/wifi'>Wi‑Fi Settings</a>"
"</div>";
// PANEL: Controls
html += "<div class='panel'><h3>Camera Controls</h3>";
html += "<div class='row'><label for='res'>Resolution</label>"
"<select id='res' onchange=\"fetch('/resolution?set='+this.value).then(()=>location.reload())\">";
for (const auto& o : resolutionOptions) {
bool sel = (o.size == cur);
html += "<option value='" + String(o.name) + "'" + (sel ? " selected" : "") + ">"
+ String(o.name) + " (" + String(o.w) + "×" + String(o.h) + ")</option>";
}
html += "</select></div>";
html += "<div class='row'>"
"<button class='btn' onclick=\"fetch('/action?go=up')\">Up</button> "
"<button class='btn' onclick=\"fetch('/action?go=down')\">Down</button> "
"<button class='btn' onclick=\"fetch('/action?go=left')\">Left</button> "
"<button class='btn' onclick=\"fetch('/action?go=right')\">Right</button>"
"</div>";
html += "</div>"; // panel
// PANEL: Video (unchanged stream URL to keep your working setup)
html += "<div class='panel'><h3>Live Video</h3>";
html += "<img class='stream' src='http://" + WiFi.localIP().toString() + ":81/stream' alt='Video stream'>";
html += "</div>";
// PANEL: Status
html += "<div class='panel'><h3>Status</h3><pre id='st'>Loading…</pre></div>"
"<script>fetch('/api/status').then(r=>r.json()).then(j=>{"
"document.getElementById('st').textContent=JSON.stringify(j,null,2);});</script>";
html += "</div></body></html>";
request->send(200, "text/html", html);
}
void startCameraServer() {
// Reuse singleton AsyncWebServer from WiFiManager (port 80)
AsyncWebServer& camServer = getWebServer();
// Main page: render skinned UI
camServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
if (!isAuthorized(request)) {
auto* r = request->beginResponse(401, "text/plain", "Unauthorized");
r->addHeader("WWW-Authenticate", "Basic realm=\"ESP32Cam\"");
request->send(r);
return;
}
renderCameraPage(request);
});
// Alias so AP page can link back as "/cam" later without touching other files
camServer.on("/cam", HTTP_GET, [](AsyncWebServerRequest *request){
if (!isAuthorized(request)) {
auto* r = request->beginResponse(401, "text/plain", "Unauthorized");
r->addHeader("WWW-Authenticate", "Basic realm=\"ESP32Cam\"");
request->send(r);
return;
}
renderCameraPage(request);
});
// Change resolution + persist
camServer.on("/resolution", HTTP_GET, [](AsyncWebServerRequest *request){
if (!isAuthorized(request)) {
auto* r = request->beginResponse(401, "text/plain", "Unauthorized");
r->addHeader("WWW-Authenticate", "Basic realm=\"ESP32Cam\"");
request->send(r);
return;
}
if (!request->hasParam("set")) {
request->send(400, "text/plain", "Missing ?set=");
return;
}
const String target = request->getParam("set")->value();
const auto* opt = findOptionByName(target);
if (!opt) { request->send(400, "text/plain", "Invalid resolution"); return; }
sensor_t* s = esp_camera_sensor_get();
if (!s) { request->send(500, "text/plain", "Sensor unavailable"); return; }
s->set_framesize(s, opt->size);
camPrefs.begin(CAM_NS, false);
camPrefs.putUChar(KEY_RES, static_cast<uint8_t>(opt->size));
camPrefs.end();
request->send(200, "text/plain", "OK");
});
// PTZ actions
camServer.on("/action", HTTP_GET, [](AsyncWebServerRequest *request){
if (!isAuthorized(request)) {
auto* r = request->beginResponse(401, "text/plain", "Unauthorized");
r->addHeader("WWW-Authenticate", "Basic realm=\"ESP32Cam\"");
request->send(r);
return;
}
if (request->hasParam("go")) {
String dir = request->getParam("go")->value();
if (dir == "up") servo1Pos = clamp180(servo1Pos + 10);
else if (dir == "down") servo1Pos = clamp180(servo1Pos - 10);
else if (dir == "left") servo2Pos = clamp180(servo2Pos + 10);
else if (dir == "right") servo2Pos = clamp180(servo2Pos - 10);
servo1.write(servo1Pos);
servo2.write(servo2Pos);
}
request->send(200, "text/plain", "OK");
});
// JSON status (handy for your PC viewer)
camServer.on("/api/status", HTTP_GET, [](AsyncWebServerRequest* req){
if (!isAuthorized(req)) {
auto* r = req->beginResponse(401, "text/plain", "Unauthorized");
r->addHeader("WWW-Authenticate", "Basic realm=\"ESP32Cam\"");
req->send(r);
return;
}
sensor_t* s = esp_camera_sensor_get();
framesize_t fs = s ? s->status.framesize : FRAMESIZE_INVALID;
const auto* cur = findOptionBySize(fs);
String json = "{";
json += "\"ip\":\"" + WiFi.localIP().toString() + "\"";
if (cur) {
json += ",\"resolution\":\"" + String(cur->name) + "\"";
json += ",\"width\":" + String(cur->w) + ",\"height\":" + String(cur->h);
}
json += "}";
req->send(200, "application/json", json);
});
// Ensure the shared web server is listening (STA mode path)
ensureWebServerStarted();
}
// ===== Camera init (unchanged) =====
void setupCamera() {
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = 5;
config.pin_d1 = 18;
config.pin_d2 = 19;
config.pin_d3 = 21;
config.pin_d4 = 36;
config.pin_d5 = 39;
config.pin_d6 = 34;
config.pin_d7 = 35;
config.pin_xclk = 0;
config.pin_pclk = 22;
config.pin_vsync = 25;
config.pin_href = 23;
config.pin_sccb_sda = 26;
config.pin_sccb_scl = 27;
config.pin_pwdn = 32;
config.pin_reset = -1;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
bool psram = psramFound();
bool found = false;
// Try from high to low until one initialises
for (const auto& option : resolutionOptions) {
config.frame_size = option.size;
config.jpeg_quality = psram ? 10 : 12;
config.fb_count = psram ? 2 : 1;
// ensure clean state between attempts
esp_camera_deinit();
delay(50);
esp_err_t err = esp_camera_init(&config);
if (err == ESP_OK) {
Serial.printf("Camera initialized with resolution: %s\n", option.name);
found = true;
break;
} else {
Serial.printf("Failed to init with %s (%d), trying lower...\n", option.name, err);
}
}
if (!found) {
Serial.println("Camera init failed for all resolutions.");
return;
}
// Apply saved framesize (if any) AFTER successful init
camPrefs.begin(CAM_NS, true);
uint8_t saved = camPrefs.getUChar(KEY_RES, 0xFF);
camPrefs.end();
if (saved != 0xFF) {
sensor_t* s = esp_camera_sensor_get();
if (s) {
s->set_framesize(s, static_cast<framesize_t>(saved));
Serial.printf("Applied saved framesize id: %u\n", saved);
}
}
// PTZ init
setupServos(); // sets 50Hz on both (from Utils.cpp)
servo1.attach(SERVO_1, 1000, 2000);
servo2.attach(SERVO_2, 1000, 2000);
servo1.write(servo1Pos);
servo2.write(servo2Pos);
// Start MJPEG stream on :81 (unchanged)
startStreamServer();
}