main.ino
Arduino (C++) · 226 lines
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <TinyGPS++.h>
#include <HardwareSerial.h>
// =======================
// GPS CONFIGURATION
// =======================
#define GPS_RX_PIN 16 // ESP32 RX <- GPS TX
#define GPS_TX_PIN 17 // ESP32 TX -> GPS RX
#define GPS_BAUD 9600
#define GPS_TIMEOUT_MS 2000 // no bytes within this window => module disconnected
TinyGPSPlus gps;
HardwareSerial GPSserial(2); // UART2
unsigned long lastRxMs = 0; // timestamp of the last byte received from GPS
// =======================
// WIFI ACCESS POINT CONFIG
// =======================
const char* ap_ssid = "ESP32-GPS"; // open AP (no password)
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
// =======================
// DNS / CAPTIVE PORTAL
// =======================
const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer server(80);
// =======================
// HELPERS
// =======================
String jsonEscape(String s) {
s.replace("\"", "\\\"");
return s;
}
// Build JSON with current GPS state
String gpsJson() {
// "connected" if we received any byte within the last GPS_TIMEOUT_MS
bool link = (lastRxMs != 0) && (millis() - lastRxMs < GPS_TIMEOUT_MS);
// Only trust parsed values while the link is alive (avoids showing stale data)
bool hasFix = link && gps.location.isValid();
String j = "{";
j += "\"link\":" + String(link ? "true" : "false");
j += ",\"chars\":" + String(gps.charsProcessed());
j += ",\"fix\":" + String(hasFix ? "true" : "false");
j += ",\"sats\":" + String((link && gps.satellites.isValid()) ? String(gps.satellites.value()) : "null");
j += ",\"hdop\":" + String((link && gps.hdop.isValid()) ? String(gps.hdop.hdop(), 1) : "null");
if (hasFix) {
// 2 decimal places only (~1 km) to avoid revealing the exact location
j += ",\"lat\":" + String(gps.location.lat(), 2);
j += ",\"lng\":" + String(gps.location.lng(), 2);
} else {
j += ",\"lat\":null,\"lng\":null";
}
j += ",\"alt\":" + String((link && gps.altitude.isValid()) ? String(gps.altitude.meters(), 2) : "null");
j += ",\"speed\":" + String((link && gps.speed.isValid()) ? String(gps.speed.kmph(), 2) : "null");
j += ",\"course\":"+ String((link && gps.course.isValid()) ? String(gps.course.deg(), 2) : "null");
if (link && gps.date.isValid() && gps.time.isValid()) {
char buf[40];
sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d UTC",
gps.date.year(), gps.date.month(), gps.date.day(),
gps.time.hour(), gps.time.minute(), gps.time.second());
j += ",\"datetime\":\"" + String(buf) + "\"";
} else {
j += ",\"datetime\":null";
}
j += "}";
return j;
}
// =======================
// HTML PAGE
// =======================
String htmlPage() {
String html = "<!DOCTYPE html><html><head>"
"<meta charset='UTF-8'>"
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>ESP32 GPS</title>"
"<style>"
"body{font-family:sans-serif;margin:20px;background:#111;color:#eee;}"
"h2{margin-bottom:4px;}"
".card{background:#1e1e1e;border-radius:10px;padding:16px;max-width:420px;}"
".row{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #333;}"
".row b{color:#4fc3f7;}"
".status{padding:8px 12px;border-radius:8px;display:inline-block;margin:8px 0;font-weight:bold;}"
".ok{background:#1b5e20;} .wait{background:#5d4037;} .err{background:#b71c1c;}"
"</style>"
"</head><body>";
html += "<h2>ESP32 GPS Tracker</h2>";
html += "<div id='stat' class='status wait'>Connecting to GPS...</div>";
html += "<div class='card'>";
html += "<div class='row'><span>Fix</span><b id='fix'>--</b></div>";
html += "<div class='row'><span>Satellites</span><b id='sats'>--</b></div>";
html += "<div class='row'><span>HDOP</span><b id='hdop'>--</b></div>";
html += "<div class='row'><span>Latitude</span><b id='lat'>--</b></div>";
html += "<div class='row'><span>Longitude</span><b id='lng'>--</b></div>";
html += "<div class='row'><span>Altitude</span><b id='alt'>--</b></div>";
html += "<div class='row'><span>Speed</span><b id='speed'>--</b></div>";
html += "<div class='row'><span>Course</span><b id='course'>--</b></div>";
html += "<div class='row'><span>Time (UTC)</span><b id='dt'>--</b></div>";
html += "</div>";
// JavaScript: fetch /data every 1s and update the page
html += "<script>"
"function upd(){"
"fetch('/data').then(r=>r.json()).then(d=>{"
"let s=document.getElementById('stat');"
"if(!d.link){s.className='status err';s.textContent='NO DATA from GPS - module disconnected or check wiring';}"
"else if(d.fix){s.className='status ok';s.textContent='FIX OK';}"
"else{s.className='status wait';s.textContent='Searching for satellites... (may take a few minutes)';}"
"document.getElementById('fix').textContent=d.link?(d.fix?'YES':'NO'):'--';"
"document.getElementById('sats').textContent=d.sats??'--';"
"document.getElementById('hdop').textContent=d.hdop??'--';"
"document.getElementById('lat').textContent=d.lat??'--';"
"document.getElementById('lng').textContent=d.lng??'--';"
"document.getElementById('alt').textContent=(d.alt??'--')+(d.alt!=null?' m':'');"
"document.getElementById('speed').textContent=(d.speed??'--')+(d.speed!=null?' km/h':'');"
"document.getElementById('course').textContent=(d.course??'--')+(d.course!=null?' deg':'');"
"document.getElementById('dt').textContent=d.datetime??'--';"
"}).catch(e=>{});"
"}"
"setInterval(upd,1000);upd();"
"</script>";
html += "</body></html>";
return html;
}
// =======================
// CAPTIVE PORTAL REDIRECT
// =======================
void redirectToRoot() {
String url = "http://" + apIP.toString() + "/";
server.sendHeader("Location", url, true);
server.send(302, "text/plain", "");
}
// =======================
// HTTP HANDLERS
// =======================
void handleRoot() {
server.send(200, "text/html", htmlPage());
}
void handleData() {
server.send(200, "application/json", gpsJson());
}
void handleNotFound() {
// Redirect any unknown path to the main page (captive portal behavior)
redirectToRoot();
}
// Captive portal triggers used by Android, iOS, Windows
void handleGenerate204() { handleRoot(); } // /generate_204 (Android)
void handleHotspotDetect() { handleRoot(); } // /hotspot-detect.html (iOS/macOS)
void handleNCsi() { handleRoot(); } // /ncsi.txt (Windows)
// =======================
// SETUP
// =======================
void setup() {
Serial.begin(115200);
delay(100);
// Initialize GPS UART
GPSserial.begin(GPS_BAUD, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
// Start WiFi in AP mode (open network)
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, netMsk);
WiFi.softAP(ap_ssid);
Serial.println();
Serial.print("AP started. SSID: ");
Serial.println(ap_ssid);
Serial.print("AP IP address: ");
Serial.println(apIP);
// Start DNS server -> redirect all domains to our AP
dnsServer.start(DNS_PORT, "*", apIP);
// Setup web server routes
server.on("/", handleRoot);
server.on("/data", handleData);
// Captive portal paths
server.on("/generate_204", handleGenerate204);
server.on("/hotspot-detect.html", handleHotspotDetect);
server.on("/ncsi.txt", handleNCsi);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("Web server + DNS captive portal started.");
}
// =======================
// LOOP
// =======================
void loop() {
// Feed the GPS parser with UART data (non-blocking)
while (GPSserial.available()) {
gps.encode(GPSserial.read());
lastRxMs = millis(); // mark that a fresh byte arrived
}
dnsServer.processNextRequest();
server.handleClient();
}