HTTPServer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #include "HTTPServer.h"
  2. #include <Arduino.h>
  3. /// <summary>
  4. /// Constructs an HTTPServer instance with the specified port and shutter controller.
  5. /// Creates a new AsyncWebServer instance but does not start it yet.
  6. /// </summary>
  7. HTTPServer::HTTPServer(uint16_t port, IShutterController* controller)
  8. : shutterController(controller)
  9. {
  10. server = new AsyncWebServer(port);
  11. }
  12. /// <summary>
  13. /// Destructor that properly cleans up the AsyncWebServer instance.
  14. /// </summary>
  15. HTTPServer::~HTTPServer()
  16. {
  17. if (server)
  18. {
  19. delete server;
  20. }
  21. }
  22. /// <summary>
  23. /// Configures the ESP8266 as a WiFi access point with the provided credentials.
  24. /// Sets up the static IP configuration and starts the access point.
  25. /// </summary>
  26. void HTTPServer::setupWiFiAP(const char* ssid, const char* password,
  27. IPAddress local_IP, IPAddress gateway, IPAddress subnet)
  28. {
  29. if (!WiFi.softAPConfig(local_IP, gateway, subnet))
  30. {
  31. Serial.println("Failed to config IP");
  32. }
  33. WiFi.softAP(ssid, password);
  34. Serial.println(WiFi.softAPIP());
  35. Serial.println("AP Started - Waiting for connections");
  36. }
  37. /// <summary>
  38. /// Registers all HTTP API routes and their corresponding handlers.
  39. /// Associates each route with its handler method using lambda expressions.
  40. /// </summary>
  41. void HTTPServer::setupRoutes()
  42. {
  43. // Root endpoint - serves home page
  44. server->on("/", HTTP_GET, [this](AsyncWebServerRequest *request) {
  45. handleRoot(request);
  46. });
  47. // Focus endpoint
  48. server->on("/api/focus", HTTP_GET, [this](AsyncWebServerRequest *request) {
  49. handleFocus(request);
  50. });
  51. // Take photo endpoint
  52. server->on("/api/takePhoto", HTTP_GET, [this](AsyncWebServerRequest *request) {
  53. handleTakePhoto(request);
  54. });
  55. // Reset endpoint
  56. server->on("/api/reset", HTTP_GET, [this](AsyncWebServerRequest *request) {
  57. handleReset(request);
  58. });
  59. // Multiple shoot endpoint
  60. server->on("/api/multiple", HTTP_GET, [this](AsyncWebServerRequest *request) {
  61. handleMultiple(request);
  62. });
  63. // Health check endpoint
  64. server->on("/api/healthcheck", HTTP_GET, [this](AsyncWebServerRequest *request) {
  65. handleHealthCheck(request);
  66. });
  67. }
  68. /// <summary>
  69. /// Handles GET / request to serve the home page.
  70. /// Returns a simple HTML interface for controlling the camera remote.
  71. /// Provides buttons for focus, photo capture, reset, and multiple shot controls.
  72. /// </summary>
  73. void HTTPServer::handleRoot(AsyncWebServerRequest *request)
  74. {
  75. const char* html = R"rawliteral(
  76. <!DOCTYPE html>
  77. <html>
  78. <head>
  79. <title>Minolta Remote Control</title>
  80. <style>
  81. * { margin: 0; padding: 0; box-sizing: border-box; }
  82. body {
  83. font-family: Arial, sans-serif;
  84. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  85. min-height: 100vh;
  86. display: flex;
  87. justify-content: center;
  88. align-items: center;
  89. padding: 20px;
  90. }
  91. .container {
  92. background: white;
  93. border-radius: 15px;
  94. box-shadow: 0 20px 60px rgba(0,0,0,0.3);
  95. padding: 30px;
  96. max-width: 500px;
  97. width: 100%;
  98. }
  99. h1 {
  100. text-align: center;
  101. color: #333;
  102. margin-bottom: 30px;
  103. font-size: 28px;
  104. }
  105. .section {
  106. margin-bottom: 25px;
  107. padding-bottom: 25px;
  108. border-bottom: 1px solid #eee;
  109. }
  110. .section:last-child { border-bottom: none; }
  111. .section h2 {
  112. color: #667eea;
  113. font-size: 16px;
  114. margin-bottom: 15px;
  115. }
  116. button {
  117. width: 100%;
  118. padding: 12px 20px;
  119. margin-bottom: 10px;
  120. font-size: 16px;
  121. font-weight: bold;
  122. border: none;
  123. border-radius: 8px;
  124. cursor: pointer;
  125. transition: all 0.3s ease;
  126. }
  127. .btn-focus {
  128. background: #4CAF50;
  129. color: white;
  130. }
  131. .btn-focus:hover { background: #45a049; }
  132. .btn-photo {
  133. background: #2196F3;
  134. color: white;
  135. }
  136. .btn-photo:hover { background: #0b7dda; }
  137. .btn-reset {
  138. background: #f44336;
  139. color: white;
  140. }
  141. .btn-reset:hover { background: #da190b; }
  142. .input-group {
  143. display: flex;
  144. gap: 10px;
  145. margin-bottom: 10px;
  146. }
  147. input {
  148. flex: 1;
  149. padding: 10px;
  150. border: 1px solid #ddd;
  151. border-radius: 4px;
  152. font-size: 14px;
  153. }
  154. .btn-multiple {
  155. background: #FF9800;
  156. color: white;
  157. }
  158. .btn-multiple:hover { background: #e68900; }
  159. .status {
  160. margin-top: 20px;
  161. padding: 15px;
  162. border-radius: 8px;
  163. text-align: center;
  164. display: none;
  165. }
  166. .status.success {
  167. background: #d4edda;
  168. color: #155724;
  169. display: block;
  170. }
  171. .status.error {
  172. background: #f8d7da;
  173. color: #721c24;
  174. display: block;
  175. }
  176. </style>
  177. </head>
  178. <body>
  179. <div class="container">
  180. <h1>📷 Minolta Remote</h1>
  181. <div class="section">
  182. <h2>Basic Controls</h2>
  183. <button class="btn-focus" onclick="sendRequest('/api/focus')">🎯 Focus</button>
  184. <button class="btn-photo" onclick="sendRequest('/api/takePhoto')">📸 Take Photo</button>
  185. <button class="btn-reset" onclick="sendRequest('/api/reset')">🔄 Reset</button>
  186. </div>
  187. <div class="section">
  188. <h2>Photo Hold Duration</h2>
  189. <input type="number" id="msec" min="100" max="5000" value="1000" placeholder="Duration (ms)">
  190. <button class="btn-photo" onclick="takePhotoWithDelay()">📸 Take with Delay</button>
  191. </div>
  192. <div class="section">
  193. <h2>Multiple Shots</h2>
  194. <div class="input-group">
  195. <input type="number" id="count" min="1" max="100" value="3" placeholder="Count">
  196. <input type="number" id="delay" min="100" max="5000" value="500" placeholder="Delay (ms)">
  197. </div>
  198. <div class="input-group">
  199. <input type="number" id="msecMulti" min="100" max="5000" value="1000" placeholder="Duration (ms)">
  200. </div>
  201. <button class="btn-multiple" onclick="multipleShoot()">🎬 Multiple Shots</button>
  202. </div>
  203. <div id="status" class="status"></div>
  204. </div>
  205. <script>
  206. function sendRequest(endpoint) {
  207. fetch(endpoint)
  208. .then(response => {
  209. if (response.ok) {
  210. showStatus('✓ Success: ' + endpoint, 'success');
  211. } else {
  212. showStatus('✗ Error: ' + response.statusText, 'error');
  213. }
  214. })
  215. .catch(error => showStatus('✗ Connection Error', 'error'));
  216. }
  217. function takePhotoWithDelay() {
  218. const msec = document.getElementById('msec').value;
  219. fetch('/api/takePhoto?msec=' + msec)
  220. .then(response => {
  221. if (response.ok) {
  222. showStatus('✓ Photo taken (' + msec + 'ms)', 'success');
  223. } else {
  224. showStatus('✗ Error taking photo', 'error');
  225. }
  226. })
  227. .catch(error => showStatus('✗ Connection Error', 'error'));
  228. }
  229. function multipleShoot() {
  230. const count = document.getElementById('count').value;
  231. const delay = document.getElementById('delay').value;
  232. const msec = document.getElementById('msecMulti').value;
  233. if (count < 1 || count > 100) {
  234. showStatus('✗ Count must be between 1 and 100', 'error');
  235. return;
  236. }
  237. fetch('/api/multiple?count=' + count + '&delay=' + delay + '&msec=' + msec)
  238. .then(response => {
  239. if (response.ok) {
  240. showStatus('✓ ' + count + ' shots queued', 'success');
  241. } else {
  242. showStatus('✗ Error taking photos', 'error');
  243. }
  244. })
  245. .catch(error => showStatus('✗ Connection Error', 'error'));
  246. }
  247. function showStatus(message, type) {
  248. const status = document.getElementById('status');
  249. status.textContent = message;
  250. status.className = 'status ' + type;
  251. setTimeout(() => {
  252. status.className = 'status';
  253. }, 3000);
  254. }
  255. </script>
  256. </body>
  257. </html>
  258. )rawliteral";
  259. request->send(200, "text/html", html);
  260. }
  261. /// <summary>
  262. /// Handles GET /api/focus request to perform a half press (focus) operation.
  263. /// Logs the request, activates the camera focus, and responds with success.
  264. /// </summary>
  265. void HTTPServer::handleFocus(AsyncWebServerRequest *request)
  266. {
  267. onRequestStart("api/focus");
  268. shutterController->halfPress();
  269. onRequestEnd("api/focus");
  270. request->send(200, "application/json", "{\"result\":\"true\"}");
  271. }
  272. /// <summary>
  273. /// Handles GET /api/takePhoto request to take a photograph.
  274. /// Supports optional "msec" query parameter to control the shutter hold duration (default: 1000ms).
  275. /// </summary>
  276. void HTTPServer::handleTakePhoto(AsyncWebServerRequest *request)
  277. {
  278. onRequestStart("api/takePhoto");
  279. if (request->hasParam("msec"))
  280. {
  281. int ms = request->getParam("msec")->value().toInt();
  282. shutterController->pressFullWithDelay(ms);
  283. }
  284. else
  285. {
  286. shutterController->pressFullWithDelay(1000);
  287. }
  288. onRequestEnd("api/takePhoto");
  289. request->send(200, "application/json", "{\"result\":\"true\"}");
  290. }
  291. /// <summary>
  292. /// Handles GET /api/reset request to release the shutter and return to neutral position.
  293. /// Logs the request, releases all controls, and responds with success.
  294. /// </summary>
  295. void HTTPServer::handleReset(AsyncWebServerRequest *request)
  296. {
  297. onRequestStart("api/reset");
  298. shutterController->unPress();
  299. onRequestEnd("api/reset");
  300. request->send(200, "application/json", "{\"result\":\"true\"}");
  301. }
  302. /// <summary>
  303. /// Handles GET /api/multiple request to take multiple photos in sequence.
  304. /// Requires query parameters: "count" (number of photos) and "delay" (ms between shots).
  305. /// Supports optional "msec" parameter for individual shot duration (default: 1000ms).
  306. /// </summary>
  307. void HTTPServer::handleMultiple(AsyncWebServerRequest *request)
  308. {
  309. onRequestStart("api/multiple");
  310. if (request->hasParam("count") && request->hasParam("delay"))
  311. {
  312. int ms = 1000;
  313. int count = request->getParam("count")->value().toInt();
  314. int delayMs = request->getParam("delay")->value().toInt();
  315. if (request->hasParam("msec"))
  316. {
  317. ms = request->getParam("msec")->value().toInt();
  318. }
  319. shutterController->multipleShoot(ms, count, delayMs);
  320. }
  321. onRequestEnd("api/multiple");
  322. request->send(200, "application/json", "{\"result\":\"true\"}");
  323. }
  324. /// <summary>
  325. /// Handles GET /api/healthcheck request as a simple health check endpoint.
  326. /// Returns a plain text "Is working" response to verify server connectivity.
  327. /// </summary>
  328. void HTTPServer::handleHealthCheck(AsyncWebServerRequest *request)
  329. {
  330. onRequestStart("api/healthcheck");
  331. onRequestEnd("api/healthcheck");
  332. request->send(200, "text/plain", "Is working");
  333. }
  334. /// <summary>
  335. /// Logs the start of a request to the serial console and enables the status LED.
  336. /// Called at the beginning of each request handler.
  337. /// </summary>
  338. /// <param name="endpoint">The name of the API endpoint being processed</param>
  339. void HTTPServer::onRequestStart(const char* endpoint)
  340. {
  341. Serial.print("[REQUEST] ");
  342. Serial.println(endpoint);
  343. digitalWrite(LED_BUILTIN, HIGH);
  344. }
  345. /// <summary>
  346. /// Logs the completion of a request to the serial console and disables the status LED.
  347. /// Called at the end of each request handler.
  348. /// </summary>
  349. /// <param name="endpoint">The name of the API endpoint that was processed</param>
  350. void HTTPServer::onRequestEnd(const char* endpoint)
  351. {
  352. digitalWrite(LED_BUILTIN, LOW);
  353. Serial.print("[RESPONSE] ");
  354. Serial.println(endpoint);
  355. }
  356. /// <summary>
  357. /// Initializes the WiFi access point and starts the HTTP server.
  358. /// Must be called during application setup to enable the server.
  359. /// Calls setupWiFiAP() to configure WiFi, setupRoutes() to register endpoints, and starts the server.
  360. /// </summary>
  361. void HTTPServer::begin(const char* ssid, const char* password,
  362. IPAddress local_IP, IPAddress gateway, IPAddress subnet)
  363. {
  364. setupWiFiAP(ssid, password, local_IP, gateway, subnet);
  365. setupRoutes();
  366. server->begin();
  367. Serial.println("HTTP Server started");
  368. }