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

+26 -8
View File
@@ -7,6 +7,7 @@
#include "types.h" #include "types.h"
#include "Sensors.h" #include "Sensors.h"
// Keep the existing WiFi settings at the start of the persisted structure.
struct NetworkSettings { struct NetworkSettings {
char hostname[25] = DEFAULT_HOSTNAME; char hostname[25] = DEFAULT_HOSTNAME;
bool useDhcp = true; bool useDhcp = true;
@@ -19,16 +20,33 @@ struct NetworkSettings {
} staticConfig; } staticConfig;
struct { struct {
char ssid[33] = DEFAULT_AP_SSID; struct {
char password[65] = DEFAULT_AP_PASSWORD; char ssid[33] = DEFAULT_AP_SSID;
uint8_t channel = 6; char password[65] = DEFAULT_AP_PASSWORD;
} ap; uint8_t channel = 6;
} ap;
struct {
char ssid[33] = DEFAULT_STA_SSID;
char password[65] = DEFAULT_STA_PASSWORD;
uint8_t channel = 0;
} sta;
} wifi;
struct { struct {
char ssid[33] = DEFAULT_STA_SSID; EthernetType type = EthernetType::W5500;
char password[65] = DEFAULT_STA_PASSWORD;
uint8_t channel = 0; struct {
} sta; uint8_t clk = DEFAULT_ETH_CLK_GPIO;
uint8_t mosi = DEFAULT_ETH_MOSI_GPIO;
uint8_t miso = DEFAULT_ETH_MISO_GPIO;
uint8_t cs = DEFAULT_ETH_CS_GPIO;
uint8_t irq = DEFAULT_ETH_IRQ_GPIO;
uint8_t rst = DEFAULT_ETH_RST_GPIO;
} w5500;
} ethernet;
NetworkMode type = NetworkMode::STA;
}; };
struct SystemSettings { struct SystemSettings {
+7
View File
@@ -144,6 +144,13 @@ void onNetworkEvent(NetworkEventCallback callback);
void onNetworkStateChange(NetworkStateCallback callback); void onNetworkStateChange(NetworkStateCallback callback);
NetworkState getNetworkState(NetworkMode mode = NetworkMode::STA); NetworkState getNetworkState(NetworkMode mode = NetworkMode::STA);
NetworkMode getNetworkMode(); NetworkMode getNetworkMode();
const char* getNetworkConnectionType();
IPAddress getNetworkIp();
IPAddress getNetworkSubnet();
IPAddress getNetworkGateway();
IPAddress getNetworkDns();
String getNetworkMac();
bool isEthernetConfigured(const NetworkSettings& config = networkSettings);
bool isNetworkInterfaceStarted(NetworkMode mode); bool isNetworkInterfaceStarted(NetworkMode mode);
// Last state published by the system worker, including during event callbacks. // Last state published by the system worker, including during event callbacks.
bool isNetworkConnected(); bool isNetworkConnected();
+29
View File
@@ -63,6 +63,11 @@
#define USE_BLE false #define USE_BLE false
#endif #endif
// W5500 support is enabled by the dedicated C6 Ethernet build.
#ifndef USE_ETHERNET
#define USE_ETHERNET false
#endif
#ifndef DEFAULT_HOSTNAME #ifndef DEFAULT_HOSTNAME
#define DEFAULT_HOSTNAME "" #define DEFAULT_HOSTNAME ""
#endif #endif
@@ -91,6 +96,30 @@
#define DEFAULT_STATUS_LED_GPIO GPIO_IS_NOT_CONFIGURED #define DEFAULT_STATUS_LED_GPIO GPIO_IS_NOT_CONFIGURED
#endif #endif
#ifndef DEFAULT_ETH_CLK_GPIO
#define DEFAULT_ETH_CLK_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_MOSI_GPIO
#define DEFAULT_ETH_MOSI_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_MISO_GPIO
#define DEFAULT_ETH_MISO_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_CS_GPIO
#define DEFAULT_ETH_CS_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_IRQ_GPIO
#define DEFAULT_ETH_IRQ_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_ETH_RST_GPIO
#define DEFAULT_ETH_RST_GPIO GPIO_IS_NOT_CONFIGURED
#endif
#ifndef DEFAULT_PORTAL_LOGIN #ifndef DEFAULT_PORTAL_LOGIN
#define DEFAULT_PORTAL_LOGIN "" #define DEFAULT_PORTAL_LOGIN ""
#endif #endif
+11
View File
@@ -51,13 +51,17 @@ inline const char S_CHANNEL[] = "channel";
inline const char S_CH2_ALWAYS_ENABLED[] = "ch2_always_enabled"; inline const char S_CH2_ALWAYS_ENABLED[] = "ch2_always_enabled";
inline const char S_CH2_DISABLING_ACTION[] = "ch2_disabling_action"; inline const char S_CH2_DISABLING_ACTION[] = "ch2_disabling_action";
inline const char S_CHIP[] = "chip"; inline const char S_CHIP[] = "chip";
inline const char S_CLK[] = "clk";
inline const char S_CODE[] = "code"; inline const char S_CODE[] = "code";
inline const char S_COMMIT[] = "commit"; inline const char S_COMMIT[] = "commit";
inline const char S_CONFIGURED[] = "configured";
inline const char S_CONNECTED[] = "connected"; inline const char S_CONNECTED[] = "connected";
inline const char S_CONNECTION_TYPE[] = "connection_type";
inline const char S_COOLING[] = "cooling"; inline const char S_COOLING[] = "cooling";
inline const char S_COOLING_SUPPORT[] = "cooling_support"; inline const char S_COOLING_SUPPORT[] = "cooling_support";
inline const char S_CORE[] = "core"; inline const char S_CORE[] = "core";
inline const char S_CORES[] = "cores"; inline const char S_CORES[] = "cores";
inline const char S_CS[] = "cs";
inline const char S_CURRENT_TEMP[] = "current_temp"; inline const char S_CURRENT_TEMP[] = "current_temp";
inline const char S_DATE[] = "date"; inline const char S_DATE[] = "date";
inline const char S_DEADBAND[] = "deadband"; inline const char S_DEADBAND[] = "deadband";
@@ -76,11 +80,13 @@ inline const char S_EMERGENCY[] = "emergency";
inline const char S_ENABLED[] = "enabled"; inline const char S_ENABLED[] = "enabled";
inline const char S_ENV[] = "env"; inline const char S_ENV[] = "env";
inline const char S_EQUITHERM[] = "equitherm"; inline const char S_EQUITHERM[] = "equitherm";
inline const char S_ETHERNET[] = "ethernet";
inline const char S_EXPONENT[] = "exponent"; inline const char S_EXPONENT[] = "exponent";
inline const char S_EXTERNAL_PUMP[] = "ext_pump"; inline const char S_EXTERNAL_PUMP[] = "ext_pump";
inline const char S_FACTOR[] = "factor"; inline const char S_FACTOR[] = "factor";
inline const char S_FALSE[] = "false"; inline const char S_FALSE[] = "false";
inline const char S_FAULT[] = "fault"; inline const char S_FAULT[] = "fault";
inline const char S_FEATURES[] = "features";
inline const char S_FREEZE_PROTECTION[] = "freeze_protection"; inline const char S_FREEZE_PROTECTION[] = "freeze_protection";
inline const char S_FREEZING[] = "freezing"; inline const char S_FREEZING[] = "freezing";
inline const char S_FILTERING[] = "filtering"; inline const char S_FILTERING[] = "filtering";
@@ -115,6 +121,7 @@ inline const char S_INPUT[] = "input";
inline const char S_INTERVAL[] = "interval"; inline const char S_INTERVAL[] = "interval";
inline const char S_INVERT_STATE[] = "invert_state"; inline const char S_INVERT_STATE[] = "invert_state";
inline const char S_IP[] = "ip"; inline const char S_IP[] = "ip";
inline const char S_IRQ[] = "irq";
inline const char S_I_FACTOR[] = "i_factor"; inline const char S_I_FACTOR[] = "i_factor";
inline const char S_I_MULTIPLIER[] = "i_multiplier"; inline const char S_I_MULTIPLIER[] = "i_multiplier";
inline const char S_LOGIN[] = "login"; inline const char S_LOGIN[] = "login";
@@ -135,8 +142,10 @@ inline const char S_MIN_FREE[] = "min_free";
inline const char S_MIN_MAX_FREE_BLOCK[] = "min_max_free_block"; inline const char S_MIN_MAX_FREE_BLOCK[] = "min_max_free_block";
inline const char S_MIN_POWER[] = "min_power"; inline const char S_MIN_POWER[] = "min_power";
inline const char S_MIN_TEMP[] = "min_temp"; inline const char S_MIN_TEMP[] = "min_temp";
inline const char S_MISO[] = "miso";
inline const char S_MODEL[] = "model"; inline const char S_MODEL[] = "model";
inline const char S_MODULATION[] = "modulation"; inline const char S_MODULATION[] = "modulation";
inline const char S_MOSI[] = "mosi";
inline const char S_MQTT[] = "mqtt"; inline const char S_MQTT[] = "mqtt";
inline const char S_NAME[] = "name"; inline const char S_NAME[] = "name";
inline const char S_SLUG[] = "slug"; inline const char S_SLUG[] = "slug";
@@ -174,6 +183,7 @@ inline const char S_RESTART[] = "restart";
inline const char S_RETURN_TEMP[] = "return_temp"; inline const char S_RETURN_TEMP[] = "return_temp";
inline const char S_REV[] = "rev"; inline const char S_REV[] = "rev";
inline const char S_RSSI[] = "rssi"; inline const char S_RSSI[] = "rssi";
inline const char S_RST[] = "rst";
inline const char S_RX_LED_GPIO[] = "rx_led_gpio"; inline const char S_RX_LED_GPIO[] = "rx_led_gpio";
inline const char S_SDK[] = "sdk"; inline const char S_SDK[] = "sdk";
inline const char S_SENSORS[] = "sensors"; inline const char S_SENSORS[] = "sensors";
@@ -218,3 +228,4 @@ inline const char S_USER[] = "user";
inline const char S_VALUE[] = "value"; inline const char S_VALUE[] = "value";
inline const char S_VERSION[] = "version"; inline const char S_VERSION[] = "version";
inline const char S_WEBSERIAL[] = "web_serial"; inline const char S_WEBSERIAL[] = "web_serial";
inline const char S_WIFI[] = "wifi";
+12
View File
@@ -14,6 +14,11 @@ enum class ChannelDisablingAction : uint8_t {
OFF_AND_ZERO_SETPOINT = 2 OFF_AND_ZERO_SETPOINT = 2
}; };
enum class EthernetType : uint8_t {
NONE = 0,
W5500 = 1
};
struct SettingResult { struct SettingResult {
bool changed = false; bool changed = false;
bool accepted = false; bool accepted = false;
@@ -77,6 +82,13 @@ enum class NetworkEvent : uint8_t {
STA_GOT_IP, STA_GOT_IP,
STA_LOST_IP, STA_LOST_IP,
STA_GOT_IP6, STA_GOT_IP6,
ETH_STARTED,
ETH_STOPPED,
ETH_CONNECTED,
ETH_DISCONNECTED,
ETH_GOT_IP,
ETH_LOST_IP,
ETH_GOT_IP6,
AP_STARTED, AP_STARTED,
AP_STOPPED, AP_STOPPED,
AP_CLIENT_CONNECTED, AP_CLIENT_CONNECTED,
+1 -1
View File
@@ -5,7 +5,7 @@
}, },
"devDependencies": { "devDependencies": {
"cssnano": "^9.3.2", "cssnano": "^9.3.2",
"cssnano-preset-advanced": "^9.2.2", "cssnano-preset-advanced": "^10.0.0",
"gulp": "^5.0.0", "gulp": "^5.0.0",
"gulp-concat": "^2.6.1", "gulp-concat": "^2.6.1",
"gulp-gzip": "^1.4.2", "gulp-gzip": "^1.4.2",
+13
View File
@@ -290,6 +290,19 @@ custom_sdkconfig = ${esp32_defaults.custom_sdkconfig}
'# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set' '# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set'
CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y
; W5500 support uses a separate build to fit the existing OTA slot.
[env:esp32_c6_ethernet]
extends = env:esp32_c6
lib_deps = ${esp32_defaults.lib_deps}
build_unflags = ${env:esp32_c6.build_unflags}
-DUSE_BLE
build_flags = ${env:esp32_c6.build_flags}
-D USE_ETHERNET=1
custom_sdkconfig = ${env:esp32_c6.custom_sdkconfig}
'# CONFIG_BT_ENABLED is not set'
CONFIG_ETH_USE_SPI_ETHERNET=y
CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF=y
[env:otthing] [env:otthing]
extends = esp32_defaults extends = esp32_defaults
board = lolin_c3_mini board = lolin_c3_mini
+105 -34
View File
@@ -164,6 +164,7 @@ void saveSettingsNow() {
// Initialization // Initialization
static bool loadNetworkSettings() { static bool loadNetworkSettings() {
bool loaded = false; bool loaded = false;
fsNetworkSettings.addWithoutWipe(true);
switch (fsNetworkSettings.read()) { switch (fsNetworkSettings.read()) {
case FD_FS_ERR: 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_SUBNET] = src.staticConfig.subnet;
dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns; dst[S_STATIC_CONFIG][S_DNS] = src.staticConfig.dns;
dst[S_AP][S_SSID] = src.ap.ssid; auto wifi = dst[S_WIFI].to<JsonObject>();
dst[S_AP][S_PASSWORD] = src.ap.password; wifi[S_AP][S_SSID] = src.wifi.ap.ssid;
dst[S_AP][S_CHANNEL] = src.ap.channel; 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; wifi[S_STA][S_SSID] = src.wifi.sta.ssid;
dst[S_STA][S_PASSWORD] = src.sta.password; wifi[S_STA][S_PASSWORD] = src.wifi.sta.password;
dst[S_STA][S_CHANNEL] = src.sta.channel; 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; 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 // ap
if (src[S_AP][S_SSID].is<JsonString>()) { if (ap[S_SSID].is<JsonString>()) {
const JsonString value = src[S_AP][S_SSID].as<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; result.accepted = true;
if (strcmp(value.c_str(), dst.ap.ssid) != 0) { if (strcmp(value.c_str(), dst.wifi.ap.ssid) != 0) {
strcpy(dst.ap.ssid, value.c_str()); strcpy(dst.wifi.ap.ssid, value.c_str());
result.changed = true; result.changed = true;
} }
} }
} }
if (src[S_AP][S_PASSWORD].is<JsonString>()) { if (ap[S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_AP][S_PASSWORD].as<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; result.accepted = true;
if (strcmp(value.c_str(), dst.ap.password) != 0) { if (strcmp(value.c_str(), dst.wifi.ap.password) != 0) {
strcpy(dst.ap.password, value.c_str()); strcpy(dst.wifi.ap.password, value.c_str());
result.changed = true; result.changed = true;
} }
} }
} }
if (src[S_AP][S_CHANNEL].is<uint8_t>()) { if (ap[S_CHANNEL].is<uint8_t>()) {
const auto value = src[S_AP][S_CHANNEL].as<uint8_t>(); const auto value = ap[S_CHANNEL].as<uint8_t>();
if (value < 12) { if (value < 12) {
result.accepted = true; result.accepted = true;
if (value != dst.ap.channel) { if (value != dst.wifi.ap.channel) {
dst.ap.channel = value; dst.wifi.ap.channel = value;
result.changed = true; result.changed = true;
} }
} }
@@ -470,38 +488,88 @@ SettingResult fromJson(JsonVariantConst src, NetworkSettings& dst) {
// sta // sta
if (src[S_STA][S_SSID].is<JsonString>()) { if (sta[S_SSID].is<JsonString>()) {
const JsonString value = src[S_STA][S_SSID].as<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; result.accepted = true;
if (strcmp(value.c_str(), dst.sta.ssid) != 0) { if (strcmp(value.c_str(), dst.wifi.sta.ssid) != 0) {
strcpy(dst.sta.ssid, value.c_str()); strcpy(dst.wifi.sta.ssid, value.c_str());
result.changed = true; result.changed = true;
} }
} }
} }
if (src[S_STA][S_PASSWORD].is<JsonString>()) { if (sta[S_PASSWORD].is<JsonString>()) {
const JsonString value = src[S_STA][S_PASSWORD].as<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; result.accepted = true;
if (strcmp(value.c_str(), dst.sta.password) != 0) { if (strcmp(value.c_str(), dst.wifi.sta.password) != 0) {
strcpy(dst.sta.password, value.c_str()); strcpy(dst.wifi.sta.password, value.c_str());
result.changed = true; result.changed = true;
} }
} }
} }
if (src[S_STA][S_CHANNEL].is<uint8_t>()) { if (sta[S_CHANNEL].is<uint8_t>()) {
const auto value = src[S_STA][S_CHANNEL].as<uint8_t>(); const auto value = sta[S_CHANNEL].as<uint8_t>();
if (value < 12) { if (value < 12) {
result.accepted = true; result.accepted = true;
if (value != dst.sta.channel) { if (value != dst.wifi.sta.channel) {
dst.sta.channel = value; 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; 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::NTC_10K_TEMP):
case static_cast<uint8_t>(Sensors::Type::DALLAS_TEMP): case static_cast<uint8_t>(Sensors::Type::DALLAS_TEMP):
#if USE_BLE
case static_cast<uint8_t>(Sensors::Type::BLUETOOTH): case static_cast<uint8_t>(Sensors::Type::BLUETOOTH):
#endif
case static_cast<uint8_t>(Sensors::Type::DHT11): case static_cast<uint8_t>(Sensors::Type::DHT11):
case static_cast<uint8_t>(Sensors::Type::DHT22): case static_cast<uint8_t>(Sensors::Type::DHT22):
case static_cast<uint8_t>(Sensors::Type::HEATING_SETPOINT_TEMP): 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_CONNECTED] = isNetworkConnected();
master[S_NETWORK][S_RSSI] = src.network.rssi; master[S_NETWORK][S_RSSI] = src.network.rssi;
master[S_NETWORK][S_CONNECTION_TYPE] = getNetworkConnectionType();
master[S_MQTT][S_CONNECTED] = isMqttConnected(); master[S_MQTT][S_CONNECTED] = isMqttConnected();
master[S_EMERGENCY][S_STATE] = src.emergency.state; master[S_EMERGENCY][S_STATE] = src.emergency.state;
master[S_EXTERNAL_PUMP][S_STATE] = src.externalPump.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"); auto gauge = std::make_unique<HA::Gauge>("rssi", "RSSI");
if (!remove) { if (!remove) {
gauge->stateTopic = "~/state/master/network/rssi"; 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->category = HA::Category::DIAGNOSTIC;
gauge->deviceClass = "signal_strength"; gauge->deviceClass = "signal_strength";
gauge->icon = "mdi:signal"; 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) { 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); auto id = makeDynamicSensorId(sensor, valueType);
if (id.empty()) { if (id.empty()) {
return; return;
+2 -2
View File
@@ -3,7 +3,6 @@
#include <app.h> #include <app.h>
#include <MycilaMQTT.h> #include <MycilaMQTT.h>
#include <WiFi.h>
#include <algorithm> #include <algorithm>
#include <atomic> #include <atomic>
#include <bitset> #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/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/connected"), isNetworkConnected());
publishValue(mqttTopic("state/master/network/rssi"), std::to_string(vars.network.rssi)); 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/emergency/state"), vars.emergency.state);
publishValue(mqttTopic("state/master/ext_pump/state"), vars.externalPump.state); publishValue(mqttTopic("state/master/ext_pump/state"), vars.externalPump.state);
publishValue(mqttTopic("state/master/cascade_control/input"), vars.cascadeControl.input); publishValue(mqttTopic("state/master/cascade_control/input"), vars.cascadeControl.input);
@@ -704,7 +704,7 @@ static void connect() {
.version = BUILD_VERSION, .version = BUILD_VERSION,
.model = PROJECT_NAME, .model = PROJECT_NAME,
.manufacturer = PROJECT_REPO, .manufacturer = PROJECT_REPO,
.url = std::string("http://") + WiFi.localIP().toString().c_str() + "/", .url = std::string("http://") + getNetworkIp().toString().c_str() + "/",
}, },
mqttPrefix, mqttPrefix,
[](const char* topic, const std::string& payload) { [](const char* topic, const std::string& payload) {
+384 -38
View File
@@ -5,6 +5,9 @@
#include <DNSServer.h> #include <DNSServer.h>
#include <ESPmDNS.h> #include <ESPmDNS.h>
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
#if USE_ETHERNET
#include <ETH.h>
#endif
#include <Network.h> #include <Network.h>
#include <WiFi.h> #include <WiFi.h>
#include <esp_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<bool> apStarted{false};
static std::atomic<NetworkState> staState{NetworkState::NETWORK_DISABLED}; static std::atomic<NetworkState> staState{NetworkState::NETWORK_DISABLED};
static std::atomic<NetworkState> apState{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. // Subscriptions are fixed before the worker starts.
static std::vector<NetworkEventCallback> networkCallbacks; 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. // Framework callbacks only copy events. Driver and service operations stay in this worker.
struct PendingNetworkEvent { 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; NetworkEvent event;
uint8_t reason; // STA disconnect reason. uint8_t reason; // STA disconnect reason.
}; };
@@ -66,6 +76,7 @@ static bool mdnsStarted = false;
static unsigned long lastDnsAttempt = 0; static unsigned long lastDnsAttempt = 0;
static unsigned long lastMdnsAttempt = 0; static unsigned long lastMdnsAttempt = 0;
static char mdnsHostname[sizeof(networkSettings.hostname)] = {}; static char mdnsHostname[sizeof(networkSettings.hostname)] = {};
static void stopMdns();
// Event subscriptions // Event subscriptions
void onNetworkEvent(NetworkEventCallback callback) { void onNetworkEvent(NetworkEventCallback callback) {
@@ -98,27 +109,110 @@ NetworkState getNetworkState(NetworkMode mode) {
return apState.load(); 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; return NetworkState::NETWORK_DISABLED;
} }
bool isNetworkConnected() { bool isNetworkConnected() {
return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED; return getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED
|| getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED;
} }
NetworkMode getNetworkMode() { NetworkMode getNetworkMode() {
if (isNetworkConnected()) { if (getNetworkState(networkSettings.type) == NetworkState::NETWORK_CONNECTED) {
return networkSettings.type;
}
if (getNetworkState(NetworkMode::STA) == NetworkState::NETWORK_CONNECTED) {
return NetworkMode::STA; return NetworkMode::STA;
} }
if (getNetworkState(NetworkMode::ETH) == NetworkState::NETWORK_CONNECTED) {
return NetworkMode::ETH;
}
return apStarted.load() ? NetworkMode::AP : NetworkMode::NONE; 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) { bool isNetworkInterfaceStarted(NetworkMode mode) {
if (mode == NetworkMode::STA) { if (mode == NetworkMode::STA) {
return staStarted.load(); return staStarted.load();
} }
#if USE_ETHERNET
if (mode == NetworkMode::ETH) {
return ethStarted.load();
}
#endif
return mode == NetworkMode::AP && apStarted.load(); return mode == NetworkMode::AP && apStarted.load();
} }
@@ -135,15 +229,24 @@ static void notifyNetworkEvent(NetworkEvent event) {
} }
static void setNetworkState(NetworkMode mode, NetworkState next) { static void setNetworkState(NetworkMode mode, NetworkState next) {
auto& state = mode == NetworkMode::STA ? staState : apState; auto* state = mode == NetworkMode::STA ? &staState : &apState;
const NetworkState previous = state.load(); #if USE_ETHERNET
if (mode == NetworkMode::ETH) {
state = &ethState;
}
#endif
const NetworkState previous = state->load();
if (previous == next) { if (previous == next) {
return; return;
} }
if (mode == NetworkMode::STA) { const bool uplink = mode == NetworkMode::STA || mode == NetworkMode::ETH;
if (previous == NetworkState::NETWORK_CONNECTED) { 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(); disconnectedTime = millis();
connectedIp = 0; connectedIp = 0;
vars.network.rssi = 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. // Publish before callbacks so getters and JSON already reflect the new state.
state.store(next); state->store(next);
for (auto& callback : stateCallbacks) { for (auto& callback : stateCallbacks) {
callback(mode, previous, next); callback(mode, previous, next);
} }
if (mode == NetworkMode::STA) { if (uplink) {
if (next == NetworkState::NETWORK_CONNECTED) { if (next == NetworkState::NETWORK_CONNECTED) {
stopMdns();
notifyNetworkEvent(NetworkEvent::CONNECTED); notifyNetworkEvent(NetworkEvent::CONNECTED);
} else if (previous == NetworkState::NETWORK_CONNECTED) { } else if (previous == NetworkState::NETWORK_CONNECTED && !anotherConnected) {
stopMdns();
notifyNetworkEvent(NetworkEvent::DISCONNECTED); 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. // This callback runs in the Arduino event task; only copy the event data here.
switch (event) { switch (event) {
// Station // Station
@@ -228,6 +333,30 @@ static void handleWifiEvent(arduino_event_id_t event, arduino_event_info_t info)
queueNetworkEvent(NetworkEvent::AP_GOT_IP6); queueNetworkEvent(NetworkEvent::AP_GOT_IP6);
break; 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: default:
break; break;
} }
@@ -245,6 +374,10 @@ static void postInterfaceStopped(arduino_event_id_t type) {
} }
// WiFi interfaces // WiFi interfaces
static bool shouldEnableWifiRadio() {
return networkSettings.type == NetworkMode::STA;
}
static void configureWifiRadio() { static void configureWifiRadio() {
// Apply the existing channel policy after the WiFi driver has started. // Apply the existing channel policy after the WiFi driver has started.
const wifi_country_t country = { const wifi_country_t country = {
@@ -271,6 +404,10 @@ static void stopAccessPoint() {
} }
static void startAccessPoint() { static void startAccessPoint() {
if (!shouldEnableWifiRadio()) {
return;
}
lastApAttempt = millis(); lastApAttempt = millis();
setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING); setNetworkState(NetworkMode::AP, NetworkState::AP_STARTING);
@@ -287,9 +424,9 @@ static void startAccessPoint() {
configureWifiRadio(); configureWifiRadio();
WiFi.AP.setHostname(networkSettings.hostname); WiFi.AP.setHostname(networkSettings.hostname);
if (!WiFi.AP.create( if (!WiFi.AP.create(
networkSettings.ap.ssid, networkSettings.wifi.ap.ssid,
networkSettings.ap.password[0] ? networkSettings.ap.password : nullptr, networkSettings.wifi.ap.password[0] ? networkSettings.wifi.ap.password : nullptr,
networkSettings.ap.channel networkSettings.wifi.ap.channel
)) { )) {
stopAccessPoint(); stopAccessPoint();
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
@@ -314,7 +451,7 @@ static bool resetWifi() {
} }
lastConnectionAttempt = 0; lastConnectionAttempt = 0;
if (restoreAp) { if (restoreAp && shouldEnableWifiRadio()) {
startAccessPoint(); startAccessPoint();
} }
@@ -322,6 +459,10 @@ static bool resetWifi() {
} }
static bool startNetworkConnection() { static bool startNetworkConnection() {
if (!shouldEnableWifiRadio()) {
return false;
}
// Ordinary retries preserve AP. Escalate only if STA cannot be stopped. // Ordinary retries preserve AP. Escalate only if STA cannot be stopped.
const bool wasStarted = WiFi.STA.started(); const bool wasStarted = WiFi.STA.started();
@@ -371,15 +512,100 @@ static bool startNetworkConnection() {
); );
return WiFi.STA.connect( return WiFi.STA.connect(
networkSettings.sta.ssid, networkSettings.wifi.sta.ssid,
networkSettings.sta.password[0] ? networkSettings.sta.password : nullptr, networkSettings.wifi.sta.password[0] ? networkSettings.wifi.sta.password : nullptr,
networkSettings.sta.channel 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 // Station connection and recovery timeouts
static void updateConnection() { static void updateConnection() {
if (!networkSettings.sta.ssid[0]) { if (!networkSettings.wifi.sta.ssid[0]) {
return; return;
} }
@@ -433,7 +659,7 @@ static void updateAccessPoint() {
return; 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) { if (!lastApAttempt || millis() - lastApAttempt > 15000) {
ESP_LOGI(L_NETWORK, "Start fallback AP"); ESP_LOGI(L_NETWORK, "Start fallback AP");
startAccessPoint(); startAccessPoint();
@@ -543,6 +769,10 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
switch (pending.event) { switch (pending.event) {
// Station // Station
case NetworkEvent::STA_STARTED: case NetworkEvent::STA_STARTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Repeated START must not invalidate an active connection. // Repeated START must not invalidate an active connection.
if (staStarted.exchange(true)) { if (staStarted.exchange(true)) {
break; break;
@@ -570,24 +800,28 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
} }
case NetworkEvent::STA_CONNECTED: case NetworkEvent::STA_CONNECTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Association alone does not confirm a usable IP address. // Association alone does not confirm a usable IP address.
staAssociated = true; staAssociated = true;
break; break;
case NetworkEvent::STA_GOT_IP: case NetworkEvent::STA_GOT_IP:
if (!pending.value) { if (!shouldEnableWifiRadio() || !pending.value) {
return; return;
} }
// GOT_IP confirms both DHCP and configured static IPv4 after association. // GOT_IP confirms both DHCP and configured static IPv4 after association.
// IP changes invalidate the previous client session, including A -> B -> A. // 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; disconnectReason = 0;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
} }
staAssociated = true; staAssociated = true;
connectedIp = pending.value; connectedIp = pending.value;
if (!isNetworkConnected()) { if (getNetworkState(NetworkMode::STA) != NetworkState::NETWORK_CONNECTED) {
vars.network.rssi = WiFi.STA.RSSI(); vars.network.rssi = WiFi.STA.RSSI();
lastRssiUpdate = millis(); lastRssiUpdate = millis();
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_CONNECTED); setNetworkState(NetworkMode::STA, NetworkState::NETWORK_CONNECTED);
@@ -604,8 +838,72 @@ static void processNetworkEvent(const PendingNetworkEvent& pending) {
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED); setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISCONNECTED);
break; 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 // Access point
case NetworkEvent::AP_STARTED: case NetworkEvent::AP_STARTED:
if (!shouldEnableWifiRadio()) {
return;
}
// Preserve clients and captive portal state on a repeated START. // Preserve clients and captive portal state on a repeated START.
if (apStarted.exchange(true)) { if (apStarted.exchange(true)) {
break; break;
@@ -662,6 +960,10 @@ static void processNetworkEvents() {
staAssociated = false; staAssociated = false;
setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED); setNetworkState(NetworkMode::STA, NetworkState::NETWORK_DISABLED);
setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED); setNetworkState(NetworkMode::AP, NetworkState::NETWORK_DISABLED);
#if USE_ETHERNET
ethStarted.store(false);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
#endif
if (overflowed) { if (overflowed) {
ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi requested"); ESP_LOGW(L_NETWORK, "Network event queue overflow, reset WiFi requested");
@@ -684,6 +986,21 @@ static void processNetworkEvents() {
return; 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; recoveryPending = false;
} }
@@ -700,7 +1017,7 @@ static void processNetworkEvents() {
// Connection services // Connection services
static void updateRssi() { static void updateRssi() {
if (isNetworkConnected() && millis() - lastRssiUpdate >= 1000) { if (getNetworkMode() == NetworkMode::STA && millis() - lastRssiUpdate >= 1000) {
vars.network.rssi = WiFi.STA.RSSI(); vars.network.rssi = WiFi.STA.RSSI();
lastRssiUpdate = millis(); lastRssiUpdate = millis();
} }
@@ -716,7 +1033,7 @@ static void updateNtp() {
} }
static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) { static void logNetworkState(NetworkMode mode, NetworkState previous, NetworkState state) {
if (mode != NetworkMode::STA) { if (mode != networkSettings.type) {
return; return;
} }
@@ -748,25 +1065,31 @@ static Task networkStartTask("Start network services", Task::Type::ONCE, [](void
webServer->begin(); webServer->begin();
webServerReady = true; webServerReady = true;
configureLoggingTask.resume(); 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*) { static Task reconnectTask("Reconnect network", Task::Type::ONCE, [](void*) {
ESP_LOGI(L_NETWORK, "Reconnecting..."); ESP_LOGI(L_NETWORK, "Reconnecting...");
const bool wasStarted = WiFi.STA.started(); #if USE_ETHERNET
if (!WiFi.STA.end()) { if (ethernetRunning) {
ESP_LOGW(L_NETWORK, "Failed stop STA, reset WiFi..."); // Keep the installed SPI device, but cycle the link to reapply hostname and IPv4.
resetWifi(); const esp_err_t result = esp_eth_stop(ETH.handle());
return; if (result != ESP_OK) {
} ESP_LOGE(L_NETWORK, "Failed restart Ethernet: %s", esp_err_to_name(result));
return;
if (wasStarted) { } else {
postInterfaceStopped(ARDUINO_EVENT_WIFI_STA_STOP); ethernetRunning = false;
ethStarted.store(false);
setNetworkState(NetworkMode::ETH, NetworkState::NETWORK_DISABLED);
}
} }
#endif
lastConnectionAttempt = 0; if (!resetWifi()) {
connectionPending = false; networkRecoveryRequested.store(true);
}
}); });
static Task networkTask("Network", [](void*) { static Task networkTask("Network", [](void*) {
@@ -796,6 +1119,29 @@ static Task networkTask("Network", [](void*) {
return; 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 (isNetworkConnected()) {
if (connectionPending) { if (connectionPending) {
connectionPending = false; connectionPending = false;
@@ -836,7 +1182,7 @@ void initNetwork() {
}); });
Network.begin(); Network.begin();
Network.onEvent(handleWifiEvent); Network.onEvent(handleNetworkEvent);
onNetworkStateChange(logNetworkState); onNetworkStateChange(logNetworkState);
WiFi.persistent(false); WiFi.persistent(false);
WiFi.STA.setAutoReconnect(false); WiFi.STA.setAutoReconnect(false);
+45 -12
View File
@@ -13,6 +13,9 @@
#include <Update.h> #include <Update.h>
#include <UpgradeHandler.h> #include <UpgradeHandler.h>
#include <WiFi.h> #include <WiFi.h>
#if USE_ETHERNET
#include <ETH.h>
#endif
#include <MycilaWebSerial.h> #include <MycilaWebSerial.h>
#include <esp_core_dump.h> #include <esp_core_dump.h>
@@ -47,8 +50,16 @@ static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
const IPAddress apIP = WiFi.AP.localIP(); const IPAddress apIP = WiFi.AP.localIP();
const IPAddress staIP = WiFi.STA.localIP(); const IPAddress staIP = WiFi.STA.localIP();
if (localIP == apIP && localIP == staIP) { const bool matchesAp = localIP == apIP;
// Matching AP/STA addresses cannot identify the interface. 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; return RequestInterface::UNKNOWN;
} }
@@ -60,6 +71,10 @@ static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
return RequestInterface::STA; return RequestInterface::STA;
} }
if (matchesEth) {
return RequestInterface::ETH;
}
return RequestInterface::UNKNOWN; return RequestInterface::UNKNOWN;
} }
@@ -373,6 +388,9 @@ static void restApi() {
auto *response = new AsyncJsonResponse(); auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot(); auto& doc = response->getRoot();
toJson(networkSettings, doc); toJson(networkSettings, doc);
#if USE_ETHERNET
doc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
#endif
// send response // send response
response->setLength(); response->setLength();
@@ -403,6 +421,9 @@ static void restApi() {
auto *response = new AsyncJsonResponse(); auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot(); auto& responseDoc = response->getRoot();
toJson(networkSettings, responseDoc); toJson(networkSettings, responseDoc);
#if USE_ETHERNET
responseDoc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
#endif
// send response // send response
response->setLength(); response->setLength();
@@ -415,10 +436,16 @@ static void restApi() {
reconnectNetwork(); reconnectNetwork();
} }
}); });
nsHandler.setMaxContentLength(512); nsHandler.setMaxContentLength(1024);
nsHandler.addMiddleware(&authMiddleware); nsHandler.addMiddleware(&authMiddleware);
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) { 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(); auto apCount = WiFi.scanComplete();
switch (apCount) { switch (apCount) {
@@ -879,22 +906,28 @@ static void restApi() {
auto *response = new AsyncJsonResponse(); auto *response = new AsyncJsonResponse();
auto& doc = response->getRoot(); auto& doc = response->getRoot();
#if USE_ETHERNET
doc[S_FEATURES][S_ETHERNET] = true;
#endif
auto docSystem = doc[S_SYSTEM].to<JsonObject>(); auto docSystem = doc[S_SYSTEM].to<JsonObject>();
docSystem[S_RESET_REASON] = getResetReason(); docSystem[S_RESET_REASON] = getResetReason();
docSystem[S_UPTIME] = millis() / 1000; 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>(); auto docNetwork = doc[S_NETWORK].to<JsonObject>();
docNetwork[S_HOSTNAME] = networkSettings.hostname; docNetwork[S_HOSTNAME] = networkSettings.hostname;
docNetwork[S_MAC] = WiFi.STA.macAddress(); docNetwork[S_MAC] = getNetworkMac();
docNetwork[S_CONNECTED] = isConnected; docNetwork[S_CONNECTED] = isConnected;
docNetwork[S_SSID] = strlen(networkSettings.sta.ssid) ? networkSettings.sta.ssid : nullptr; docNetwork[S_CONNECTION_TYPE] = getNetworkConnectionType();
docNetwork[S_SIGNAL_QUALITY] = isConnected ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0; docNetwork[S_SSID] = wifiUplink ? WiFi.STA.SSID() : "";
docNetwork[S_CHANNEL] = isConnected ? networkSettings.sta.channel : 0; docNetwork[S_SIGNAL_QUALITY] = wifiUplink ? rssiToSignalQuality(WiFi.STA.RSSI()) : 0;
docNetwork[S_IP] = isConnected ? WiFi.STA.localIP().toString() : ""; docNetwork[S_CHANNEL] = wifiUplink ? WiFi.channel() : 0;
docNetwork[S_SUBNET] = isConnected ? WiFi.STA.subnetMask().toString() : ""; docNetwork[S_IP] = isConnected ? getNetworkIp().toString() : "";
docNetwork[S_GATEWAY] = isConnected ? WiFi.STA.gatewayIP().toString() : ""; docNetwork[S_SUBNET] = isConnected ? getNetworkSubnet().toString() : "";
docNetwork[S_DNS] = isConnected ? WiFi.STA.dnsIP().toString() : ""; docNetwork[S_GATEWAY] = isConnected ? getNetworkGateway().toString() : "";
docNetwork[S_DNS] = isConnected ? getNetworkDns().toString() : "";
auto docBuild = doc[S_BUILD].to<JsonObject>(); auto docBuild = doc[S_BUILD].to<JsonObject>();
docBuild[S_VERSION] = BUILD_VERSION; docBuild[S_VERSION] = BUILD_VERSION;
+28 -2
View File
@@ -144,15 +144,34 @@
"network": { "network": {
"title": "网络 - OpenTherm Gateway", "title": "网络 - OpenTherm Gateway",
"name": "网络设置", "name": "网络设置",
"type": {
"title": "连接方式",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": { "section": {
"static": "静态设置", "static": "静态设置",
"ethernet": "以太网",
"wifi": "Wi-Fi",
"availableNetworks": "可用网络", "availableNetworks": "可用网络",
"staSettings": "WiFi 设置", "staSettings": "WiFi 设置",
"apSettings": "AP 设置" "apSettings": "AP 设置"
}, },
"scan": { "scan": {
"pos": "#", "pos": "#",
"info": "Info" "info": "Info",
"unavailable": "仅在 Wi-Fi 模式下可扫描网络。"
},
"ethernet": {
"notConfigured": "配置全部六个 GPIO 引脚以使用以太网。",
"clk": "SPI 时钟 GPIO",
"mosi": "SPI MOSI GPIO",
"miso": "SPI MISO GPIO",
"cs": "SPI CS GPIO",
"irq": "中断 GPIO",
"rst": "复位 GPIO",
"note": "W5500 SPI 接线"
}, },
"wifi": { "wifi": {
"ssid": "SSID", "ssid": "SSID",
@@ -168,7 +187,14 @@
"ip": "IP", "ip": "IP",
"subnet": "子网掩码", "subnet": "子网掩码",
"gateway": "网关", "gateway": "网关",
"dns": "DNS 服务器" "dns": "DNS 服务器",
"connection": "连接",
"connectionType": {
"ethernet": "以太网",
"wifi": "WiFi",
"wifi-ap": "WiFi 接入点",
"none": "无"
}
}, },
"sta": { "sta": {
"channel": { "channel": {
+28 -2
View File
@@ -144,15 +144,34 @@
"network": { "network": {
"title": "Network - OpenTherm Gateway", "title": "Network - OpenTherm Gateway",
"name": "Network settings", "name": "Network settings",
"type": {
"title": "Connection method",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": { "section": {
"static": "Static settings", "static": "Static settings",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Available networks", "availableNetworks": "Available networks",
"staSettings": "WiFi settings", "staSettings": "WiFi settings",
"apSettings": "AP settings" "apSettings": "AP settings"
}, },
"scan": { "scan": {
"pos": "#", "pos": "#",
"info": "Info" "info": "Info",
"unavailable": "Network scanning is available only in Wi-Fi mode."
},
"ethernet": {
"notConfigured": "Configure all six GPIOs to use Ethernet.",
"clk": "SPI clock GPIO",
"mosi": "SPI MOSI GPIO",
"miso": "SPI MISO GPIO",
"cs": "SPI CS GPIO",
"irq": "Interrupt GPIO",
"rst": "Reset GPIO",
"note": "W5500 SPI wiring"
}, },
"wifi": { "wifi": {
"ssid": "SSID", "ssid": "SSID",
@@ -168,7 +187,14 @@
"ip": "IP", "ip": "IP",
"subnet": "Subnet", "subnet": "Subnet",
"gateway": "Gateway", "gateway": "Gateway",
"dns": "DNS" "dns": "DNS",
"connection": "Connection",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "None"
}
}, },
"sta": { "sta": {
"channel": { "channel": {
+28 -2
View File
@@ -144,15 +144,34 @@
"network": { "network": {
"title": "Rete - OpenTherm Gateway", "title": "Rete - OpenTherm Gateway",
"name": "Impostazioni rete", "name": "Impostazioni rete",
"type": {
"title": "Metodo di connessione",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": { "section": {
"static": "Impostazioni statico", "static": "Impostazioni statico",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Reti disponibili", "availableNetworks": "Reti disponibili",
"staSettings": "Impostazioni WiFi", "staSettings": "Impostazioni WiFi",
"apSettings": "Impostazioni AP" "apSettings": "Impostazioni AP"
}, },
"scan": { "scan": {
"pos": "#", "pos": "#",
"info": "Info" "info": "Info",
"unavailable": "La ricerca delle reti è disponibile solo in modalità Wi-Fi."
},
"ethernet": {
"notConfigured": "Configura tutti e sei i GPIO per utilizzare Ethernet.",
"clk": "GPIO clock SPI",
"mosi": "GPIO MOSI SPI",
"miso": "GPIO MISO SPI",
"cs": "GPIO CS SPI",
"irq": "GPIO interrupt",
"rst": "GPIO reset",
"note": "Cablaggio SPI del W5500"
}, },
"wifi": { "wifi": {
"ssid": "SSID", "ssid": "SSID",
@@ -168,7 +187,14 @@
"ip": "IP", "ip": "IP",
"subnet": "Subnet", "subnet": "Subnet",
"gateway": "Gateway", "gateway": "Gateway",
"dns": "DNS" "dns": "DNS",
"connection": "Connessione",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "Nessuno"
}
}, },
"sta": { "sta": {
"channel": { "channel": {
+28 -2
View File
@@ -144,15 +144,34 @@
"network": { "network": {
"title": "Netwerk - OpenTherm Gateway", "title": "Netwerk - OpenTherm Gateway",
"name": "Netwerkinstellingen", "name": "Netwerkinstellingen",
"type": {
"title": "Verbindingsmethode",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": { "section": {
"static": "Statische instellingen", "static": "Statische instellingen",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Beschikbare netwerken", "availableNetworks": "Beschikbare netwerken",
"staSettings": "WiFi-instellingen", "staSettings": "WiFi-instellingen",
"apSettings": "AP-instellingen" "apSettings": "AP-instellingen"
}, },
"scan": { "scan": {
"pos": "#", "pos": "#",
"info": "Info" "info": "Info",
"unavailable": "Netwerken zoeken is alleen beschikbaar in de Wi-Fi-modus."
},
"ethernet": {
"notConfigured": "Configureer alle zes GPIO's om Ethernet te gebruiken.",
"clk": "SPI-klok GPIO",
"mosi": "SPI MOSI GPIO",
"miso": "SPI MISO GPIO",
"cs": "SPI CS GPIO",
"irq": "Interrupt GPIO",
"rst": "Reset GPIO",
"note": "W5500 SPI-bedrading"
}, },
"wifi": { "wifi": {
"ssid": "SSID", "ssid": "SSID",
@@ -168,7 +187,14 @@
"ip": "IP", "ip": "IP",
"subnet": "Subnet", "subnet": "Subnet",
"gateway": "Gateway", "gateway": "Gateway",
"dns": "DNS" "dns": "DNS",
"connection": "Verbinding",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "Geen"
}
}, },
"sta": { "sta": {
"channel": { "channel": {
+28 -2
View File
@@ -144,15 +144,34 @@
"network": { "network": {
"title": "Сеть - OpenTherm Gateway", "title": "Сеть - OpenTherm Gateway",
"name": "Настройки сети", "name": "Настройки сети",
"type": {
"title": "Способ подключения",
"wifi": "Wi-Fi",
"ethernet": "Ethernet"
},
"section": { "section": {
"static": "Статические параметры", "static": "Статические параметры",
"ethernet": "Ethernet",
"wifi": "Wi-Fi",
"availableNetworks": "Доступные сети", "availableNetworks": "Доступные сети",
"staSettings": "Настройки подключения", "staSettings": "Настройки подключения",
"apSettings": "Настройки точки доступа" "apSettings": "Настройки точки доступа"
}, },
"scan": { "scan": {
"pos": "#", "pos": "#",
"info": "Инфо" "info": "Инфо",
"unavailable": "Поиск сетей доступен только в режиме Wi-Fi."
},
"ethernet": {
"notConfigured": "Для подключения через Ethernet настройте все шесть GPIO.",
"clk": "GPIO тактирования SPI",
"mosi": "GPIO MOSI SPI",
"miso": "GPIO MISO SPI",
"cs": "GPIO CS SPI",
"irq": "GPIO прерывания",
"rst": "GPIO сброса",
"note": "Подключение W5500 по SPI"
}, },
"wifi": { "wifi": {
"ssid": "Имя сети", "ssid": "Имя сети",
@@ -168,7 +187,14 @@
"ip": "IP адрес", "ip": "IP адрес",
"subnet": "Адрес подсети", "subnet": "Адрес подсети",
"gateway": "Адрес шлюза", "gateway": "Адрес шлюза",
"dns": "DNS адрес" "dns": "DNS адрес",
"connection": "Подключение",
"connectionType": {
"ethernet": "Ethernet",
"wifi": "WiFi",
"wifi-ap": "WiFi AP",
"none": "Нет"
}
}, },
"sta": { "sta": {
"channel": { "channel": {
+12 -2
View File
@@ -50,15 +50,19 @@
<th scope="row" data-i18n>network.params.mac</th> <th scope="row" data-i18n>network.params.mac</th>
<td><b id="network-mac"></b></td> <td><b id="network-mac"></b></td>
</tr> </tr>
<tr>
<th scope="row" data-i18n>network.params.connection</th>
<td><b id="network-connection"></b></td>
</tr>
<tr> <tr>
<th scope="row" data-i18n>network.wifi.connected</th> <th scope="row" data-i18n>network.wifi.connected</th>
<td><i id="network-connected"></i></td> <td><i id="network-connected"></i></td>
</tr> </tr>
<tr> <tr id="network-ssid-row">
<th scope="row" data-i18n>network.wifi.ssid</th> <th scope="row" data-i18n>network.wifi.ssid</th>
<td><b id="network-ssid"></b></td> <td><b id="network-ssid"></b></td>
</tr> </tr>
<tr> <tr id="network-signal-row">
<th scope="row" data-i18n>network.wifi.signal</th> <th scope="row" data-i18n>network.wifi.signal</th>
<td><b id="network-signal"></b> %</td> <td><b id="network-signal"></b> %</td>
</tr> </tr>
@@ -239,6 +243,7 @@
setTextValue('#network-hostname', result.network.hostname); setTextValue('#network-hostname', result.network.hostname);
setTextValue('#network-mac', result.network.mac); setTextValue('#network-mac', result.network.mac);
setTextValue('#network-connection', i18n(`network.params.connectionType.${result.network.connection_type}`));
setStatus( setStatus(
'#network-connected', '#network-connected',
result.network.connected ? "success" : "error", result.network.connected ? "success" : "error",
@@ -246,6 +251,11 @@
); );
setTextValue('#network-ssid', result.network.ssid); setTextValue('#network-ssid', result.network.ssid);
setValue('#network-signal', result.network.signal_quality); setValue('#network-signal', result.network.signal_quality);
// SSID and signal strength describe only the Wi-Fi uplink.
const wifiUplink = result.network.connection_type === "wifi";
document.getElementById("network-ssid-row")?.classList.toggle("hidden", !wifiUplink);
document.getElementById("network-signal-row")?.classList.toggle("hidden", !wifiUplink);
setTextValue('#network-ip', result.network.ip); setTextValue('#network-ip', result.network.ip);
setTextValue('#network-subnet', result.network.subnet); setTextValue('#network-subnet', result.network.subnet);
setTextValue('#network-gateway', result.network.gateway); setTextValue('#network-gateway', result.network.gateway);
+170 -49
View File
@@ -46,6 +46,14 @@
<input type="text" name="hostname" maxlength="24" pattern="[A-Za-z0-9]+[A-Za-z0-9\-]+[A-Za-z0-9]+" required> <input type="text" name="hostname" maxlength="24" pattern="[A-Za-z0-9]+[A-Za-z0-9\-]+[A-Za-z0-9]+" required>
</label> </label>
<label>
<span data-i18n>network.type.title</span>
<select name="type">
<option value="2" data-i18n>network.type.wifi</option>
<option value="3" hidden disabled data-i18n>network.type.ethernet</option>
</select>
</label>
<label> <label>
<input type="checkbox" name="use_dhcp" value="true"> <input type="checkbox" name="use_dhcp" value="true">
<span data-i18n>network.params.dhcp</span> <span data-i18n>network.params.dhcp</span>
@@ -56,7 +64,7 @@
<label> <label>
<span data-i18n>network.params.ip</span> <span data-i18n>network.params.ip</span>
<input type="text" name="static_config[ip]" value="true" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required> <input type="text" name="static_config[ip]" maxlength="16" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required>
</label> </label>
<label> <label>
@@ -79,34 +87,43 @@
</div> </div>
</article> </article>
<article>
<article id="wifi-section">
<div> <div>
<hgroup>
<h2 data-i18n>network.section.wifi</h2>
<p></p>
</hgroup>
<hgroup> <hgroup>
<h3 data-i18n>network.section.availableNetworks</h3> <h3 data-i18n>network.section.availableNetworks</h3>
<p></p> <p></p>
</hgroup> </hgroup>
<form action="/api/network/scan" id="network-scan"> <form action="/api/network/scan" id="network-scan">
<div style="max-height: 25rem;" class="overflow-auto"> <fieldset id="wifi-scan-controls" disabled>
<table id="networks" role="grid"> <div style="max-height: 25rem;" class="overflow-auto">
<thead> <table id="networks" role="grid">
<tr> <thead>
<th scope="col" data-i18n>network.scan.pos</th> <tr>
<th scope="col" data-i18n>network.wifi.ssid</th> <th scope="col" data-i18n>network.scan.pos</th>
<th scope="col" data-i18n>network.scan.info</th> <th scope="col" data-i18n>network.wifi.ssid</th>
</tr> <th scope="col" data-i18n>network.scan.info</th>
</thead> </tr>
<tbody></tbody> </thead>
</table> <tbody></tbody>
</div> </table>
</div>
<button type="submit" data-i18n>button.refresh</button> <p id="scan-unavailable" class="hidden" data-i18n>network.scan.unavailable</p>
<button type="submit" data-i18n>button.refresh</button>
</fieldset>
</form> </form>
<hr /> <hr />
<div> <div>
<hgroup> <hgroup>
<h2 data-i18n>network.section.staSettings</h2> <h3 data-i18n>network.section.staSettings</h3>
<p></p> <p></p>
</hgroup> </hgroup>
@@ -114,49 +131,100 @@
<form action="/api/network/settings" id="sta-settings" class="hidden"> <form action="/api/network/settings" id="sta-settings" class="hidden">
<label> <label>
<span data-i18n>network.wifi.ssid</span> <span data-i18n>network.wifi.ssid</span>
<input type="text" name="sta[ssid]" maxlength="32" required> <input type="text" name="wifi[sta][ssid]" maxlength="32" required>
</label> </label>
<label> <label>
<span data-i18n>network.wifi.password</span> <span data-i18n>network.wifi.password</span>
<input type="password" name="sta[password]" maxlength="64" required> <input type="password" name="wifi[sta][password]" maxlength="64" required>
</label> </label>
<label> <label>
<span data-i18n>network.wifi.channel</span> <span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="sta[channel]" min="0" max="12" step="1" required> <input type="number" inputmode="numeric" name="wifi[sta][channel]" min="0" max="12" step="1" required>
<small data-i18n>network.sta.channel.note</small> <small data-i18n>network.sta.channel.note</small>
</label> </label>
<button type="submit" data-i18n>button.save</button> <button type="submit" data-i18n>button.save</button>
</form> </form>
</div> </div>
<hr />
<div>
<hgroup>
<h3 data-i18n>network.section.apSettings</h3>
<p></p>
</hgroup>
<div id="ap-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="ap-settings" class="hidden">
<label>
<span data-i18n>network.wifi.ssid</span>
<input type="text" name="wifi[ap][ssid]" maxlength="32" required>
</label>
<label>
<span data-i18n>network.wifi.password</span>
<input type="text" name="wifi[ap][password]" maxlength="64" required>
</label>
<label>
<span data-i18n>network.wifi.channel</span>
<input type="number" inputmode="numeric" name="wifi[ap][channel]" min="1" max="12" step="1" required>
</label>
<button type="submit" data-i18n>button.save</button>
</form>
</div>
</div> </div>
</article> </article>
<article> <article id="ethernet-section" class="hidden">
<div> <div>
<hgroup> <hgroup>
<h2 data-i18n>network.section.apSettings</h2> <h3 data-i18n>network.section.ethernet</h3>
<p></p> <p></p>
</hgroup> </hgroup>
<div id="ap-settings-busy" aria-busy="true"></div> <div id="ethernet-settings-busy" aria-busy="true"></div>
<form action="/api/network/settings" id="ap-settings" class="hidden"> <form action="/api/network/settings" id="ethernet-settings" class="hidden">
<label> <small id="ethernet-not-configured" class="hidden" data-i18n>network.ethernet.notConfigured</small>
<span data-i18n>network.wifi.ssid</span>
<input type="text" name="ap[ssid]" maxlength="32" required>
</label>
<label> <div class="grid">
<span data-i18n>network.wifi.password</span> <label>
<input type="text" name="ap[password]" maxlength="64" required> <span data-i18n>network.ethernet.clk</span>
</label> <input type="number" inputmode="numeric" name="ethernet[gpio][clk]" min="0" max="254" step="1">
</label>
<label> <label>
<span data-i18n>network.wifi.channel</span> <span data-i18n>network.ethernet.mosi</span>
<input type="number" inputmode="numeric" name="ap[channel]" min="1" max="12" step="1" required> <input type="number" inputmode="numeric" name="ethernet[gpio][mosi]" min="0" max="254" step="1">
</label> </label>
<label>
<span data-i18n>network.ethernet.miso</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][miso]" min="0" max="254" step="1">
</label>
</div>
<div class="grid">
<label>
<span data-i18n>network.ethernet.cs</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][cs]" min="0" max="254" step="1">
</label>
<label>
<span data-i18n>network.ethernet.irq</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][irq]" min="0" max="254" step="1">
</label>
<label>
<span data-i18n>network.ethernet.rst</span>
<input type="number" inputmode="numeric" name="ethernet[gpio][rst]" min="0" max="254" step="1">
</label>
</div>
<small data-i18n>network.ethernet.note</small>
<button type="submit" data-i18n>button.save</button> <button type="submit" data-i18n>button.save</button>
</form> </form>
@@ -181,7 +249,16 @@
const lang = new Lang(document.getElementById('lang')); const lang = new Lang(document.getElementById('lang'));
await lang.build(); await lang.build();
let networkType = 2;
const fillData = (data) => { const fillData = (data) => {
networkType = data.type;
setSelectValue("[name='type']", networkType);
const canScan = networkType === 2;
document.getElementById('wifi-scan-controls').disabled = !canScan;
document.querySelector('#scan-unavailable').classList.toggle('hidden', canScan);
setInputValue("[name='hostname']", data.hostname); setInputValue("[name='hostname']", data.hostname);
setCheckboxValue("[name='use_dhcp']", data.use_dhcp); setCheckboxValue("[name='use_dhcp']", data.use_dhcp);
setInputValue("[name='static_config[ip]']", data.static_config.ip); setInputValue("[name='static_config[ip]']", data.static_config.ip);
@@ -190,34 +267,78 @@
setInputValue("[name='static_config[dns]']", data.static_config.dns); setInputValue("[name='static_config[dns]']", data.static_config.dns);
setBusy('#network-settings-busy', '#network-settings', false); setBusy('#network-settings-busy', '#network-settings', false);
setInputValue("[name='sta[ssid]']", data.sta.ssid); const ethernet = data.ethernet || {};
setInputValue("[name='sta[password]']", data.sta.password); const ethernetConfigured = !!ethernet.configured;
setInputValue("[name='sta[channel]']", data.sta.channel); const ethernetGpio = ethernet.gpio || {};
const gpioValue = (value) => (value ?? 255) < 255 ? value : '';
setInputValue("[name='ethernet[gpio][clk]']", gpioValue(ethernetGpio.clk));
setInputValue("[name='ethernet[gpio][mosi]']", gpioValue(ethernetGpio.mosi));
setInputValue("[name='ethernet[gpio][miso]']", gpioValue(ethernetGpio.miso));
setInputValue("[name='ethernet[gpio][cs]']", gpioValue(ethernetGpio.cs));
setInputValue("[name='ethernet[gpio][irq]']", gpioValue(ethernetGpio.irq));
setInputValue("[name='ethernet[gpio][rst]']", gpioValue(ethernetGpio.rst));
document.getElementById('ethernet-not-configured')?.classList.toggle('hidden', ethernetConfigured);
setBusy('#ethernet-settings-busy', '#ethernet-settings', false);
setInputValue("[name='wifi[sta][ssid]']", data.wifi.sta.ssid);
setInputValue("[name='wifi[sta][password]']", data.wifi.sta.password);
setInputValue("[name='wifi[sta][channel]']", data.wifi.sta.channel);
setBusy('#sta-settings-busy', '#sta-settings', false); setBusy('#sta-settings-busy', '#sta-settings', false);
setInputValue("[name='ap[ssid]']", data.ap.ssid); setInputValue("[name='wifi[ap][ssid]']", data.wifi.ap.ssid);
setInputValue("[name='ap[password]']", data.ap.password); setInputValue("[name='wifi[ap][password]']", data.wifi.ap.password);
setInputValue("[name='ap[channel]']", data.ap.channel); setInputValue("[name='wifi[ap][channel]']", data.wifi.ap.channel);
setBusy('#ap-settings-busy', '#ap-settings', false); setBusy('#ap-settings-busy', '#ap-settings', false);
}; };
const applyCapabilities = (info) => {
// pages and firmware ship together: the section stays hidden unless the build says it can do ethernet
const supported = info?.features?.ethernet === true;
document.getElementById('ethernet-section')?.classList.toggle('hidden', !supported);
const ethernetOption = document.querySelector("[name='type'] option[value='3']");
ethernetOption.hidden = !supported;
ethernetOption.disabled = !supported;
return supported;
};
try { try {
const response = await fetch("/api/network/settings", { const [response, infoResponse] = await Promise.all([
cache: "no-cache", fetch("/api/network/settings", {
credentials: "include" cache: "no-cache",
}); credentials: "include"
}),
fetch("/api/info", {
cache: "no-cache",
credentials: "include"
})
]);
if (!response.ok) { if (!response.ok) {
throw new Error('Response not valid'); throw new Error('Response not valid');
} }
const info = infoResponse.ok ? await infoResponse.json() : null;
const ethernetSupported = applyCapabilities(info);
const result = await response.json(); const result = await response.json();
fillData(result); fillData(result);
setupForm('#network-settings', fillData, ['hostname', 'static_config.ip', 'static_config.gateway', 'static_config.subnet', 'static_config.dns']); setupForm('#network-settings', fillData, ['hostname', 'static_config.ip', 'static_config.gateway', 'static_config.subnet', 'static_config.dns']);
setupNetworkScanForm('#network-scan', '#networks');
setupForm('#sta-settings', fillData, ['sta.ssid', 'sta.password']); // Keep scans disabled if an earlier request finishes after the connection method changes.
setupForm('#ap-settings', fillData, ['ap.ssid', 'ap.password']); setupNetworkScanForm('#network-scan', '#networks', networkType === 2);
if (ethernetSupported) {
setupForm('#ethernet-settings', fillData);
}
setupForm('#sta-settings', fillData, ['wifi.sta.ssid', 'wifi.sta.password']);
setupForm('#ap-settings', fillData, ['wifi.ap.ssid', 'wifi.ap.password']);
} catch (error) { } catch (error) {
console.log(error); console.log(error);
+38
View File
@@ -97,6 +97,44 @@ const convertLegacyBackup = (data) => {
const result = convert(data); const result = convert(data);
const network = result?.network;
if (network !== null && typeof network === 'object' && !Array.isArray(network)) {
const hasLegacyAp = Object.prototype.hasOwnProperty.call(network, 'ap');
const hasLegacySta = Object.prototype.hasOwnProperty.call(network, 'sta');
if (hasLegacyAp || hasLegacySta) {
const wifi = network.wifi !== null && typeof network.wifi === 'object' && !Array.isArray(network.wifi)
? network.wifi : Object.create(null);
if (hasLegacyAp && !Object.prototype.hasOwnProperty.call(wifi, 'ap')) {
wifi.ap = network.ap;
}
if (hasLegacySta && !Object.prototype.hasOwnProperty.call(wifi, 'sta')) {
wifi.sta = network.sta;
}
network.wifi = wifi;
delete network.ap;
delete network.sta;
}
if (!Object.prototype.hasOwnProperty.call(network, 'type')) {
if (typeof network.ethernet?.enabled === 'boolean') {
network.type = network.ethernet.enabled ? 3 : 2;
} else if (hasLegacyAp || hasLegacySta) {
network.type = 2;
}
}
if (network.ethernet !== null && typeof network.ethernet === 'object' && !Array.isArray(network.ethernet)) {
if (Object.prototype.hasOwnProperty.call(network.ethernet, 'pins')
&& !Object.prototype.hasOwnProperty.call(network.ethernet, 'gpio')) {
network.ethernet.gpio = network.ethernet.pins;
}
delete network.ethernet.pins;
delete network.ethernet.enabled;
}
}
const opentherm = result?.settings?.opentherm; const opentherm = result?.settings?.opentherm;
if (opentherm !== null && typeof opentherm === 'object') { if (opentherm !== null && typeof opentherm === 'object') {
delete opentherm.unit_system; delete opentherm.unit_system;
+4 -2
View File
@@ -92,7 +92,7 @@ const setupForm = (formSelector, onResultCallback = null, noCastItems = []) => {
}); });
} }
const setupNetworkScanForm = (formSelector, tableSelector) => { const setupNetworkScanForm = (formSelector, tableSelector, autorun = true) => {
const form = document.querySelector(formSelector); const form = document.querySelector(formSelector);
if (!form) { if (!form) {
console.error("form not found"); console.error("form not found");
@@ -261,7 +261,9 @@ const setupNetworkScanForm = (formSelector, tableSelector) => {
}; };
form.addEventListener('submit', onSubmitFn); form.addEventListener('submit', onSubmitFn);
onSubmitFn(); if (autorun) {
onSubmitFn();
}
} }
const setBusy = (busySelector, contentSelector, value, parent = undefined) => { const setBusy = (busySelector, contentSelector, value, parent = undefined) => {