Guest User

Untitled

a guest
Oct 5th, 2025
21
0
6 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.06 KB | Source Code | 0 0
  1. #include <WiFi.h>
  2. #include <WebServer.h>
  3. #include <DNSServer.h>
  4. #include <ESPmDNS.h>
  5.  
  6. // ===== WiFi / AP Config =====
  7. const char* ssid = "STUG";
  8. const char* password = ""; // open
  9. IPAddress apIP(10, 10, 0, 1);
  10. IPAddress netM(255, 255, 255, 0);
  11.  
  12. WebServer server(80);
  13. DNSServer dnsServer;
  14.  
  15. // ===== Motor Pins =====
  16. const int LEFT_POS = 1;
  17. const int LEFT_NEG = 0;
  18. const int RIGHT_POS = 20;
  19. const int RIGHT_NEG = 21;
  20.  
  21. // ===== State =====
  22. String currentCommand = "";
  23. String activeButton = "";
  24. unsigned long lastSend = 0;
  25. const unsigned long sendInterval = 100; // ms
  26.  
  27. // ===== Web Page (controller) =====
  28. const char webpage[] PROGMEM = R"rawliteral(
  29. <!DOCTYPE html>
  30. <html>
  31. <head>
  32. <meta charset="utf-8" />
  33. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  34. <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate, max-age=0">
  35. <title>STUG Controller</title>
  36. <style>
  37. html,body { height:100%; }
  38. body { margin:0; display:flex; height:100vh; justify-content:center; align-items:center; background:#111; }
  39. .grid { display:grid; grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr 1fr; gap:10px; width:100%; max-width:480px; padding:16px; box-sizing:border-box; }
  40. button { font-size:2.5rem; width:100%; padding:24px; background:#444; color:#fff; border:none; border-radius:12px; touch-action:none; -webkit-tap-highlight-color: transparent; }
  41. button:active { background:#777; }
  42. </style>
  43. </head>
  44. <body>
  45. <div class="grid">
  46. <div></div>
  47. <button ontouchstart="press('forward')" ontouchend="release('forward')" onmousedown="press('forward')" onmouseup="release('forward')" onmouseleave="release('forward')">▲</button>
  48. <div></div>
  49.  
  50. <button ontouchstart="press('left')" ontouchend="release('left')" onmousedown="press('left')" onmouseup="release('left')" onmouseleave="release('left')">◀</button>
  51. <div></div>
  52. <button ontouchstart="press('right')" ontouchend="release('right')" onmousedown="press('right')" onmouseup="release('right')" onmouseleave="release('right')">▶</button>
  53.  
  54. <div></div>
  55. <button ontouchstart="press('backward')" ontouchend="release('backward')" onmousedown="press('backward')" onmouseup="release('backward')" onmouseleave="release('backward')">▼</button>
  56. <div></div>
  57. </div>
  58. <script>
  59. // Use keep-alive OFF to avoid caching/probe weirdness
  60. const params = { cache: 'no-store', headers: { 'Cache-Control': 'no-store', 'Pragma': 'no-cache', 'Connection': 'close' } };
  61. function press(cmd) { fetch("/cmd?c=" + cmd + "&a=down", params); }
  62. function release(cmd) { fetch("/cmd?c=" + cmd + "&a=up", params); }
  63. // Safety: stop if page is hidden (user switches apps)
  64. document.addEventListener('visibilitychange', () => {
  65. if (document.hidden) fetch('/cmd?c=safe&a=up', params);
  66. });
  67. </script>
  68. </body>
  69. </html>
  70. )rawliteral";
  71.  
  72. // ===== Util: common headers =====
  73. void addNoCacheClose() {
  74. server.sendHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
  75. server.sendHeader("Pragma", "no-cache");
  76. server.sendHeader("Connection", "close");
  77. }
  78.  
  79. // ===== Serve controller (with host redirect) =====
  80. void serveControllerPage() {
  81. addNoCacheClose();
  82. String host = server.hostHeader();
  83. String ipStr = apIP.toString();
  84. // If the Host header isn't our IP or mDNS name, force a redirect to our root.
  85. if (host != ipStr && host != "stug.local") {
  86. server.sendHeader("Location", String("http://") + ipStr + "/", true);
  87. server.send(302, "text/plain", "");
  88. return;
  89. }
  90. server.send(200, "text/html", webpage);
  91. }
  92.  
  93. // ===== Handle button commands =====
  94. void handleCommand() {
  95. if (server.hasArg("c") && server.hasArg("a")) {
  96. String c = server.arg("c");
  97. String a = server.arg("a");
  98. if (a == "down") {
  99. activeButton = c;
  100. currentCommand = c;
  101. } else if (a == "up") {
  102. if (activeButton == c) {
  103. activeButton = "";
  104. currentCommand = "";
  105. }
  106. }
  107. }
  108. addNoCacheClose();
  109. server.send(200, "text/plain", "OK");
  110. }
  111.  
  112. // ===== Motor Control =====
  113. void setMotors(const String& cmd) {
  114. if (cmd == "forward") {
  115. digitalWrite(LEFT_POS, HIGH); digitalWrite(LEFT_NEG, LOW);
  116. digitalWrite(RIGHT_POS, HIGH); digitalWrite(RIGHT_NEG, LOW);
  117. } else if (cmd == "backward") {
  118. digitalWrite(LEFT_POS, LOW); digitalWrite(LEFT_NEG, HIGH);
  119. digitalWrite(RIGHT_POS, LOW); digitalWrite(RIGHT_NEG, HIGH);
  120. } else if (cmd == "left") {
  121. digitalWrite(LEFT_POS, LOW); digitalWrite(LEFT_NEG, HIGH);
  122. digitalWrite(RIGHT_POS, HIGH); digitalWrite(RIGHT_NEG, LOW);
  123. } else if (cmd == "right") {
  124. digitalWrite(LEFT_POS, HIGH); digitalWrite(LEFT_NEG, LOW);
  125. digitalWrite(RIGHT_POS, LOW); digitalWrite(RIGHT_NEG, HIGH);
  126. } else {
  127. digitalWrite(LEFT_POS, LOW); digitalWrite(LEFT_NEG, LOW);
  128. digitalWrite(RIGHT_POS, LOW); digitalWrite(RIGHT_NEG, LOW);
  129. }
  130. }
  131.  
  132. // ===== Captive Portal helpers =====
  133. // For all probe endpoints, answer with 200 and small HTML (not 204), to trigger portal.
  134. void captiveOK() {
  135. addNoCacheClose();
  136. server.send(200, "text/html",
  137. "<!doctype html><meta name='viewport' content='width=device-width, initial-scale=1'>"
  138. "<title>Sign-in</title><p>Redirecting...</p>"
  139. "<script>location.replace('/');</script>");
  140. }
  141. // For everything else, 302 to root so the address bar is nice.
  142. void redirectToRoot() {
  143. addNoCacheClose();
  144. server.sendHeader("Location", String("http://") + apIP.toString() + "/", true);
  145. server.send(302, "text/plain", "");
  146. }
  147.  
  148. void setup() {
  149. Serial.begin(115200);
  150. delay(400);
  151. Serial.println("\nBooting...");
  152.  
  153. // Motor pin setup
  154. pinMode(LEFT_POS, OUTPUT);
  155. pinMode(LEFT_NEG, OUTPUT);
  156. pinMode(RIGHT_POS, OUTPUT);
  157. pinMode(RIGHT_NEG, OUTPUT);
  158. setMotors(""); // stop at startup
  159.  
  160. // Wi-Fi AP setup (more deterministic for picky phones)
  161. WiFi.persistent(false);
  162. WiFi.mode(WIFI_MODE_AP);
  163. WiFi.setSleep(false); // reliability
  164. WiFi.softAPConfig(apIP, apIP, netM);
  165. WiFi.softAP(ssid, password, 1 /*chan*/, 0 /*hidden*/, 4 /*max clients*/);
  166. delay(150);
  167. Serial.print("AP IP: "); Serial.println(WiFi.softAPIP());
  168.  
  169. // DNS catch-all (lower TTL, no error replies to avoid weird caching)
  170. dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
  171. dnsServer.setTTL(0);
  172. dnsServer.start(53, "*", apIP);
  173.  
  174. // mDNS for convenience: http://stug.local
  175. if (MDNS.begin("stug")) {
  176. MDNS.addService("http", "tcp", 80);
  177. Serial.println("mDNS started: http://stug.local");
  178. } else {
  179. Serial.println("mDNS start failed (continuing).");
  180. }
  181.  
  182. // Web routes
  183. server.on("/", HTTP_ANY, serveControllerPage);
  184. server.on("/cmd", HTTP_ANY, handleCommand);
  185.  
  186. // --- Captive portal probe endpoints (serve HTML 200 + JS redirect) ---
  187. // Google/Android
  188. server.on("/generate_204", HTTP_ANY, captiveOK);
  189. server.on("/gen_204", HTTP_ANY, captiveOK);
  190. // Microsoft/Windows
  191. server.on("/connecttest.txt", HTTP_ANY, captiveOK);
  192. server.on("/ncsi.txt", HTTP_ANY, captiveOK);
  193. // Apple
  194. server.on("/hotspot-detect.html", HTTP_ANY, captiveOK);
  195. server.on("/captive.apple.com", HTTP_ANY, captiveOK);
  196. // Samsung variants (HTTP)
  197. server.on("/connectivitycheck.txt", HTTP_ANY, captiveOK);
  198. server.on("/mobile/success.html", HTTP_ANY, captiveOK);
  199. // Some carriers poke simple roots like "/"
  200. server.on("/success.txt", HTTP_ANY, captiveOK);
  201.  
  202. // Favicon etc. → just redirect to root
  203. server.on("/favicon.ico", HTTP_ANY, redirectToRoot);
  204.  
  205. // Catch-all → 302 to "/"
  206. server.onNotFound(redirectToRoot);
  207.  
  208. server.begin();
  209. Serial.println("ESP32-C3 Controller Ready!");
  210. }
  211.  
  212. void loop() {
  213. dnsServer.processNextRequest();
  214. server.handleClient();
  215.  
  216. // Stream the active command every 100ms
  217. if (!currentCommand.isEmpty()) {
  218. unsigned long now = millis();
  219. if (now - lastSend >= sendInterval) {
  220. lastSend = now;
  221. Serial.println(currentCommand);
  222. }
  223. }
  224.  
  225. // Update motors
  226. setMotors(currentCommand);
  227.  
  228. // Yield to Wi-Fi/stack
  229. delay(1);
  230. }
  231.  
Advertisement
Add Comment
Please, Sign In to add comment