Community project

ESP32 and DS18B20 - Data collector and Talker for NMEA0183

Photo of ESP32 and DS18B20 - Data collector  and Talker for NMEA0183
Generated with AI

schema

Published December 3, 2026

This project turns an ESP32 into a multi-sensor temperature data collector and NMEA0183 network talker. Five DS18B20 temperature probes monitor different points in a system, with the ESP32 reading and broadcasting the data over Wi-Fi using the NMEA0183 protocol. The guide includes a wiring diagram for connecting all five probes, a complete parts list, and step-by-step assembly instructions to get the temperature monitoring system up and running.

The firmware enables the ESP32 to act as both a listener and talker on an NMEA0183 network, collecting temperature data from up to four external sources while simultaneously sharing local probe readings via TCP and UDP. A web dashboard provides configuration and monitoring, with Wi-Fi setup and probe naming built into the interface. This makes it ideal for marine systems, HVAC monitoring, or any application requiring networked temperature sensing with NMEA0183 compatibility.

Wiring diagram

Wiring diagram for ESP32 and DS18B20 - Data collector  and Talker for NMEA0183
Loading diagram…

Gather all the parts

QtyComponent
1

Resistor

4.7 kΩ

Through-hole resistor (current-limiting in series with an LED)

1

DS18B20

Digital temperature sensor using OneWire protocol

1

DS18B20

Digital temperature sensor using OneWire protocol

1

DS18B20

Digital temperature sensor using OneWire protocol

1

DS18B20

Digital temperature sensor using OneWire protocol

1

DS18B20

Digital temperature sensor using OneWire protocol

Assemble it in 2 steps

1. Wire all five temperature probes

Unplug USB. Connect each probe VCC to 3V3, GND to GND, and DATA to GPIO18. Check the probe pinout rather than guessing from wire colors. Place one 4.7 kΩ resistor between GPIO18 and 3V3. Keep the data branches short for the first test. Reconnect USB and press Deploy, then look for Probe 1 through Probe 5 and Celsius readings in the serial output at 115200 baud.

2. Connect the dashboard to your Wi-Fi

Join DS18D20 using password ProbeDials5. Stay connected if Windows says there is no internet. Open http://192.168.5.1/ and either open the temperature dashboard directly or enter your 2.4 GHz Wi-Fi name and password. Once the page shows the dashboard address, switch back to your normal Wi-Fi and open that address. The address is also printed in the ESP32 serial output. The setup network turns off about one minute after connecting. Successful Wi-Fi details are saved on the ESP32 for its next restart.

Review all connections

1. Connections between "probe-1" and "ESP32"

Functionprobe-1ESP32
powerVCC3V3
groundGNDGND
dataDATAGPIO 18

2. Connections between "probe-2" and "ESP32"

Functionprobe-2ESP32
powerVCC3V3
groundGNDGND
dataDATA → DS18B20 DATAEXT

3. Connections between "probe-3" and "ESP32"

Functionprobe-3ESP32
powerVCC3V3
groundGNDGND
dataDATA → DS18B20 DATAEXT

4. Connections between "probe-4" and "ESP32"

Functionprobe-4ESP32
powerVCC3V3
groundGNDGND
dataDATA → DS18B20 DATAEXT

5. Connections between "probe-5" and "ESP32"

Functionprobe-5ESP32
powerVCC3V3
groundGNDGND
dataDATA → DS18B20 DATAEXT

6. Connections between "temp-pullup" and "ESP32"

Functiontemp-pullupESP32
digitalP1 → DS18B20 DATAEXT
powerP23V3

Deploy the firmware

// =======================================================================
// ========== temperature and NMEA TCP/UDP listner/Talker ================
// ESP32-3 board and a 5 temperature probes DS18B20
// Default password: ProbeDia5
// Funtion:
// 1. NMEA0183 
//    a. delivers 5 temperatures from 5 probes as the local source
//    b. Listner on max 4 Talkers (TCP and UDP) to collect data
//    c. Talker makes all collected and the local data available via UDP and 
//       TCP/IP
//    d. wired connection to input on a Rasphbary Pi 5
// =======================================================================
//
// ========= To do
//   
//
// =======================================================================

