feat: merge master Ethernet support into dev

Adapt W5500 to the native network event queue and select STA or ETH from NetworkSettings. Preserve the existing dev network settings and add a separate C6 Ethernet build without BLE to fit the OTA slot.

Validate with S3 and C6 Ethernet firmware builds, the shared LittleFS image, binary layout checks and targeted network transition checks.
This commit is contained in:
Yurii committed 2026-11-23 21:06:26 +03:00
commit 4e71915222
21 files changed
+1007 -158

No files matched your search

+105 -34
View File
@@ -164,6 +164,7 @@ void saveSettingsNow() {
// Initialization
static bool loadNetworkSettings() {
bool loaded = false;
fsNetworkSettings.addWithoutWipe(true);
switch (fsNetworkSettings.read()) {
case FD_FS_ERR:
@@ -341,13 +342,26 @@ JsonVariant toJson(const NetworkSettings& src, JsonVariant dst) {
dst[S_STATIC_CONFIG][S_SUBNET] = src.staticConfig.subnet;
dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns;
dst[S_AP][S_SSID] = src.ap.ssid;
dst[S_AP][S_PASSWORD] = src.ap.password;
dst[S_AP][S_CHANNEL] = src.ap.channel;
auto wifi = dst[S_WIFI].to<JsonObject>();
wifi[S_AP][S_SSID] = src.wifi.ap.ssid;
wifi[S_AP][S_PASSWORD] = src.wifi.ap.password;
wifi[S_AP][S_CHANNEL] = src.wifi.ap.channel;
dst[S_STA][S_SSID] = src.sta.ssid;
dst[S_STA][S_PASSWORD] = src.sta.password;
dst[S_STA][S_CHANNEL] = src.sta.channel;
wifi[S_STA][S_SSID] = src.wifi.sta.ssid;
wifi[S_STA][S_PASSWORD] = src.wifi.sta.password;
wifi[S_STA][S_CHANNEL] = src.wifi.sta.channel;
#if USE_ETHERNET
auto gpio = dst[S_ETHERNET][S_GPIO].to<JsonObject>();
gpio[S_CLK] = src.ethernet.w5500.clk;
gpio[S_MOSI] = src.ethernet.w5500.mosi;
gpio[S_MISO] = src.ethernet.w5500.miso;
gpio[S_CS] = src.ethernet.w5500.cs;
gpio[S_IRQ] = src.ethernet.w5500.irq;
gpio[S_RST] = src.ethernet.w5500.rst;
#endif
dst[S_TYPE] = static_cast<uint8_t>(src.type);
return dst;
}
@@ -430,39 +444,43 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
}
const auto wifi = src[S_WIFI];
const auto ap = wifi[S_AP];
const auto sta = wifi[S_STA];
// ap
if (src[S_AP][S_SSID].is<JsonString>()) {
const JsonString value = src[S_AP][S_SSID].as<JsonString>();
if (ap[S_SSID].is<JsonString>()) {
const JsonString value = ap[S_SSID].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.ap.ssid)) {
if (value.size() && value.size() < sizeof(dst.wifi.ap.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ap.ssid) != 0) {
strcpy(dst.ap.ssid, value.c_str());
if (strcmp(value.c_str(), dst.wifi.ap.ssid) != 0) {
strcpy(dst.wifi.ap.ssid, value.c_str());
result.changed = true;
}
}
}
if (src[S_AP][S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_AP][S_PASSWORD].as<JsonString>();
if (ap[S_PASSWORD].is<JsonString>()) {
const JsonString value = ap[S_PASSWORD].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.ap.password)) {
if (value.size() && value.size() < sizeof(dst.wifi.ap.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.ap.password) != 0) {
strcpy(dst.ap.password, value.c_str());
if (strcmp(value.c_str(), dst.wifi.ap.password) != 0) {
strcpy(dst.wifi.ap.password, value.c_str());
result.changed = true;
}
}
}
if (src[S_AP][S_CHANNEL].is<uint8_t>()) {
const auto value = src[S_AP][S_CHANNEL].as<uint8_t>();
if (ap[S_CHANNEL].is<uint8_t>()) {
const auto value = ap[S_CHANNEL].as<uint8_t>();
if (value < 12) {
result.accepted = true;
if (value != dst.ap.channel) {
dst.ap.channel = value;
if (value != dst.wifi.ap.channel) {
dst.wifi.ap.channel = value;
result.changed = true;
}
}
@@ -470,38 +488,88 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
// sta
if (src[S_STA][S_SSID].is<JsonString>()) {
const JsonString value = src[S_STA][S_SSID].as<JsonString>();
if (sta[S_SSID].is<JsonString>()) {
const JsonString value = sta[S_SSID].as<JsonString>();
if (value.size() && value.size() < sizeof(dst.sta.ssid)) {
if (value.size() && value.size() < sizeof(dst.wifi.sta.ssid)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.sta.ssid) != 0) {
strcpy(dst.sta.ssid, value.c_str());
if (strcmp(value.c_str(), dst.wifi.sta.ssid) != 0) {
strcpy(dst.wifi.sta.ssid, value.c_str());
result.changed = true;
}
}
}
if (src[S_STA][S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_STA][S_PASSWORD].as<JsonString>();
if (sta[S_PASSWORD].is<JsonString>()) {
const JsonString value = sta[S_PASSWORD].as<JsonString>();
if (value.size() < sizeof(dst.sta.password)) {
if (value.size() < sizeof(dst.wifi.sta.password)) {
result.accepted = true;
if (strcmp(value.c_str(), dst.sta.password) != 0) {
strcpy(dst.sta.password, value.c_str());
if (strcmp(value.c_str(), dst.wifi.sta.password) != 0) {
strcpy(dst.wifi.sta.password, value.c_str());
result.changed = true;
}
}
}
if (src[S_STA][S_CHANNEL].is<uint8_t>()) {
const auto value = src[S_STA][S_CHANNEL].as<uint8_t>();
if (sta[S_CHANNEL].is<uint8_t>()) {
const auto value = sta[S_CHANNEL].as<uint8_t>();
if (value < 12) {
result.accepted = true;
if (value != dst.sta.channel) {
dst.sta.channel = value;
if (value != dst.wifi.sta.channel) {
dst.wifi.sta.channel = value;
result.changed = true;
}
}
}
#if USE_ETHERNET
// Ethernet GPIOs use the same strict numeric contract as the other GPIO settings.
const auto ethernet = src[S_ETHERNET];
const auto parseGpio = [&result](JsonVariantConst gpio, uint8_t& target, bool output) {
uint8_t value;
if (gpio.is<JsonString>() && gpio.as<JsonString>().size() == 0) {
value = GPIO_IS_NOT_CONFIGURED;
} else if (gpio.is<uint8_t>()) {
value = gpio.as<uint8_t>();
} else {
return;
}
if (value != GPIO_IS_NOT_CONFIGURED && !(output ? GPIO_IS_VALID_OUTPUT(value) : GPIO_IS_VALID_INPUT(value))) {
return;
}
result.accepted = true;
if (value != target) {
target = value;
result.changed = true;
}
};
const auto gpio = ethernet[S_GPIO];
parseGpio(gpio[S_CLK], dst.ethernet.w5500.clk, true);
parseGpio(gpio[S_MOSI], dst.ethernet.w5500.mosi, true);
parseGpio(gpio[S_MISO], dst.ethernet.w5500.miso, false);
parseGpio(gpio[S_CS], dst.ethernet.w5500.cs, true);
parseGpio(gpio[S_IRQ], dst.ethernet.w5500.irq, false);
parseGpio(gpio[S_RST], dst.ethernet.w5500.rst, true);
#endif
if (src[S_TYPE].is<uint8_t>()) {
const auto value = static_cast<NetworkMode>(src[S_TYPE].as<uint8_t>());
if (value == NetworkMode::STA
#if USE_ETHERNET
|| value == NetworkMode::ETH
#endif
) {
result.accepted = true;
if (value != dst.type) {
dst.type = value;
result.changed = true;
}
}
@@ -3167,7 +3235,9 @@ SettingResult fromJson(const JsonVariantConst src, Sensors::Settings& dst) {
case static_cast<uint8_t>(Sensors::Type::NTC_10K_TEMP):
case static_cast<uint8_t>(Sensors::Type::DALLAS_TEMP):
#if USE_BLE
case static_cast<uint8_t>(Sensors::Type::BLUETOOTH):
#endif
case static_cast<uint8_t>(Sensors::Type::DHT11):
case static_cast<uint8_t>(Sensors::Type::DHT22):
case static_cast<uint8_t>(Sensors::Type::HEATING_SETPOINT_TEMP):
@@ -3428,6 +3498,7 @@ JsonVariant toJson(const Variables& src, JsonVariant dst) {
master[S_NETWORK][S_CONNECTED] = isNetworkConnected();
master[S_NETWORK][S_RSSI] = src.network.rssi;
master[S_NETWORK][S_CONNECTION_TYPE] = getNetworkConnectionType();
master[S_MQTT][S_CONNECTED] = isMqttConnected();
master[S_EMERGENCY][S_STATE] = src.emergency.state;
master[S_EXTERNAL_PUMP][S_STATE] = src.externalPump.state;
+8
View File
@@ -532,6 +532,8 @@ void publishHaEntity(HaEntity entityId, bool remove) {
auto gauge = std::make_unique<HA::Gauge>("rssi", "RSSI");
if (!remove) {
gauge->stateTopic = "~/state/master/network/rssi";
gauge->availabilityTopic = "~/state/master/network/connection_type";
gauge->availabilityTemplate = "{{ 'online' if value == 'wifi' else 'offline' }}";
gauge->category = HA::Category::DIAGNOSTIC;
gauge->deviceClass = "signal_strength";
gauge->icon = "mdi:signal";
@@ -906,6 +908,12 @@ static const char* getDynamicSensorIcon(Sensors::Purpose purpose) {
}
void publishDynamicSensor(const Sensors::Settings& sensor, Sensors::ValueType valueType, bool enabledByDefault) {
#if !USE_BLE
if (sensor.type == Sensors::Type::BLUETOOTH) {
return;
}
#endif
auto id = makeDynamicSensorId(sensor, valueType);
if (id.empty()) {
return;
+2 -2
View File
@@ -3,7 +3,6 @@
#include <app.h>
#include <MycilaMQTT.h>
#include <WiFi.h>
#include <algorithm>
#include <atomic>
#include <bitset>
@@ -287,6 +286,7 @@ static void publishMasterState() {
publishValue(mqttTopic("state/master/dhw/max_temp"), convertTemp(settings.dhw.maxTemp, UnitSystem::METRIC, settings.system.unitSystem), 2);
publishValue(mqttTopic("state/master/network/connected"), isNetworkConnected());
publishValue(mqttTopic("state/master/network/rssi"), std::to_string(vars.network.rssi));
publishValue(mqttTopic("state/master/network/connection_type"), getNetworkConnectionType());
publishValue(mqttTopic("state/master/emergency/state"), vars.emergency.state);
publishValue(mqttTopic("state/master/ext_pump/state"), vars.externalPump.state);
publishValue(mqttTopic("state/master/cascade_control/input"), vars.cascadeControl.input);
@@ -704,7 +704,7 @@ static void connect() {
.version = BUILD_VERSION,
.model = PROJECT_NAME,
.manufacturer = PROJECT_REPO,
.url = std::string("http://") + WiFi.localIP().toString().c_str() + "/",
.url = std::string("http://") + getNetworkIp().toString().c_str() + "/",
},
mqttPrefix,
[](const char* topic, const std::string& payload) {
+384 -38
View File
@@ -5,6 +5,9 @@
#include <DNSServer.h>
#include <ESPmDNS.h>
#include <ESPAsyncWebServer.h>
#if USE_ETHERNET
#include <ETH.h>
#endif
#include <Network.h>
#include <WiFi.h>
#include <esp_wifi.h>
@@ -19,6 +22,13 @@ static std::atomic<bool> staStarted{false};
static std::atomic<bool> apStarted{false};
static std::atomic<NetworkState> staState{NetworkState::NETWORK_DISABLED};
static std::atomic<NetworkState> apState{NetworkState::NETWORK_DISABLED};
#if USE_ETHERNET
static std::atomic<bool> ethStarted{false};
static std::atomic<NetworkState> ethState{NetworkState::NETWORK_DISABLED};
static bool ethernetRunning = false;
static bool ethernetInitFailed = false;
static unsigned long lastEthernetDriverAttempt = 0;
#endif
// Subscriptions are fixed before the worker starts.
static std::vector<NetworkEventCallback> networkCallbacks;
@@ -26,7 +36,7 @@ static std::vector<NetworkStateCallback> stateCallbacks;
// Framework callbacks only copy events. Driver and service operations stay in this worker.
struct PendingNetworkEvent {
uint32_t value; // IPv4 address for STA_GOT_IP and AP_STARTED.
uint32_t value; // IPv4 address for STA_GOT_IP, ETH_GOT_IP and AP_STARTED.
NetworkEvent event;
uint8_t reason; // STA disconnect reason.
};
@@ -66,6 +76,7 @@ static bool mdnsStarted = false;
static unsigned long lastDnsAttempt = 0;
static unsigned long lastMdnsAttempt = 0;
static char mdnsHostname[sizeof(networkSettings.hostname)] = {};
static void stopMdns();
// Event subscriptions
void onNetworkEvent(NetworkEventCallback callback) {
@@ -98,27 +109,110 @@ NetworkState getNetworkState(NetworkMode mode) {
return apState.load();
}
// Ethernet initialization and routing will be implemented separately.
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
return ethState.load();
}
#endif
return NetworkState::NETWORK_DISABLED;
}
bool isNetworkConnected() {
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED;
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED
|| getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED;
}
NetworkMode getNetworkMode() {
if (isNetworkConnected()) {
if (getNetworkState(networkSettings.type) == NetworkState::NETWORK_CONNECTED) {
return networkSettings.type;
}
if (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED) {
return NetworkMode::STA;
}
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED) {
return NetworkMode::ETH;
}
return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE;
}
const char* getNetworkConnectionType() {
switch (getNetworkMode()) {
case NetworkMode::ETH:
return S_ETHERNET;
case NetworkMode::STA:
return "wifi";
case NetworkMode::AP:
return "wifi-ap";
default:
return "none";
}
}
static NetworkInterface& getNetworkInterface() {
#if USE_ETHERNET
if (getNetworkMode() == NetworkMode::ETH) {
return ETH;
}
#endif
if (getNetworkMode() == NetworkMode::AP) {
return WiFi.AP;
}
return WiFi.STA;
}
IPAddress getNetworkIp() {
return getNetworkInterface().localIP();
}
IPAddress getNetworkSubnet() {
return getNetworkInterface().subnetMask();
}
IPAddress getNetworkGateway() {
return getNetworkInterface().gatewayIP();
}
IPAddress getNetworkDns() {
return getNetworkInterface().dnsIP();
}
String getNetworkMac() {
return getNetworkInterface().macAddress();
}
bool isEthernetConfigured(const NetworkSettings& config) {
#if USE_ETHERNET
const auto& gpios = config.ethernet.w5500;
return config.ethernet.type == EthernetType::W5500
&& GPIO_IS_VALID_OUTPUT(gpios.clk)
&& GPIO_IS_VALID_OUTPUT(gpios.mosi)
&& GPIO_IS_VALID_INPUT(gpios.miso)
&& GPIO_IS_VALID_OUTPUT(gpios.cs)
&& GPIO_IS_VALID_INPUT(gpios.irq)
&& GPIO_IS_VALID_OUTPUT(gpios.rst);
#else
(void)config;
return false;
#endif
}
bool isNetworkInterfaceStarted(NetworkMode mode) {
if (mode == NetworkMode::STA) {
return staStarted.load();
}
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
return ethStarted.load();
}
#endif
return mode == NetworkMode::AP && apStarted.load();
}
@@ -135,15 +229,24 @@ static void notifyNetworkEvent(NetworkEvent event) {
}
static void setNetworkState(NetworkMode mode, NetworkState next) {
auto& state = mode == NetworkMode::STA ? staState : apState;
const NetworkState previous = state.load();
auto* state = mode == NetworkMode::STA ? &staState : &apState;
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
state = &ethState;
}
#endif
const NetworkState previous = state->load();
if (previous == next) {
return;
}
if (mode == NetworkMode::STA) {
if (previous == NetworkState::NETWORK_CONNECTED) {
const bool uplink = mode == NetworkMode::STA || mode == NetworkMode::ETH;
const bool anotherConnected = getNetworkState(mode == NetworkMode::STA ? NetworkMode::ETH : NetworkMode::STA)
== NetworkState::NETWORK_CONNECTED;
if (uplink) {
// A late STOP from the previous interface must not erase the new connection.
if (previous == NetworkState::NETWORK_CONNECTED && !anotherConnected) {
disconnectedTime = millis();
connectedIp = 0;
vars.network.rssi = 0;
@@ -157,16 +260,18 @@ static void setNetworkState(NetworkMode mode, NetworkState next) {
}
// Publish before callbacks so getters and JSON already reflect the new state.
state.store(next);
state->store(next);
for (auto& callback : stateCallbacks) {
callback(mode, previous, next);
}
if (mode == NetworkMode::STA) {
if (uplink) {
if (next == NetworkState::NETWORK_CONNECTED) {
stopMdns();
notifyNetworkEvent(NetworkEvent::CONNECTED);
} else if (previous == NetworkState::NETWORK_CONNECTED) {
} else if (previous == NetworkState::NETWORK_CONNECTED && !anotherConnected) {
stopMdns();
notifyNetworkEvent(NetworkEvent::DISCONNECTED);
}
}
@@ -182,7 +287,7 @@ static void queueNetworkEvent(NetworkEvent event, uint32_t value = 0, uint8_t re
}
}
static void handleWifiEvent(arduino_event_id_t event, arduino_event_info_t info) {
static void handleNetworkEvent(arduino_event_id_t event, arduino_event_info_t info) {
// This callback runs in the Arduino event task; only copy the event data here.
switch (event) {
// Station
@@ -228,6 +333,30 @@ static void handleWifiEvent(arduino_event_id_t event, arduino_event_info_t info)
queueNetworkEvent(NetworkEvent::AP_GOT_IP6);
break;
#if USE_ETHERNET
case ARDUINO_EVENT_ETH_START:
queueNetworkEvent(NetworkEvent::ETH_STARTED);
break;
case ARDUINO_EVENT_ETH_STOP:
queueNetworkEvent(NetworkEvent::ETH_STOPPED);
break;
case ARDUINO_EVENT_ETH_CONNECTED:
queueNetworkEvent(NetworkEvent::ETH_CONNECTED);
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
queueNetworkEvent(NetworkEvent::ETH_DISCONNECTED);
break;
case ARDUINO_EVENT_ETH_GOT_IP:
queueNetworkEvent(NetworkEvent::ETH_GOT_IP, info.got_ip.ip_info.ip.addr);
break;
case ARDUINO_EVENT_ETH_LOST_IP:
queueNetworkEvent(NetworkEvent::ETH_LOST_IP);
break;
case ARDUINO_EVENT_ETH_GOT_IP6:
queueNetworkEvent(NetworkEvent::ETH_GOT_IP6);
break;
#endif
default:
break;
}
@@ -245,6 +374,10 @@ static void postInterfaceStopped(arduino_event_id_t type) {
}
// WiFi interfaces
static bool shouldEnableWifiRadio() {
return networkSettings.type == NetworkMode::STA;
}
static void configureWifiRadio() {
// Apply the existing channel policy after the WiFi driver has started.
const wifi_country_t country = {
@@ -271,6 +404,10 @@ static void stopAccessPoint() {
}
static void startAccessPoint() {
if (!shouldEnableWifiRadio()) {
return;
}
lastApAttempt = millis();
setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING);
@@ -287,9 +424,9 @@ static void startAccessPoint() {
configureWifiRadio();
WiFi.AP.setHostname(networkSettings.hostname);
if (!WiFi.AP.create(
networkSettings.ap.ssid,
networkSettings.ap.password[0] ? networkSettings.ap.password : nullptr,
networkSettings.ap.channel
networkSettings.wifi.ap.ssid,
networkSettings.wifi.ap.password[0] ? networkSettings.wifi.ap.password : nullptr,
networkSettings.wifi.ap.channel
)) {
stopAccessPoint();
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
@@ -314,7 +451,7 @@ static bool resetWifi() {
}
lastConnectionAttempt = 0;
if (restoreAp) {
if (restoreAp && shouldEnableWifiRadio()) {
startAccessPoint();
}
@@ -322,6 +459,10 @@ static bool resetWifi() {
}
static bool startNetworkConnection() {
if (!shouldEnableWifiRadio()) {
return false;
}
// Ordinary retries preserve AP. Escalate only if STA cannot be stopped.
const bool wasStarted = WiFi.STA.started();
@@ -371,15 +512,100 @@ static bool startNetworkConnection() {
);
return WiFi.STA.connect(
networkSettings.sta.ssid,
networkSettings.sta.password[0] ? networkSettings.sta.password : nullptr,
networkSettings.sta.channel
networkSettings.wifi.sta.ssid,
networkSettings.wifi.sta.password[0] ? networkSettings.wifi.sta.password : nullptr,
networkSettings.wifi.sta.channel
);
}
// The SPI driver stays installed across enable/disable; rewiring needs a restart.
#if USE_ETHERNET
static bool configureEthernet() {
ETH.setHostname(networkSettings.hostname);
// Prefer Ethernet while the previous interface finishes shutting down.
ETH.setRoutePrio(200);
if (networkSettings.useDhcp) {
return ETH.config();
}
IPAddress ip, gateway, subnet, dns;
ip.fromString(networkSettings.staticConfig.ip);
gateway.fromString(networkSettings.staticConfig.gateway);
subnet.fromString(networkSettings.staticConfig.subnet);
dns.fromString(networkSettings.staticConfig.dns);
return ETH.config(ip, gateway, subnet, dns);
}
static void updateEthernet() {
const bool enabled = networkSettings.type == NetworkMode::ETH && isEthernetConfigured();
if (!enabled) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
if (!ethernetRunning) {
return;
}
if (lastEthernetDriverAttempt && millis() - lastEthernetDriverAttempt < 15000) {
return;
}
lastEthernetDriverAttempt = millis();
const esp_err_t result = esp_eth_stop(ETH.handle());
if (result != ESP_OK) {
ESP_LOGE(L_NETWORK, "Failed stop Ethernet: %s", esp_err_to_name(result));
return;
}
ethernetRunning = false;
ethStarted.store(false);
lastEthernetDriverAttempt = 0;
return;
}
if (ethernetRunning || ethernetInitFailed) {
return;
}
if (lastEthernetDriverAttempt && millis() - lastEthernetDriverAttempt < 15000) {
return;
}
lastEthernetDriverAttempt = millis();
if (ETH.handle() == nullptr) {
const auto& gpios = networkSettings.ethernet.w5500;
ESP_LOGI(L_NETWORK, "Initialize W5500 Ethernet");
if (!ETH.begin(
ETH_PHY_W5500, 1, gpios.cs, gpios.irq, gpios.rst,
SPI2_HOST, gpios.clk, gpios.miso, gpios.mosi, 12
)) {
// begin() can leave the SPI bus allocated. Retrying would reuse partial initialization.
ethernetInitFailed = true;
ESP_LOGE(L_NETWORK, "W5500 initialization failed, check wiring and restart");
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_TIMEOUT);
return;
}
} else {
const esp_err_t result = esp_eth_start(ETH.handle());
if (result != ESP_OK) {
ESP_LOGE(L_NETWORK, "Failed start Ethernet: %s", esp_err_to_name(result));
return;
}
}
ethernetRunning = true;
lastEthernetDriverAttempt = 0;
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING);
}
#endif
// Station connection and recovery timeouts
static void updateConnection() {
if (!networkSettings.sta.ssid[0]) {
if (!networkSettings.wifi.sta.ssid[0]) {
return;
}
@@ -433,7 +659,7 @@ static void updateAccessPoint() {
return;
}
if (!apStarted.load() && (!networkSettings.sta.ssid[0] || millis() - disconnectedTime > 185000)) {
if (!apStarted.load() && (!networkSettings.wifi.sta.ssid[0] || millis() - disconnectedTime > 185000)) {
if (!lastApAttempt || millis() - lastApAttempt > 15000) {
ESP_LOGI(L_NETWORK, "Start fallback AP");
startAccessPoint();
@@ -543,6 +769,10 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
switch (pending.event) {
// Station
case NetworkEvent::STA_STARTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Repeated START must not invalidate an active connection.
if (staStarted.exchange(true)) {
break;
@@ -570,24 +800,28 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
}
case NetworkEvent::STA_CONNECTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Association alone does not confirm a usable IP address.
staAssociated = true;
break;
case NetworkEvent::STA_GOT_IP:
if (!pending.value) {
if (!shouldEnableWifiRadio() || !pending.value) {
return;
}
// GOT_IP confirms both DHCP and configured static IPv4 after association.
// IP changes invalidate the previous client session, including A -> B -> A.
if (isNetworkConnected() && connectedIp != pending.value) {
if (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED && connectedIp != pending.value) {
disconnectReason = 0;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
}
staAssociated = true;
connectedIp = pending.value;
if (!isNetworkConnected()) {
if (getNetworkState(NetworkMode::STA) != NetworkState::NETWORK_CONNECTED) {
vars.network.rssi = WiFi.STA.RSSI();
lastRssiUpdate = millis();
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_CONNECTED);
@@ -604,8 +838,72 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
break;
#if USE_ETHERNET
case NetworkEvent::ETH_STARTED:
if (!ethernetRunning || networkSettings.type != NetworkMode::ETH || !isEthernetConfigured()) {
return;
}
if (ethStarted.exchange(true)) {
break;
}
// Apply after native START so a preceding STOP cannot clear the static-IP state.
if (!configureEthernet()) {
ESP_LOGE(L_NETWORK, "Failed configure Ethernet IPv4");
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_TIMEOUT);
break;
}
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_DISABLED) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_ENABLED);
}
break;
case NetworkEvent::ETH_STOPPED:
ethStarted.store(false);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
break;
case NetworkEvent::ETH_CONNECTED:
if (!ethernetRunning || networkSettings.type != NetworkMode::ETH || !isEthernetConfigured()) {
return;
}
if (getNetworkState(NetworkMode::ETH) != NetworkState::NETWORK_CONNECTED) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING);
}
break;
case NetworkEvent::ETH_GOT_IP:
if (!ethernetRunning || networkSettings.type != NetworkMode::ETH || !isEthernetConfigured()
|| !pending.value || !ETH.connected() || !ETH.hasIP()
) {
return;
}
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED && connectedIp != pending.value) {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISCONNECTED);
}
connectedIp = pending.value;
if (getNetworkState(NetworkMode::ETH) != NetworkState::NETWORK_CONNECTED) {
vars.network.rssi = 0;
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTED);
}
break;
case NetworkEvent::ETH_DISCONNECTED:
case NetworkEvent::ETH_LOST_IP:
setNetworkState(
NetworkMode::ETH,
ethernetRunning ? NetworkState::NETWORK_DISCONNECTED : NetworkState::NETWORK_DISABLED
);
break;
#endif
// Access point
case NetworkEvent::AP_STARTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Preserve clients and captive portal state on a repeated START.
if (apStarted.exchange(true)) {
break;
@@ -662,6 +960,10 @@ static void processNetworkEvents() {
staAssociated = false;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED);
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
#if USE_ETHERNET
ethStarted.store(false);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
#endif
if (overflowed) {
ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi requested");
@@ -684,6 +986,21 @@ static void processNetworkEvents() {
return;
}
#if USE_ETHERNET
// Re-read native Ethernet state after the queue was reset; the driver remains installed.
if (ethernetRunning && networkSettings.type == NetworkMode::ETH && isEthernetConfigured()) {
ethStarted.store(ETH.started());
if (ETH.hasIP() && ETH.connected() && static_cast<uint32_t>(ETH.localIP())) {
connectedIp = static_cast<uint32_t>(ETH.localIP());
vars.network.rssi = 0;
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTED);
} else {
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_CONNECTING);
}
}
#endif
recoveryPending = false;
}
@@ -700,7 +1017,7 @@ static void processNetworkEvents() {
// Connection services
static void updateRssi() {
if (isNetworkConnected() && millis() - lastRssiUpdate >= 1000) {
if (getNetworkMode() == NetworkMode::STA && millis() - lastRssiUpdate >= 1000) {
vars.network.rssi = WiFi.STA.RSSI();
lastRssiUpdate = millis();
}
@@ -716,7 +1033,7 @@ static void updateNtp() {
}
static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) {
if (mode != NetworkMode::STA) {
if (mode != networkSettings.type) {
return;
}
@@ -748,25 +1065,31 @@ static Task networkStartTask("Start network services", Task::Type::ONCE, [](void
webServer->begin();
webServerReady = true;
configureLoggingTask.resume();
ESP_LOGD(L_PORTAL_WEBSERVER, "Started: AP up or STA connected");
ESP_LOGD(L_PORTAL_WEBSERVER, "Started: AP up or uplink connected");
});
static Task reconnectTask("Reconnect network", Task::Type::ONCE, [](void*) {
ESP_LOGI(L_NETWORK, "Reconnecting...");
const bool wasStarted = WiFi.STA.started();
if (!WiFi.STA.end()) {
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi...");
resetWifi();
return;
}
#if USE_ETHERNET
if (ethernetRunning) {
// Keep the installed SPI device, but cycle the link to reapply hostname and IPv4.
const esp_err_t result = esp_eth_stop(ETH.handle());
if (result != ESP_OK) {
ESP_LOGE(L_NETWORK, "Failed restart Ethernet: %s", esp_err_to_name(result));
return;
if (wasStarted) {
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP);
} else {
ethernetRunning = false;
ethStarted.store(false);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
}
}
#endif
lastConnectionAttempt = 0;
connectionPending = false;
if (!resetWifi()) {
networkRecoveryRequested.store(true);
}
});
static Task networkTask("Network", [](void*) {
@@ -796,6 +1119,29 @@ static Task networkTask("Network", [](void*) {
return;
}
if (!shouldEnableWifiRadio()) {
if (WiFi.getMode() != WIFI_OFF && !resetWifi()) {
networkRecoveryRequested.store(true);
return;
}
#if USE_ETHERNET
updateEthernet();
#endif
if (isNetworkConnected()) {
updateNtp();
}
return;
}
#if USE_ETHERNET
updateEthernet();
if (ethernetRunning) {
return;
}
#endif
if (isNetworkConnected()) {
if (connectionPending) {
connectionPending = false;
@@ -836,7 +1182,7 @@ void initNetwork() {
});
Network.begin();
Network.onEvent(handleWifiEvent);
Network.onEvent(handleNetworkEvent);
onNetworkStateChange(logNetworkState);
WiFi.persistent(false);
WiFi.STA.setAutoReconnect(false);
+45 -12
View File
@@ -13,6 +13,9 @@
#include <Update.h>
#include <UpgradeHandler.h>
#include <WiFi.h>
#if USE_ETHERNET
#include <ETH.h>
#endif
#include <MycilaWebSerial.h>
#include <esp_core_dump.h>
@@ -47,8 +50,16 @@ static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
const IPAddress apIP = WiFi.AP.localIP();
const IPAddress staIP = WiFi.STA.localIP();
if (localIP == apIP && localIP == staIP) {
// Matching AP/STA addresses cannot identify the interface.
const bool matchesAp = localIP == apIP;
const bool matchesSta = localIP == staIP;
#if USE_ETHERNET
const bool matchesEth = localIP == ETH.localIP();
#else
const bool matchesEth = false;
#endif
if (matchesAp + matchesSta + matchesEth > 1) {
// Matching interface addresses cannot identify the connection.
return RequestInterface::UNKNOWN;
}
@@ -60,6 +71,10 @@ static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
return RequestInterface::STA;
}
if (matchesEth) {
return RequestInterface::ETH;
}
return RequestInterface::UNKNOWN;
}
@@ -373,6 +388,9 @@ static void restApi() {
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
toJson(networkSettings, doc);
#if USE_ETHERNET
doc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
#endif
// send response
response->setLength();
@@ -403,6 +421,9 @@ static void restApi() {
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(networkSettings, responseDoc);
#if USE_ETHERNET
responseDoc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
#endif
// send response
response->setLength();
@@ -415,10 +436,16 @@ static void restApi() {
reconnectNetwork();
}
});
nsHandler.setMaxContentLength(512);
nsHandler.setMaxContentLength(1024);
nsHandler.addMiddleware(&authMiddleware);
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) {
// Ethernet mode must not start the Wi-Fi radio for a scan.
if (networkSettings.type != NetworkMode::STA) {
request->send(409);
return;
}
auto apCount = WiFi.scanComplete();
switch (apCount) {
@@ -879,22 +906,28 @@ static void restApi() {
auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot();
#if USE_ETHERNET
doc[S_FEATURES][S_ETHERNET] = true;
#endif
auto docSystem = doc[S_SYSTEM].to<JsonObject>();
docSystem[S_RESET_REASON] = getResetReason();
docSystem[S_UPTIME] = millis() / 1000;
bool isConnected = isNetworkConnected();
const bool isConnected = isNetworkConnected();
const bool wifiUplink = getNetworkMode() == NetworkMode::STA;
auto docNetwork = doc[S_NETWORK].to<JsonObject>();
docNetwork[S_HOSTNAME] = networkSettings.hostname;
docNetwork[S_MAC] = WiFi.STA.macAddress();
docNetwork[S_MAC] = getNetworkMac();
docNetwork[S_CONNECTED] = isConnected;
docNetwork[S_SSID] = strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr;
docNetwork[S_SIGNAL_QUALITY] = isConnected ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0;
docNetwork[S_CHANNEL] = isConnected ? networkSettings.sta.channel : 0;
docNetwork[S_IP] = isConnected ? WiFi.STA.localIP().toString() : "";
docNetwork[S_SUBNET] = isConnected ? WiFi.STA.subnetMask().toString() : "";
docNetwork[S_GATEWAY] = isConnected ? WiFi.STA.gatewayIP().toString() : "";
docNetwork[S_DNS] = isConnected ? WiFi.STA.dnsIP().toString() : "";
docNetwork[S_CONNECTION_TYPE] = getNetworkConnectionType();
docNetwork[S_SSID] = wifiUplink ? WiFi.STA.SSID() : "";
docNetwork[S_SIGNAL_QUALITY] = wifiUplink ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0;
docNetwork[S_CHANNEL] = wifiUplink ? WiFi.channel() : 0;
docNetwork[S_IP] = isConnected ? getNetworkIp().toString() : "";
docNetwork[S_SUBNET] = isConnected ? getNetworkSubnet().toString() : "";
docNetwork[S_GATEWAY] = isConnected ? getNetworkGateway().toString() : "";
docNetwork[S_DNS] = isConnected ? getNetworkDns().toString() : "";
auto docBuild = doc[S_BUILD].to<JsonObject>();
docBuild[S_VERSION] = BUILD_VERSION;