Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
f4329a85eThis file is pinned to the selected release. Download the original to open it in your design tool.
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Jibril Sharafi
#include "custometh.h"
#include <ETH.h>
#include <Preferences.h>
#include <SPI.h>
#include <WiFi.h>
#include <esp_mac.h>
#include <lwip/dns.h>
#include <lwip/tcpip.h>
#include "customwifi.h"
#include "shadow.h"
#include "wifi_provisioning.h"
namespace CustomEth
{
static TaskHeartbeat _heartbeat;
static TaskHandle_t _ethTaskHandle = NULL;
static volatile bool _stopRequested = false;
static SemaphoreHandle_t _configMutex = NULL;
static EthConfiguration _configuration;
// Arbitration state. Written from the Network event task (ETH events), the
// WiFi task (notifyStaState) and the eth task (evaluateAndApply): every access
// copies under the mutex and acts on the copy, per the FreeRTOS rules.
static SemaphoreHandle_t _ctxMutex = NULL;
static InterfaceArbitration::Context _arbCtx;
static bool _enabled = false; // Profile has Ethernet and begin() ran
static bool _eventsRegistered = false;
// _staticIntent is latched from the loaded config BEFORE ETH.begin() starts the
// driver: ARDUINO_EVENT_ETH_CONNECTED can fire before _applyStaticConfiguration()
// runs (fast PHY renegotiation on warm reboot), and the backstop must not miss
// that boot's increment. _staticApplied then records the actual apply outcome.
static bool _staticIntent = false; // Static config will be attempted this boot (not skipped by backstop)
static bool _staticApplied = false; // Static config actually applied this boot
static uint8_t _bootFailsAtBoot = 0; // Backstop counter as read at the intent latch (avoids NVS re-opens)
// Set by the Network event task at first link-up; the eth task performs the
// NVS increment (a flash GC pause must never stall network event delivery).
static volatile bool _bootFailCounted = false;
// See isCommissioned(). Set by the eth task the moment the wire proves the device in
// service, whether or not flash accepted the marker: closing the auth carve-out for
// THIS boot must not depend on NVS.
static volatile bool _commissioned = false;
static volatile bool _commissionedNvsChecked = false;
// DNS servers the wire brought (lease or static config), as raw IPAddress dwords. lwIP
// keeps ONE resolver list for every netif, so ETH.dnsIP() reads whatever the last lease
// on ANY interface wrote. Captured in the GOT_IP event, right after the wire's own lease
// wrote the list.
static volatile uint32_t _ethDns[2] = {0, 0};
#define ETH_MAX_INTERFACE_CALLBACKS 6
static InterfaceChangeCallback _callbacks[ETH_MAX_INTERFACE_CALLBACKS] = {};
static size_t _callbackCount = 0;
static SPIClass* _spi = nullptr;
static void _onNetworkEvent(arduino_event_id_t event);
static void _ethTask(void *parameter);
static void _loadConfiguration();
static void _saveConfigurationToPreferences(const EthConfiguration &config);
static void _applyStaticConfiguration();
static bool _validateJsonConfiguration(JsonDocument &jsonDocument, bool partial);
static bool _validateConfiguration(const EthConfiguration &config);
static uint8_t _getStaticBootFails();
static void _setStaticBootFails(uint8_t count);
static void _updateEthState(bool linkUp, bool hasAddress);
static void _evaluateArbitration();
static void _applyDnsForActiveInterface(InterfaceArbitration::Interface active);
static void _keepDnsOnActiveInterface(InterfaceArbitration::Interface active);
static void _notifyEthTask();
// The core gives SPI Ethernet esp_derive_local_mac(base): a locally administered address
// (routers and NAC treat those as "private/randomized"), and on the S3, which owns two
// universal addresses per chip, the very same value the SoftAP uses. Take the chip's
// second universal address instead (base + 1, no carry, exactly as esp_read_mac() does):
// globally unique, Espressif-assigned, and otherwise only claimed by Bluetooth, which
// this firmware never starts.
// The netif glue copied the driver MAC when ETH.begin() attached it, so BOTH must change:
// with only the driver updated the W5500 filters on the new address while lwIP still
// sends the old one, and DHCP never completes (seen on the bench: link up, no lease).
static void _applyUniversalMac()
{
uint8_t previousMac[ETH_ADDR_LEN];
uint8_t mac[ETH_ADDR_LEN];
esp_err_t err = esp_eth_ioctl(ETH.handle(), ETH_CMD_G_MAC_ADDR, previousMac);
if (err == ESP_OK) err = esp_efuse_mac_get_default(mac);
if (err == ESP_OK) {
mac[ETH_ADDR_LEN - 1] += 1;
err = esp_eth_ioctl(ETH.handle(), ETH_CMD_S_MAC_ADDR, mac);
}
if (err == ESP_OK) {
err = esp_netif_set_mac(ETH.netif(), mac);
// Never leave the two halves disagreeing: put the driver back on the old address.
if (err != ESP_OK) esp_eth_ioctl(ETH.handle(), ETH_CMD_S_MAC_ADDR, previousMac);
}
if (err != ESP_OK) LOG_WARNING("Could not set the universal Ethernet MAC (%s) - keeping the core default", esp_err_to_name(err));
}
bool registerEvents()
{
if (!globalHwProfile->hasEthernet) return true;
if (_eventsRegistered) return true;
if (!createMutexIfNeeded(&_ctxMutex)) return false;
InterfaceArbitration::init(_arbCtx);
// The handler runs in the core's Network event task: it only copies state under
// the mutex and pokes the eth task, which does the actual work.
Network.onEvent(_onNetworkEvent);
_eventsRegistered = true;
return true;
}
bool begin()
{
if (!globalHwProfile->hasEthernet) {
LOG_DEBUG("Product has no Ethernet - CustomEth disabled");
return true;
}
if (_ethTaskHandle != NULL) {
LOG_DEBUG("Ethernet task is already running");
return true;
}
LOG_DEBUG("Starting Ethernet (W5500)...");
if (!registerEvents()) return false;
_loadConfiguration();
// Latched before the driver starts: see _staticIntent.
{
EthConfiguration config;
_bootFailsAtBoot = _getStaticBootFails();
_staticIntent = getConfiguration(config) && config.useStaticIp &&
_bootFailsAtBoot < ETH_STATIC_MAX_BOOT_FAILS;
}
// Dedicated SPI bus (the ADE7953 owns the default SPI): no bus sharing,
// no cross-task SPI arbitration needed.
_spi = new SPIClass(HSPI);
_spi->begin(globalHwProfile->ethSckPin, globalHwProfile->ethMisoPin,
globalHwProfile->ethMosiPin, globalHwProfile->ethCsPin);
if (!ETH.begin(ETH_PHY_W5500, ETH_PHY_ADDR_W5500,
globalHwProfile->ethCsPin, globalHwProfile->ethIrqPin,
globalHwProfile->ethRstPin, *_spi, ETH_SPI_FREQ_MHZ)) {
LOG_ERROR("W5500 initialization failed - Ethernet unavailable this boot");
_spi->end();
delete _spi;
_spi = nullptr;
return false;
}
_applyUniversalMac();
// Same hostname as the WiFi interface: one device, one name in the DHCP lease table.
// Only after begin(): the core drops setHostname() while the netif does not exist yet
// (the router then lists the device as "espressif"). Still ahead of DHCP, which
// waits for link-up.
char hostname[WIFI_HOSTNAME_BUFFER_SIZE];
snprintf(hostname, sizeof(hostname), "%s-%.*s", WIFI_HOSTNAME_PREFIX, WIFI_HOSTNAME_DEVICE_ID_LENGTH, DEVICE_ID);
if (!ETH.setHostname(hostname)) LOG_WARNING("Could not set the Ethernet hostname to %s", hostname);
_applyStaticConfiguration();
_stopRequested = false;
BaseType_t created = xTaskCreate(_ethTask, ETH_TASK_NAME, ETH_TASK_STACK_SIZE, NULL, ETH_TASK_PRIORITY, &_ethTaskHandle);
if (created != pdPASS) {
LOG_ERROR("Failed to create Ethernet task");
_ethTaskHandle = NULL;
return false;
}
_enabled = true;
LOG_INFO("Ethernet started");
LOG_DEBUG("Ethernet pins: CS=%u IRQ=%u RST=%u", globalHwProfile->ethCsPin,
globalHwProfile->ethIrqPin, globalHwProfile->ethRstPin);
return true;
}
void stop()
{
if (_ethTaskHandle == NULL) return;
_stopRequested = true;
_notifyEthTask();
}
bool isEnabled() { return _enabled; }
bool isCommissioned()
{
// Monotonic: once commissioned, always commissioned this boot (only a factory reset
// clears the marker, and that path restarts). NVS is read once; after that the eth
// task is the only source of change and it publishes through _commissioned, so
// callers can poll this from any task at the cost of a bool load.
if (!globalHwProfile->hasEthernet) return false; // No wire to be commissioned over, and no eth_ns to probe
if (_commissioned) return true;
if (_commissionedNvsChecked) return false;
_commissionedNvsChecked = true;
Preferences prefs;
if (!prefs.begin(PREFERENCES_NAMESPACE_ETH, true)) return false; // eth_ns never written (Home, or factory-fresh Pro)
if (prefs.getBool(ETH_COMMISSIONED_KEY, false)) _commissioned = true;
prefs.end();
return _commissioned;
}
// One mutex hold for everything readers need; every predicate derives from it.
struct Snapshot {
InterfaceArbitration::Interface active;
bool linkUp;
bool serviceable; // link + address + lwIP settle time elapsed
uint64_t serviceableSinceMs;
};
static Snapshot _snapshot()
{
Snapshot snap = {InterfaceArbitration::Interface::NONE, false, false, 0};
if (_ctxMutex == NULL || !acquireMutex(&_ctxMutex)) return snap;
snap.active = _arbCtx.active;
snap.linkUp = _arbCtx.ethLinkUp;
snap.serviceableSinceMs = _arbCtx.ethServiceableSinceMs;
bool raw = InterfaceArbitration::isEthServiceable(_arbCtx);
releaseMutex(&_ctxMutex);
// Same reasoning as WIFI_LWIP_STABILIZATION_DELAY: give lwIP a moment
// after the address appears before services pile onto the netif.
snap.serviceable = raw && snap.serviceableSinceMs != 0 &&
(millis64() - snap.serviceableSinceMs) >= ETH_LWIP_STABILIZATION_DELAY;
return snap;
}
bool isLinkUp()
{
if (!_enabled) return false;
return _snapshot().linkUp;
}
bool isServiceable()
{
if (!_enabled) return false;
return _snapshot().serviceable;
}
InterfaceArbitration::Interface activeInterface()
{
return _snapshot().active;
}
void notifyStaState(bool connected)
{
if (_ctxMutex == NULL) return; // Home, or before registerEvents(): nothing to arbitrate
if (!acquireMutex(&_ctxMutex)) return;
InterfaceArbitration::onStaState(_arbCtx, connected);
releaseMutex(&_ctxMutex);
_notifyEthTask();
}
bool onInterfaceChange(InterfaceChangeCallback callback)
{
if (callback == nullptr || _callbackCount >= ETH_MAX_INTERFACE_CALLBACKS) return false;
_callbacks[_callbackCount++] = callback;
return true;
}
// ------------------------------------------------------------------
// Events and arbitration
// ------------------------------------------------------------------
static void _onNetworkEvent(arduino_event_id_t event)
{
switch (event) {
case ARDUINO_EVENT_ETH_CONNECTED:
// Backstop accounting: count the attempt at first link-up, so a
// crash caused by the static config still accumulates, while a
// cable-out boot (no link ever) stays neutral per the spec. The
// NVS write is deferred to the eth task (see _bootFailCounted;
// same rule as _onWiFiEvent).
if (_staticIntent) _bootFailCounted = true;
_updateEthState(true, ETH.hasIP());
break;
case ARDUINO_EVENT_ETH_GOT_IP:
// Plain lwIP reads, no esp_netif call from this task. A static config
// filled the cache itself.
if (!_staticApplied) {
_ethDns[0] = lwipDnsServer(0);
_ethDns[1] = lwipDnsServer(1);
}
_updateEthState(true, true);
break;
case ARDUINO_EVENT_ETH_LOST_IP:
_updateEthState(ETH.linkUp(), false);
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
case ARDUINO_EVENT_ETH_STOP:
_updateEthState(false, false);
break;
default:
return;
}
// The cloud copy of the Ethernet state lives in the wifi shadow. A standby link
// changing state forces no MQTT reconnect, so flag it here (flag only, any task).
Shadow::requestReport("wifi");
}
static void _updateEthState(bool linkUp, bool hasAddress)
{
if (!acquireMutex(&_ctxMutex)) return;
InterfaceArbitration::onEthState(_arbCtx, linkUp, hasAddress, millis64());
releaseMutex(&_ctxMutex);
_notifyEthTask();
}
static void _notifyEthTask()
{
if (_ethTaskHandle != NULL) xTaskNotifyGive(_ethTaskHandle);
}
// Runs in the eth task only - never from the Network event task (no logging there).
static void _logLinkDetails()
{
LOG_INFO("Ethernet up: IP %s | Gateway %s | Subnet %s | DNS %s | MAC %s | %u Mbps %s duplex | %s",
ETH.localIP().toString().c_str(), ETH.gatewayIP().toString().c_str(),
ETH.subnetMask().toString().c_str(), ETH.dnsIP(0).toString().c_str(),
ETH.macAddress().c_str(), (unsigned)ETH.linkSpeed(),
ETH.fullDuplex() ? "full" : "half",
_staticApplied ? "static" : "DHCP");
}
static void _ethTask(void *parameter)
{
(void)parameter;
LOG_DEBUG("Ethernet task started");
bool mdnsEnsured = false;
bool serviceableAnnounced = false;
bool bootFailPersisted = false;
bool backstopCleared = false;
bool commissionAttempted = false;
while (!_stopRequested) {
TASK_HEARTBEAT(_heartbeat);
// Deferred from the Network event task (see ARDUINO_EVENT_ETH_CONNECTED).
if (_bootFailCounted && !bootFailPersisted) {
bootFailPersisted = true;
_setStaticBootFails((uint8_t)(_bootFailsAtBoot + 1));
}
_evaluateArbitration();
Snapshot snap = _snapshot();
_keepDnsOnActiveInterface(snap.active);
if (snap.serviceable) {
// First proof of being in service on the wire: persist the
// commissioning marker so the provisioning state machine never
// treats this device as UNPROVISIONED again (the auth carve-out
// must not re-arm on a recovery-AP raise months into service).
// Published BEFORE the WiFi task is woken below: that task polls
// isCommissioned() and closes the carve-out for this boot too.
// One attempt per boot even on write failure - no per-tick NVS churn;
// a failed write only costs the NEXT boot its head start.
if (!commissionAttempted && !isCommissioned()) {
commissionAttempted = true;
Preferences prefs;
bool persisted = false;
if (prefs.begin(PREFERENCES_NAMESPACE_ETH, false)) {
persisted = prefs.putBool(ETH_COMMISSIONED_KEY, true) > 0;
prefs.end();
}
_commissioned = true;
if (persisted) LOG_INFO("Device commissioned over Ethernet - marker persisted");
else LOG_WARNING("Device commissioned over Ethernet for this boot, but the marker could not be persisted");
}
if (!serviceableAnnounced) {
serviceableAnnounced = true;
_logLinkDetails();
// The WiFi task owns the recovery AP and the network LED layer: wake it
// so both follow the wire now instead of at its next periodic tick.
CustomWifi::notifyWiredStateChanged();
}
// An Ethernet-only device (no WiFi credentials) never runs the WiFi
// connect path that starts mDNS - kick it here on the serviceable
// rising edge. Idempotent on devices where WiFi already started it.
if (!mdnsEnsured) {
mdnsEnsured = CustomWifi::ensureMdnsStarted();
}
// Same story as mDNS above: the WiFi connect path requests the one-shot
// telemetry ping itself, which an Ethernet-only device never runs.
// Cheap to call every tick: it only spawns the telemetry task, rate-
// limited and capped per boot inside CustomWifi.
CustomWifi::sendOpenSourceTelemetry();
// Backstop clear: the static config has held the interface serviceable
// past the crash window, so it is not a boot-loop offender. That is all it
// proves: a static address is "serviceable" the moment the link is up, so a
// wrong-but-valid address is not caught here (recovery: pull the cable, which
// raises the access point, or the button network reset).
if (_staticApplied && !backstopCleared &&
(millis64() - snap.serviceableSinceMs) >= ETH_STATIC_STABLE_CLEAR_MS) {
_setStaticBootFails(0);
backstopCleared = true;
LOG_INFO("Static Ethernet IP stable - boot-fail backstop counter cleared");
}
} else {
if (serviceableAnnounced) {
serviceableAnnounced = false;
LOG_WARNING("Ethernet no longer serviceable (link %s)", snap.linkUp ? "up, no address" : "down");
CustomWifi::notifyWiredStateChanged();
}
mdnsEnsured = false;
}
// Event-driven with a tick fallback: events poke us immediately, the
// timeout re-evaluates timers (hold-down, stable window).
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(ETH_TASK_TICK_MS));
}
LOG_DEBUG("Ethernet task stopping");
_ethTaskHandle = NULL;
vTaskDelete(NULL);
}
static void _evaluateArbitration()
{
if (!acquireMutex(&_ctxMutex)) return;
InterfaceArbitration::Interface previous = _arbCtx.active;
InterfaceArbitration::Decision decision = InterfaceArbitration::evaluateAndApply(_arbCtx, millis64());
releaseMutex(&_ctxMutex);
if (!decision.switchRequired) return;
LOG_INFO("Default network interface: %s -> %s",
InterfaceArbitration::interfaceName(previous),
InterfaceArbitration::interfaceName(decision.preferred));
// Route change first, then DNS, then the consumers drop their sessions
// so they reconnect on the new path immediately.
bool routed = true;
if (decision.preferred == InterfaceArbitration::Interface::ETHERNET) {
routed = Network.setDefaultInterface(ETH);
} else if (decision.preferred == InterfaceArbitration::Interface::WIFI_STATION) {
routed = Network.setDefaultInterface(WiFi.STA);
}
if (!routed) {
// Not switched: roll the decision back so the next tick tries again
LOG_WARNING("Failed to set %s as default interface", InterfaceArbitration::interfaceName(decision.preferred));
if (acquireMutex(&_ctxMutex)) {
_arbCtx.active = previous;
releaseMutex(&_ctxMutex);
}
return;
}
_applyDnsForActiveInterface(decision.preferred);
for (size_t i = 0; i < _callbackCount; i++) {
if (_callbacks[i] != nullptr) _callbacks[i](decision.preferred);
}
}
// False when nothing is known for this interface (no lease seen yet).
static bool _dnsServersOf(InterfaceArbitration::Interface iface, IPAddress &dns1, IPAddress &dns2)
{
if (iface == InterfaceArbitration::Interface::ETHERNET) {
dns1 = IPAddress(_ethDns[0]);
dns2 = IPAddress(_ethDns[1]);
} else if (iface == InterfaceArbitration::Interface::WIFI_STATION) {
CustomWifi::getStaDnsServers(dns1, dns2);
} else {
return false;
}
return dns1 != IPAddress(0, 0, 0, 0);
}
// Both interfaces stay up, and every lease the OTHER one takes or renews rewrites the
// resolver list with its own servers, with no event and no route switch to hang a
// re-apply on. So the list is checked against the active interface on every tick.
static void _keepDnsOnActiveInterface(InterfaceArbitration::Interface active)
{
IPAddress dns1, dns2;
if (!_dnsServersOf(active, dns1, dns2)) return;
if (lwipDnsServer(0) == (uint32_t)dns1) return;
_applyDnsForActiveInterface(active);
}
// lwIP's DNS server list is global, not per-netif: after a failover the
// resolver keeps the OLD interface's servers (fatal when a static ETH DNS
// sits on a now-unreachable segment). Put back what the new interface brought:
// reading ETH.dnsIP() / WiFi.STA.dnsIP() would only return that same global list.
static void _applyDnsForActiveInterface(InterfaceArbitration::Interface active)
{
IPAddress dns1, dns2;
if (!_dnsServersOf(active, dns1, dns2)) return; // Leave the list as it is
// Every slot, empty ones included: one left over from the other interface may
// not be reachable from this one. Under the core lock: the tcpip thread writes
// the same list on DHCP leases (CONFIG_LWIP_TCPIP_CORE_LOCKING=y).
LOCK_TCPIP_CORE();
for (int i = 0; i < DNS_MAX_SERVERS; i++) {
IPAddress dns = (i == 0) ? dns1 : (i == 1) ? dns2 : IPAddress(0, 0, 0, 0);
ip_addr_t addr = IPADDR4_INIT((uint32_t)dns); // Fully initialized - no garbage union bytes
dns_setserver((u8_t)i, &addr);
}
UNLOCK_TCPIP_CORE();
LOG_DEBUG("DNS reapplied for %s: %s / %s", InterfaceArbitration::interfaceName(active),
dns1.toString().c_str(), dns2.toString().c_str());
}
// ------------------------------------------------------------------
// Configuration (mirrors the CustomWifi config module pattern)
// ------------------------------------------------------------------
bool getConfiguration(EthConfiguration &config)
{
if (!acquireMutex(&_configMutex)) {
LOG_ERROR("Failed to acquire configuration mutex for getConfiguration");
return false;
}
config = _configuration;
releaseMutex(&_configMutex);
return true;
}
bool setConfiguration(const EthConfiguration &config)
{
if (!_validateConfiguration(config)) {
LOG_WARNING("Refusing to set invalid Ethernet configuration");
return false;
}
if (!createMutexIfNeeded(&_configMutex)) return false;
if (!acquireMutex(&_configMutex)) {
LOG_ERROR("Failed to acquire configuration mutex for setConfiguration");
return false;
}
_configuration = config;
releaseMutex(&_configMutex);
_saveConfigurationToPreferences(config);
LOG_DEBUG("Ethernet configuration set");
return true;
}
bool resetConfiguration()
{
// Nothing to reset while eth_ns has never been written - and writing here
// would CREATE it, breaking the "no namespace on Home" contract (the button
// network reset calls this unconditionally on every product).
{
Preferences probe;
if (!probe.begin(PREFERENCES_NAMESPACE_ETH, true)) {
LOG_DEBUG("No Ethernet configuration stored - nothing to reset");
return true;
}
probe.end();
}
LOG_DEBUG("Resetting Ethernet configuration to default");
EthConfiguration defaultConfig;
if (!setConfiguration(defaultConfig)) {
LOG_ERROR("Failed to reset Ethernet configuration");
return false;
}
_setStaticBootFails(0); // Clean slate - default config is DHCP anyway
LOG_INFO("Ethernet configuration reset to default");
return true;
}
bool getConfigurationAsJson(JsonDocument &jsonDocument)
{
EthConfiguration config;
if (!getConfiguration(config)) return false;
configurationToJson(config, jsonDocument);
return true;
}
bool setConfigurationFromJson(JsonDocument &jsonDocument, bool partial)
{
EthConfiguration config;
getConfiguration(config);
if (!configurationFromJson(jsonDocument, config, partial)) {
LOG_ERROR("Failed to set Ethernet configuration from JSON");
return false;
}
if (!setConfiguration(config)) return false;
// A user-saved config is the escape hatch: fresh boot attempts for the
// (possibly new) static IP so the backstop doesn't keep it disabled.
_setStaticBootFails(0);
return true;
}
void configurationToJson(const EthConfiguration &config, JsonDocument &jsonDocument)
{
jsonDocument["useStaticIp"] = config.useStaticIp;
jsonDocument["ip"] = JsonString(config.ip);
jsonDocument["gateway"] = JsonString(config.gateway);
jsonDocument["subnet"] = JsonString(config.subnet);
jsonDocument["dns1"] = JsonString(config.dns1);
jsonDocument["dns2"] = JsonString(config.dns2);
}
bool configurationFromJson(JsonDocument &jsonDocument, EthConfiguration &config, bool partial)
{
if (!_validateJsonConfiguration(jsonDocument, partial)) {
LOG_WARNING("Invalid Ethernet configuration JSON");
return false;
}
if (jsonDocument["useStaticIp"].is<bool>()) config.useStaticIp = jsonDocument["useStaticIp"].as<bool>();
if (jsonDocument["ip"].is<const char*>()) snprintf(config.ip, sizeof(config.ip), "%s", jsonDocument["ip"].as<const char*>());
if (jsonDocument["gateway"].is<const char*>()) snprintf(config.gateway, sizeof(config.gateway), "%s", jsonDocument["gateway"].as<const char*>());
if (jsonDocument["subnet"].is<const char*>()) snprintf(config.subnet, sizeof(config.subnet), "%s", jsonDocument["subnet"].as<const char*>());
if (jsonDocument["dns1"].is<const char*>()) snprintf(config.dns1, sizeof(config.dns1), "%s", jsonDocument["dns1"].as<const char*>());
if (jsonDocument["dns2"].is<const char*>()) snprintf(config.dns2, sizeof(config.dns2), "%s", jsonDocument["dns2"].as<const char*>());
return _validateConfiguration(config);
}
void getStatusAsJson(JsonDocument &jsonDocument)
{
jsonDocument["enabled"] = _enabled;
if (!_enabled) {
// No eth task runs arbitration (W5500 failed to start), so WiFi is all there is
jsonDocument["activeInterface"] = InterfaceArbitration::interfaceName(
WiFi.isConnected() ? InterfaceArbitration::Interface::WIFI_STATION : InterfaceArbitration::Interface::NONE);
return;
}
jsonDocument["activeInterface"] = InterfaceArbitration::interfaceName(activeInterface());
jsonDocument["linkUp"] = isLinkUp();
jsonDocument["serviceable"] = isServiceable();
jsonDocument["staticApplied"] = _staticApplied;
jsonDocument["ip"] = ETH.localIP().toString();
jsonDocument["gateway"] = ETH.gatewayIP().toString();
jsonDocument["subnet"] = ETH.subnetMask().toString();
// Ethernet's own servers: ETH.dnsIP() reads lwIP's single global list, which holds
// WiFi's servers while WiFi has the route
jsonDocument["dns1"] = IPAddress(_ethDns[0]).toString();
jsonDocument["dns2"] = IPAddress(_ethDns[1]).toString();
jsonDocument["mac"] = ETH.macAddress();
}
static void _loadConfiguration()
{
LOG_DEBUG("Loading Ethernet configuration from Preferences...");
EthConfiguration config;
// Read-only open fails when eth_ns does not exist yet: that is the lazy-
// creation contract (the namespace is only ever created by a write), so
// fall through to defaults silently rather than materializing it here.
Preferences preferences;
if (preferences.begin(PREFERENCES_NAMESPACE_ETH, true)) {
config.useStaticIp = preferences.getBool(ETH_CONFIG_USE_STATIC_KEY, false);
snprintf(config.ip, sizeof(config.ip), "%s", preferences.getString(ETH_CONFIG_IP_KEY, "").c_str());
snprintf(config.gateway, sizeof(config.gateway), "%s", preferences.getString(ETH_CONFIG_GATEWAY_KEY, "").c_str());
snprintf(config.subnet, sizeof(config.subnet), "%s", preferences.getString(ETH_CONFIG_SUBNET_KEY, "").c_str());
snprintf(config.dns1, sizeof(config.dns1), "%s", preferences.getString(ETH_CONFIG_DNS1_KEY, "").c_str());
snprintf(config.dns2, sizeof(config.dns2), "%s", preferences.getString(ETH_CONFIG_DNS2_KEY, "").c_str());
preferences.end();
}
if (!createMutexIfNeeded(&_configMutex)) return;
if (acquireMutex(&_configMutex)) {
if (_validateConfiguration(config)) {
_configuration = config;
} else {
LOG_WARNING("Stored Ethernet configuration invalid - reverting to defaults (DHCP)");
_configuration = EthConfiguration();
}
releaseMutex(&_configMutex);
}
LOG_DEBUG("Ethernet configuration loaded");
}
static void _saveConfigurationToPreferences(const EthConfiguration &config)
{
// First write creates eth_ns (lazy) - this never runs on a Home device
// because the endpoints are product-gated and begin() no-ops there.
Preferences preferences;
if (!preferences.begin(PREFERENCES_NAMESPACE_ETH, false)) {
LOG_ERROR("Failed to open Preferences namespace for Ethernet");
return;
}
preferences.putBool(ETH_CONFIG_USE_STATIC_KEY, config.useStaticIp);
preferences.putString(ETH_CONFIG_IP_KEY, config.ip);
preferences.putString(ETH_CONFIG_GATEWAY_KEY, config.gateway);
preferences.putString(ETH_CONFIG_SUBNET_KEY, config.subnet);
preferences.putString(ETH_CONFIG_DNS1_KEY, config.dns1);
preferences.putString(ETH_CONFIG_DNS2_KEY, config.dns2);
preferences.end();
LOG_DEBUG("Ethernet configuration saved to Preferences");
}
static void _applyStaticConfiguration()
{
_staticApplied = false;
// _staticIntent already folds in useStaticIp and the backstop (latched in
// begin(), the single owner of that rule this boot).
if (!_staticIntent) {
EthConfiguration config;
if (getConfiguration(config) && config.useStaticIp) {
LOG_WARNING("Static Ethernet IP disabled after %u failed boots - using DHCP (config kept, save again to retry)", _bootFailsAtBoot);
} else {
LOG_DEBUG("Using DHCP for Ethernet IP configuration");
}
return;
}
EthConfiguration config;
if (!getConfiguration(config)) return;
IPAddress ip, gateway, subnet, dns1, dns2;
if (!(ip.fromString(config.ip) && gateway.fromString(config.gateway) && subnet.fromString(config.subnet))) {
LOG_WARNING("Static Ethernet IP enabled but addresses invalid - using DHCP");
return;
}
if (!dns1.fromString(config.dns1)) dns1 = gateway; // Routers commonly relay DNS
dns2.fromString(config.dns2); // Optional - stays 0.0.0.0 when empty
if (ETH.config(ip, gateway, subnet, dns1, dns2)) {
_staticApplied = true;
_ethDns[0] = (uint32_t)dns1;
_ethDns[1] = (uint32_t)dns2;
LOG_INFO("Static Ethernet IP configured: %s (gateway: %s, attempt %u)", config.ip, config.gateway, _bootFailsAtBoot + 1);
} else {
LOG_ERROR("Failed to apply static Ethernet IP configuration - falling back to DHCP");
}
}
static bool _validateJsonConfiguration(JsonDocument &jsonDocument, bool partial)
{
if (jsonDocument.isNull() || !jsonDocument.is<JsonObject>()) {
LOG_WARNING("Invalid JSON document");
return false;
}
if (partial) {
if (jsonDocument["useStaticIp"].is<bool>()) return true;
if (jsonDocument["ip"].is<const char*>()) return true;
if (jsonDocument["gateway"].is<const char*>()) return true;
if (jsonDocument["subnet"].is<const char*>()) return true;
if (jsonDocument["dns1"].is<const char*>()) return true;
if (jsonDocument["dns2"].is<const char*>()) return true;
LOG_WARNING("No valid fields found in JSON document");
return false;
}
if (!jsonDocument["useStaticIp"].is<bool>()) { LOG_WARNING("useStaticIp field is not a boolean"); return false; }
if (!jsonDocument["ip"].is<const char*>()) { LOG_WARNING("ip field is not a string"); return false; }
if (!jsonDocument["gateway"].is<const char*>()) { LOG_WARNING("gateway field is not a string"); return false; }
if (!jsonDocument["subnet"].is<const char*>()) { LOG_WARNING("subnet field is not a string"); return false; }
if (!jsonDocument["dns1"].is<const char*>()) { LOG_WARNING("dns1 field is not a string"); return false; }
if (!jsonDocument["dns2"].is<const char*>()) { LOG_WARNING("dns2 field is not a string"); return false; }
return true;
}
static bool _validateConfiguration(const EthConfiguration &config)
{
if (!config.useStaticIp) return true;
if (!isValidIpv4(config.ip, false)) { LOG_WARNING("Static IP enabled but 'ip' is invalid"); return false; }
if (!isValidIpv4(config.gateway, false)) { LOG_WARNING("Static IP enabled but 'gateway' is invalid"); return false; }
if (!isValidIpv4(config.subnet, false)) { LOG_WARNING("Static IP enabled but 'subnet' is invalid"); return false; }
if (config.dns1[0] != '\0' && !isValidIpv4(config.dns1, true)) { LOG_WARNING("Invalid 'dns1' address"); return false; }
if (config.dns2[0] != '\0' && !isValidIpv4(config.dns2, true)) { LOG_WARNING("Invalid 'dns2' address"); return false; }
auto toHostOrder = [](const char *text) {
IPAddress address;
address.fromString(text);
return ((uint32_t)address[0] << 24) | ((uint32_t)address[1] << 16) | ((uint32_t)address[2] << 8) | (uint32_t)address[3];
};
uint32_t ipHost = toHostOrder(config.ip);
uint32_t gatewayHost = toHostOrder(config.gateway);
uint32_t maskHost = toHostOrder(config.subnet);
// A static address is "serviceable" the moment the link is up, so nothing at run
// time catches a wrong one: no access point is raised and the device just sits
// unreachable. Refuse the mistakes that can be told apart from a working config.
if (WifiProvisioning::cidrFromNetmask(maskHost) == 0) {
LOG_WARNING("Subnet mask %s is not a valid mask - rejected", config.subnet);
return false;
}
if ((ipHost & maskHost) != (gatewayHost & maskHost)) {
LOG_WARNING("Gateway %s is outside the network of %s/%s - rejected", config.gateway, config.ip, config.subnet);
return false;
}
// Each of these still counts as "serviceable" once the link is up, so no AP would
// rise and the device would sit unreachable
if (ipHost == gatewayHost) {
LOG_WARNING("Static IP %s equals the gateway - rejected", config.ip);
return false;
}
if (WifiProvisioning::cidrFromNetmask(maskHost) < 31 &&
((ipHost & ~maskHost) == 0 || (ipHost | maskHost) == 0xFFFFFFFFUL)) {
LOG_WARNING("Static IP %s is the network or broadcast address of %s - rejected", config.ip, config.subnet);
return false;
}
// A static address inside the recovery SoftAP's default subnet would route
// ambiguously exactly when the AP is most needed. Only the default candidate
// is rejected outright: the AP subnet selection avoids the other candidates
// dynamically (it accounts for the ETH subnet like it does for STA).
WifiProvisioning::Subnet apDefault = WifiProvisioning::candidateSubnet(0);
if (WifiProvisioning::subnetsOverlap(ipHost, apDefault.cidr, apDefault.address, apDefault.cidr)) {
LOG_WARNING("Static IP %s overlaps the recovery access point subnet - rejected", config.ip);
return false;
}
return true;
}
static uint8_t _getStaticBootFails()
{
Preferences preferences;
if (!preferences.begin(PREFERENCES_NAMESPACE_ETH, true)) return 0;
uint8_t count = preferences.getUChar(ETH_CONFIG_STATIC_FAILS_KEY, 0);
preferences.end();
return count;
}
static void _setStaticBootFails(uint8_t count)
{
Preferences preferences;
if (!preferences.begin(PREFERENCES_NAMESPACE_ETH, false)) {
LOG_ERROR("Failed to open Preferences to update static boot-fail counter");
return;
}
preferences.putUChar(ETH_CONFIG_STATIC_FAILS_KEY, count);
preferences.end();
}
TaskInfo getTaskInfo()
{
return getTaskInfoSafely(_ethTaskHandle, ETH_TASK_STACK_SIZE, &_heartbeat);
}
}