#include <Arduino.h>
#include <USB.h>
#include <USBCDC.h>
#include <esp_timer.h>
#include <esp_timer.h>

static USBCDC nativeUsb;
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#include <lwip/sockets.h>
#include <Preferences.h>
#include <WebServer.h>
#include "dashboard.h"


// Hardware and timing shared by the probe reader and the web API.
constexpr uint8_t kProbeCount = 5;
constexpr uint8_t kProbeDataPin = 18;
constexpr uint32_t kSampleIntervalMs = 1000;
constexpr uint32_t kConversionTimeMs = 750;
constexpr uint32_t kJoinTimeoutMs = 25000;
constexpr uint32_t kPortalGraceMs = 60000;

static WebServer server(80);
static String probeNames[kProbeCount] = {"1. Inlaat water", "2. Uitlaat water", "Probe 3", "Probe 4", "Probe 5"};
static float readings[kProbeCount] = {};
static bool ready = false;

// Keep raw samples separate so repeated calibration never compounds offsets.
static float raw[kProbeCount] = {};
static float offsets[kProbeCount] = {};

static OneWire temperatureBus(kProbeDataPin);
static DallasTemperature probes(&temperatureBus);

// Factory IDs keep the same physical probes assigned to dials 1–5.
static const DeviceAddress probeAddresses[kProbeCount] = {
  {0x28, 0xB2, 0x4D, 0xD3, 0x00, 0x00, 0x00, 0xFB},
  {0x28, 0xBA, 0xD2, 0xD4, 0x00, 0x00, 0x00, 0x04},
  {0x28, 0xA9, 0x87, 0xD2, 0x00, 0x00, 0x00, 0x48},
  {0x28, 0x85, 0x14, 0xD2, 0x00, 0x00, 0x00, 0x7A},
  {0x28, 0x8B, 0x90, 0xD4, 0x00, 0x00, 0x00, 0xB4},
};

// NMEA 0183 over the local Wi-Fi network.
constexpr uint16_t kNmeaPort = 10110;
static WiFiUDP nmeaUdp;
static WiFiServer nmeaTcp(kNmeaPort);
static WiFiClient nmeaClients[4];
static bool nmeaOnline = false;

// Accept TCP receivers without blocking other work in the main loop.
static void pollNmeaNetwork() {
  if (WiFi.status() != WL_CONNECTED) {
    if (nmeaOnline) {
      for (auto& client : nmeaClients) client.stop();
      nmeaTcp.end();
      nmeaUdp.stop();
      nmeaOnline = false;
    }
    return;
  }
  if (!nmeaOnline) {
    nmeaTcp.begin();
    nmeaTcp.setNoDelay(true);
    nmeaOnline = true;
    Serial.printf("NMEA 0183: TCP and UDP port %u\n", unsigned(kNmeaPort));
  }
  WiFiClient incoming = nmeaTcp.available();
  if (!incoming) return;
  for (auto& client : nmeaClients) {
    if (!client.connected()) {
      client.stop();
      client = incoming;
      return;
    }
  }
  incoming.stop();
}

// Use the active network’s broadcast address for UDP output.
static IPAddress nmeaBroadcast() {
  return IPAddress(uint32_t(WiFi.localIP()) | ~uint32_t(WiFi.subnetMask()));
}

// Keep only the latest successfully sent sentence for each type and source.
static String sentenceType(const String& line);
static constexpr unsigned kTalkerTypes = 64;
struct TalkerLog {
  String lines[kTalkerTypes];
  unsigned next = 0, count = 0;
};
static TalkerLog talkerLog[5]; // Local output uses group 0; network sources use groups 1–4.
static String localTalkerLines[kProbeCount];
static uint8_t relayMask = 0x0f;
// Bit 4 disables local output; older saved masks leave publishing on.
static constexpr uint8_t kLocalPublishOff = 0x10;
static bool localPublishEnabled() { return !(relayMask & kLocalPublishOff); }
static bool relayEnabled(unsigned source) { return relayMask & (1u << source); }

// Send a sentence to network receivers and record it for the Talker page.
static void publishNmeaNetwork(const char* sentence, size_t length, unsigned group = 0, unsigned probe = 0, const char* logSentence = nullptr) {
  if (!nmeaOnline || WiFi.status() != WL_CONNECTED) return;
  const IPAddress broadcast = nmeaBroadcast();
  const auto* bytes = reinterpret_cast<const uint8_t*>(sentence);
  bool sent = false;
  if (nmeaUdp.beginPacket(broadcast, kNmeaPort)) {
    const size_t written = nmeaUdp.write(bytes, length);
    sent = nmeaUdp.endPacket() == 1 && written == length;
  }
  for (auto& client : nmeaClients) {
    // Drop stalled receivers rather than delaying the next probe sample.
    if (!client.connected()) continue;
    if (send(client.fd(), bytes, length, MSG_DONTWAIT) != int(length))
      client.stop();
    else sent = true;
  }
  if (sent && group < 5) {
    String line(logSentence ? logSentence : sentence);
    line.trim();
    // Local probes share the XDR sentence type, so keep one slot per probe.
    if (group == 0) {
      localTalkerLines[probe] = line;
      return;
    }
    auto& log = talkerLog[group];
    const String type = sentenceType(line);
    unsigned slot = 0;
    while (slot < log.count && sentenceType(log.lines[slot]) != type) ++slot;
    if (slot == log.count) {
      if (log.count < kTalkerTypes) ++log.count;
      else slot = log.next++ % kTalkerTypes;
    }
    if (log.lines[slot] != line) log.lines[slot] = line;
  }
}

// Publish each valid probe separately, using the saved dashboard name in XDR.
static void publishMarineTemperatures() {
  if (!localPublishEnabled()) return;
  for (uint8_t i = 0; i < kProbeCount; ++i) {
    localTalkerLines[i] = "";
    const float c = readings[i];
    if (!isfinite(c) || c == DEVICE_DISCONNECTED_C) continue;
    // Reserve space for '$', '*HH', CR/LF and the terminating NUL.
    char body[77];
    size_t used = snprintf(body, sizeof(body), "IIXDR,C,%.2f,C,", c);
    // XDR fields must not contain delimiters, control bytes or non-ASCII bytes.
    for (unsigned char ch : probeNames[i]) {
      if (used >= sizeof(body) - 1) break;
      if ((ch & 0xC0) == 0x80) continue; // Skip UTF-8 continuation bytes.
      body[used++] = ch < 32 || ch > 126 || strchr(",$*^!\\~", ch) ? '_' : char(ch);
    }
    body[used] = '\0';
    uint8_t checksum = 0;
    for (const char* p = body; *p; ++p) checksum ^= uint8_t(*p);
    char sentence[83];
    const int length = snprintf(sentence, sizeof(sentence), "$%s*%02X\r\n",
                                body, unsigned(checksum));
    if (length > 0 && size_t(length) < sizeof(sentence)) {
      publishNmeaNetwork(sentence, length, 0, i);
    }
  }
}

// Start conversion and read it later so HTTP requests can run in between.
static void pollTemperatures() {
  static uint32_t started = 0;
  static bool converting = false;
  const uint32_t now = millis();
  if (!converting) {
    if (now - started < kSampleIntervalMs) return;
    probes.requestTemperatures();
    started = millis();
    converting = true;
    return;
  }
  if (now - started < kConversionTimeMs) return;
  converting = false;
  for (uint8_t i = 0; i < kProbeCount; ++i) {
    const auto& address = probeAddresses[i];
    const float c = probes.getTempC(address);
    raw[i] = c;
    readings[i] = c == DEVICE_DISCONNECTED_C ? c : c + offsets[i];
    Serial.printf("Probe %u (", unsigned(i) + 1);
    for (uint8_t b : address) Serial.printf("%02X", unsigned(b));
    if (c == DEVICE_DISCONNECTED_C) Serial.println("): unavailable");
    else Serial.printf("): %.2f C\n", c);
  }
  ready = true;
  publishMarineTemperatures();
}

// Wi-Fi setup and stored credentials.
static Preferences settings;
static bool portal = false, joining = false, saveOnConnect = false;
static uint32_t attemptAt = 0, connectedAt = 0, offlineAt = 0;
static bool online = false, joinPending = false, forgetPending = false;
static uint32_t joinRequestedAt = 0;
static String network, passphrase;

// Provide a local setup network when station Wi-Fi is not available.
static void startPortal() {
  if (portal) return;
  WiFi.mode(WIFI_AP_STA);
  const IPAddress portalIp(192, 168, 5, 1);
  if (!WiFi.softAPConfig(portalIp, portalIp, IPAddress(255, 255, 255, 0))) {
    Serial.println("Could not configure the setup network address.");
    return;
  }
  portal = WiFi.softAP("DS18D20", "ProbeDials5");
  if (portal) Serial.println("Wi-Fi setup: http://" + WiFi.softAPIP().toString() + "/");
}

// Start joining the saved Wi-Fi network asynchronously.
static void joinNetwork() {
  online = false;
  WiFi.disconnect();
  WiFi.setAutoReconnect(true);
  WiFi.begin(network.c_str(), passphrase.c_str());
  attemptAt = millis();
  joining = true;
}

// Advance connection and fallback state without delaying probe reads.
static void pollWiFi() {
  uint32_t now = millis();
  if (forgetPending) {
    // Let the HTTP reply reach the browser before dropping its connection.
    if (now - joinRequestedAt >= 750) {
      forgetPending = false;
      WiFi.setAutoReconnect(false);
      WiFi.disconnect();
      startPortal();
    }
    return;
  }
  if (joinPending) {
    if (now - joinRequestedAt >= 750) {
      joinPending = false;
      joinNetwork();
    }
    return;
  }
  if (WiFi.status() == WL_CONNECTED) {
    if (!online) {
      online = true;
      joining = false;
      connectedAt = now;
      // Keep the last working credentials until the new ones connect.
      if (saveOnConnect) {
        // Store the name and password together so a reboot cannot mix two saves.
        const String record = String(char(network.length())) + network + passphrase;
        bool saved = false;
        if (settings.begin("probe-wifi", false)) {
          saved = settings.putString("credentials", record) == record.length();
          settings.end();
        }
        if (!saved) Serial.println("Wi-Fi connected, but settings could not be saved.");
        saveOnConnect = false;
      }
      Serial.print("Probe dashboard: http://");
      Serial.println(WiFi.localIP());
    }
    // Give the browser time to show the new dashboard address.
    if (portal && now - connectedAt >= kPortalGraceMs) {
      WiFi.softAPdisconnect(true);
      portal = false;
    }
    return;
  }
  if (online) {
    online = false;
    offlineAt = now;
  }
  if (joining && now - attemptAt >= kJoinTimeoutMs) {
    joining = false;
    saveOnConnect = false;
    WiFi.disconnect();
    startPortal();
  }
  if (!joining && !portal && now - offlineAt >= kJoinTimeoutMs) startPortal();
}

// Validate and persist Wi-Fi settings before switching networks.
static void handleJoin() {
  // A cross-site form cannot set this header; cross-origin requests are not allowed.
  if (server.header("X-Probe-Setup") != "1" || joining || joinPending || forgetPending) {
    server.send(403, "text/plain", "Open Settings on the dashboard, or wait for the current connection attempt.");
    return;
  }
  String name = server.arg("ssid"), password = server.arg("pass");
  if (!name.length() || name.length() > 32 || password.length() > 64) {
    server.send(400, "text/plain", "Invalid Wi-Fi name or password length. Go back and try again.");
    return;
  }
  network = name;
  passphrase = password;
  saveOnConnect = true;
  joinPending = true;
  joinRequestedAt = millis();
  server.send(202, "text/plain", "Trying the new Wi-Fi. The dashboard may disconnect. If the connection fails, join DS18D20 and open http://192.168.5.1 to try again.");
}

// Clear saved credentials and return to the setup network.
static void handleForgetNetwork() {
  if (server.header("X-Probe-Setup") != "1") {
    server.send(403, "text/plain", "Open Settings on the dashboard.");
    return;
  }
  // Clear both the current record and any legacy Wi-Fi keys, not other settings.
  bool cleared = false;
  if (settings.begin("probe-wifi", false)) {
    cleared = settings.clear();
    settings.end();
  }
  if (!cleared) {
    server.send(500, "text/plain", "Could not erase saved Wi-Fi. Try again.");
    return;
  }
  network = "";
  passphrase = "";
  joining = joinPending = saveOnConnect = online = false;
  forgetPending = true;
  joinRequestedAt = millis();
  server.send(200, "text/plain", "Network forgotten. Join DS18D20 and open http://192.168.5.1 to set up Wi-Fi again.");
}

// JSON uses null for probes with no usable reading.

static void appendJsonText(String& json, const String& text) {
    for (unsigned char c : text) {
      if (c == '"' || c == '\\') json += '\\';
      if (c < 0x20) {
        char escaped[7];
        snprintf(escaped, sizeof(escaped), "\\u%04x", static_cast<unsigned>(c));
        json += escaped;
      } else json += static_cast<char>(c);
    }
}

// Save the display and publication name for the selected probe.
static void renameProbe() {
  const String probe = server.arg("probe");
  String name = server.arg("name");
  name.trim();
  if (probe.length() != 1 || probe[0] < '1' || probe[0] > '5' ||
      !name.length() || name.length() > 96) {
    server.send(400, "text/plain", "Select a probe and enter a name (up to 96 UTF-8 bytes).");
    return;
  }
  Preferences store;
  if (!store.begin("probe-names", false) || store.putString(probe.c_str(), name) != name.length()) {
    server.send(500, "text/plain", "Could not save probe name.");
    return;
  }
  probeNames[probe[0] - '1'] = name;
  server.send(200, "text/plain", "Probe name saved.");
}

// Provide one snapshot for the dashboard’s live updates.
static void sendTemperatures() {
  String json = ready ? "{\"ready\":true,\"values\":[" : "{\"ready\":false,\"values\":[";
  for (uint8_t i = 0; i < kProbeCount; ++i) {
    if (i) json += ',';
    if (!ready || readings[i] == DEVICE_DISCONNECTED_C) json += "null";
    else json += String(readings[i], 2);
  }
  json += "],\"raw\":[";
  for (uint8_t i = 0; i < kProbeCount; ++i) {
    if (i) json += ',';
    if (!ready || raw[i] == DEVICE_DISCONNECTED_C || !isfinite(raw[i])) json += "null";
    else json += String(raw[i], 2);
  }
  json += "],\"offsets\":[";
  for (uint8_t i = 0; i < kProbeCount; ++i) {
    if (i) json += ',';
    json += String(offsets[i], 2);
  }
  json += "],\"names\":[";
  for (uint8_t i = 0; i < kProbeCount; ++i) {
    if (i) json += ',';
    json += '"';
    appendJsonText(json, probeNames[i]);
    json += '"';
  }
  json += "],\"wifiStatus\":\"";
  if (WiFi.status() == WL_CONNECTED) {
    json += "Connected to ";
    // An SSID can contain quotes, backslashes, or control characters.
    const String ssid = WiFi.SSID();
    appendJsonText(json, ssid);
    json += " · IP address: " + WiFi.localIP().toString();
  }
  else json += "Not connected to normal Wi-Fi";
  json += "\",\"network\":\"";
  if (nmeaOnline && WiFi.status() == WL_CONNECTED) {
    json += "UDP broadcast: " + nmeaBroadcast().toString() + ":" + String(kNmeaPort);
    json += "\\nTCP server: " + WiFi.localIP().toString() + ":" + String(kNmeaPort);
  } else json += "UDP and TCP are offline (Wi-Fi not connected).";
  json += "\"}";
  server.sendHeader("Cache-Control", "no-store");
  server.send(200, "application/json", json);
}

// One saved offset per factory probe ID, in a separate settings namespace.
static void calibrate() {
  const String probe = server.arg("probe");
  if (probe.length() != 1 || probe[0] < '1' || probe[0] > '5') {
    server.send(400, "text/plain", "Select a probe.");
    return;
  }
  const uint8_t i = probe[0] - '1';
  float offset = 0;
  if (server.arg("reset") != "1") {
    const String reference = server.arg("reference");
    char* end;
    const float target = strtof(reference.c_str(), &end);
    if (!reference.length() || *end || !isfinite(target) || target < -55 || target > 125 ||
        !ready || !isfinite(raw[i]) || raw[i] == DEVICE_DISCONNECTED_C) {
      server.send(400, "text/plain", "Enter a reference between -55 and 125 °C and wait for a valid probe reading.");
      return;
    }
    offset = target - raw[i];
  }
  Preferences calibration;
  const String key = "offset" + probe;
  if (!calibration.begin("probe-cal", false) ||
      calibration.putFloat(key.c_str(), offset) != sizeof(float)) {
    server.send(500, "text/plain", "Could not save calibration.");
    return;
  }
  offsets[i] = offset;
  server.send(200, "text/plain", "Saved. Takes effect on the next sample.");
}

#include "nmea_input.h"

// Initialize hardware, restore saved settings, and register HTTP routes.
void setup() {
  Serial.begin(115200);
  // Set the native USB descriptor before the host enumerates the device.
  USB.productName("DS18D20");
  nativeUsb.begin();
  USB.begin();
  probes.begin();
  probes.setWaitForConversion(false);
  WiFi.persistent(false);
  WiFi.setHostname("DS18D20");
  WiFi.mode(WIFI_STA);
  WiFi.setAutoReconnect(true);
  if (settings.begin("probe-wifi", true)) {
    const String record = settings.getString("credentials");
    const unsigned nameLength = record.isEmpty() ? 0 : uint8_t(record[0]);
    if (nameLength && nameLength <= 32 && record.length() > nameLength) {
      network = record.substring(1, 1 + nameLength);
      passphrase = record.substring(1 + nameLength);
    } else {
      // Keep settings saved by earlier firmware usable.
      network = settings.getString("ssid");
      passphrase = settings.getString("pass");
    }
    settings.end();
  }
  if (network.length()) joinNetwork();
  else startPortal();
  const char* setupHeaders[] = {"X-Probe-Setup"};
  server.collectHeaders(setupHeaders, 1);
  const auto serveDashboard = [] {
    server.send_P(200, "text/html; charset=utf-8", dashboard);
  };
  server.on("/", HTTP_GET, serveDashboard);
  server.on("/dashboard", HTTP_GET, serveDashboard);
  // Read-only board information; never include saved credentials.
  server.on("/esp32-info", HTTP_GET, [] {
    char info[1024];
    const bool connected = WiFi.status() == WL_CONNECTED;
    snprintf(info, sizeof(info),
             "Board: ESP32-S3-DevKitC-1 v1.0 (N8)\n"
             "Chip: %s (revision %u)\nCPU: %u cores at %u MHz\n"
             "Flash: %lu bytes at %lu MHz\nSketch size: %lu bytes\n"
             "Heap: %lu bytes free / %lu total (lowest free: %lu)\n"
             "PSRAM: %lu bytes\nUptime: %llu seconds\n"
             "ESP-IDF: %s\nFirmware built: %s %s\n"
             "Wi-Fi station: %s\nStation IP: %s\nSignal: %s\nSetup AP IP: %s",
             ESP.getChipModel(), unsigned(ESP.getChipRevision()),
             unsigned(ESP.getChipCores()), unsigned(ESP.getCpuFreqMHz()),
             (unsigned long)ESP.getFlashChipSize(), (unsigned long)(ESP.getFlashChipSpeed()/1000000),
             (unsigned long)ESP.getSketchSize(), (unsigned long)ESP.getFreeHeap(),
             (unsigned long)ESP.getHeapSize(), (unsigned long)ESP.getMinFreeHeap(),
             (unsigned long)ESP.getPsramSize(), (unsigned long long)(esp_timer_get_time()/1000000),
             ESP.getSdkVersion(), __DATE__, __TIME__, connected ? "Connected" : "Not connected",
             connected ? WiFi.localIP().toString().c_str() : "—",
             connected ? (String(WiFi.RSSI()) + " dBm").c_str() : "—",
             (WiFi.getMode() & WIFI_MODE_AP) ? WiFi.softAPIP().toString().c_str() : "Off");
    server.sendHeader("Cache-Control", "no-store");
    server.send(200, "text/plain; charset=utf-8", info);
  });
  server.on("/temperatures", HTTP_GET, sendTemperatures);
  Preferences calibration;
  if (calibration.begin("probe-cal", true)) {
    for (uint8_t i = 0; i < kProbeCount; ++i) {
      const String key = "offset" + String(i + 1);
      offsets[i] = calibration.getFloat(key.c_str(), 0);
    }
  }
  {
    Preferences names;
    if (names.begin("probe-names", true)) {
      for (uint8_t i = 0; i < kProbeCount; ++i)
        probeNames[i] = names.getString(String(i + 1).c_str(), probeNames[i]);
    }
  }
  server.on("/probe-name", HTTP_POST, renameProbe);
  server.on("/calibrate", HTTP_POST, calibrate);
  server.on("/join", HTTP_POST, handleJoin);
  server.on("/forget-network", HTTP_POST, handleForgetNetwork);
  Preferences relaySettings;
  if (relaySettings.begin("nmea-relay", true)) {
    if (relaySettings.isKey("mask")) relayMask = relaySettings.getUChar("mask");
    relaySettings.end();
  }
  setupNmeaInput();
  server.on("/nmea-talker-relay", HTTP_POST, [] {
    const String group = server.arg("group"), enabled = server.arg("enabled");
    if (group.length() != 1 || group[0] < '0' || group[0] > '4' ||
        (enabled != "0" && enabled != "1")) {
      server.send(400, "text/plain", "Invalid forwarding setting");
      return;
    }
    const unsigned slot = group[0] - '0';
    const uint8_t bit = slot ? 1u << (slot - 1) : kLocalPublishOff;
    const bool setBit = slot ? enabled == "1" : enabled == "0";
    const uint8_t mask = setBit ? relayMask | bit : relayMask & ~bit;
    Preferences store;
    if (!store.begin("nmea-relay", false) || store.putUChar("mask", mask) != 1) {
      server.send(500, "text/plain", "Could not save forwarding setting");
      return;
    }
    relayMask = mask;
    if (enabled == "0") {
      talkerLog[slot] = TalkerLog{};
      if (!slot) for (auto& line : localTalkerLines) line = "";
    }
    server.send(200, "text/plain", "Saved");
  });
  server.on("/nmea-talker-log", HTTP_GET, [] {
    const String group = server.arg("group");
    if (group.length() != 1 || group[0] < '0' || group[0] > '4') {
      server.send(400, "text/plain", "Invalid output group");
      return;
    }
    const auto& log = talkerLog[group[0] - '0'];
    String text;
    if (group[0] == '0') {
      for (unsigned i = 0; i < kProbeCount; ++i) {
        text += localTalkerLines[i].length() ? localTalkerLines[i] : "No current output";
        text += '\n';
      }
    }
    for (unsigned i = 0; i < log.count; ++i) {
      text += log.lines[i];
      text += '\n';
    }
    const bool enabled = group[0] == '0' ? localPublishEnabled() : relayEnabled(group[0] - '1');
    server.sendHeader("X-NMEA-Relay", enabled ? "1" : "0");
    server.sendHeader("Cache-Control", "no-store");
    server.send(200, "text/plain", text);
  });
  server.begin();
}

// Give each service a turn so probe conversion does not stall the dashboard.
void loop() {
  pollWiFi();
  pollNmeaNetwork();
  pollNmeaInput();
  server.handleClient();
  pollTemperatures();
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik