Merge observer firmware branch into keymindCascade
Integrate compatible observer board, preset, WebConfig, display, CI, and policy updates. Preserve the checkout's newer MQTT binary preferences and WiFi bridge runtime where the forked implementations conflict. Keep ThinkNode observer networking WiFi-based until the Ethernet transport is wired into that runtime.
This commit is contained in:
commit
1e8ef78a2e
51 files changed
+6495
-1973
No files matched your search
@@ -8,8 +8,8 @@ protected:
|
||||
CommonRadioPrefs() { }
|
||||
public:
|
||||
void markDirty() { _is_dirty = true; }
|
||||
void clearDirty() { _is_dirty = false; }
|
||||
bool isDirty() const { return _is_dirty; }
|
||||
void clearDirty() override { _is_dirty = false; }
|
||||
bool isDirty() const override { return _is_dirty; }
|
||||
|
||||
virtual float getFreq() const = 0;
|
||||
virtual void setFreq(float f) = 0;
|
||||
|
||||
@@ -33,13 +33,24 @@
|
||||
// Fix: [esp32_base] adds `-Wl,--wrap=esp_transport_ws_init`, so every
|
||||
// creation of a WS transport (esp-mqtt does one per wss slot) is routed
|
||||
// through __wrap_esp_transport_ws_init below, which replaces the freshly
|
||||
// allocated 1024-byte buffer with a (WS_BUFFER_SIZE + 1)-byte one. The
|
||||
// out-of-bounds index WS_BUFFER_SIZE then lands on our extra byte and the
|
||||
// handshake fails cleanly ("Upgrade" header not found) instead of corrupting
|
||||
// the heap. Upstream fixed this in ESP-IDF 5.x, so this file compiles to a
|
||||
// allocated 1024-byte buffer with a (WS_BUFFER_SIZE + 1)-byte one, so the
|
||||
// out-of-bounds index WS_BUFFER_SIZE lands on our extra byte instead of the
|
||||
// heap canary. Upstream fixed this in ESP-IDF 5.x, so this file compiles to a
|
||||
// pass-through there and can be deleted (together with the --wrap flag) when
|
||||
// the fork moves to Arduino core 3.x.
|
||||
//
|
||||
// Scope: this stops the heap corruption and NOTHING else. It does not make an
|
||||
// oversized response fail the handshake — v4.4's read loop also exits on
|
||||
// `header_len < WS_BUFFER_SIZE` going false, and then still accepts the
|
||||
// connection if "Sec-WebSocket-Accept:" was inside those first bytes (it comes
|
||||
// early, so it usually is). ws_connect() therefore returns success on a partial
|
||||
// header block and the unread remainder arrives as the first "payload" read,
|
||||
// where the deframer parses HTTP bytes as a frame header. Observed on hardware
|
||||
// 2026-08-12: a large Cloudflare CSP header produced exactly that, surfacing as
|
||||
// `Invalid MSG_TYPE response: 3`. Only IDF 5.2+ fixes it (it requires the
|
||||
// "\r\n\r\n" delimiter, preserves the bytes after it, and fails cleanly when the
|
||||
// buffer fills); it cannot be patched here because transport_ws.c is precompiled.
|
||||
//
|
||||
// transport_ws_t below is copied verbatim from ESP-IDF release/v4.4
|
||||
// transport_ws.c (the struct is file-private, so it is not in any shipped
|
||||
// header). Source fidelity was verified against the shipped binary: addr2line
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// What a slot's MQTT client is doing, as opposed to whether its network is up,
|
||||
// and the two decisions that hang off it.
|
||||
//
|
||||
// Pure logic: no Arduino, esp-mqtt or bridge dependency, so the shutdown
|
||||
// contract below is a host test rather than a hardware run.
|
||||
//
|
||||
// `client->connected()` answers "is the network up" and was being used for "is
|
||||
// there anything to stop": a client resolving DNS, negotiating TLS or waiting
|
||||
// after a failed CONNECT reports not-connected, so teardown skipped it and left
|
||||
// its task running (F04).
|
||||
|
||||
enum class MqttClientState : uint8_t {
|
||||
Absent = 0, // no client object
|
||||
Configured, // client allocated, never started
|
||||
Starting, // start/reconnect requested, awaiting CONNECTED
|
||||
Connected, // CONNECTED received
|
||||
Disconnected, // started, no session (our reconnect ladder governs it)
|
||||
Stopped, // stop completed; the SDK task is joined and gone
|
||||
Quarantined, // stop failed: the SDK task was NOT joined. Never destroy,
|
||||
// never reuse, never free anything it still points at.
|
||||
};
|
||||
|
||||
static inline const char* mqttClientStateName(MqttClientState s) {
|
||||
switch (s) {
|
||||
case MqttClientState::Absent: return "absent";
|
||||
case MqttClientState::Configured: return "configured";
|
||||
case MqttClientState::Starting: return "starting";
|
||||
case MqttClientState::Connected: return "connected";
|
||||
case MqttClientState::Disconnected: return "disconnected";
|
||||
case MqttClientState::Stopped: return "stopped";
|
||||
case MqttClientState::Quarantined: return "quarantined";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
// The client has been started and not proven stopped: it may still own a task,
|
||||
// a socket and a TLS context. Quarantined is deliberately NOT live — it is
|
||||
// worse: it may own them and we can never find out.
|
||||
static inline bool mqttClientStateIsLive(MqttClientState s) {
|
||||
return s == MqttClientState::Starting || s == MqttClientState::Connected ||
|
||||
s == MqttClientState::Disconnected;
|
||||
}
|
||||
|
||||
// A connection attempt is in flight, so an event for it can still arrive.
|
||||
// Closing the transport is not enough here: PsychicMqttClient::softDisconnect()
|
||||
// returns immediately when the client is not yet connected, which means an
|
||||
// in-progress DNS/TLS/CONNECT is left to complete on its own. Cancelling one
|
||||
// requires a real stop.
|
||||
static inline bool mqttClientStateHasAttemptInFlight(MqttClientState s) {
|
||||
return s == MqttClientState::Starting;
|
||||
}
|
||||
|
||||
// The SDK task is known to be gone (or never existed), so the object may be
|
||||
// destroyed and anything it pointed at may be freed.
|
||||
static inline bool mqttClientStateIsProvenStopped(MqttClientState s) {
|
||||
return s == MqttClientState::Absent || s == MqttClientState::Configured ||
|
||||
s == MqttClientState::Stopped;
|
||||
}
|
||||
|
||||
// The bridge's cooperative stop may only be acknowledged when EVERY client is
|
||||
// proven stopped.
|
||||
//
|
||||
// This is the invariant the whole shutdown contract rests on: the owner treats
|
||||
// the acknowledgement as proof that the task destroyed its clients, and only
|
||||
// then frees the queue and buffers and allows a restart. One client whose
|
||||
// esp_mqtt_client_stop() never completed makes that false — its SDK task may
|
||||
// still be running — so the acknowledgement must be withheld and the bridge
|
||||
// left in its unproven state, however many other slots stopped cleanly.
|
||||
static inline bool mqttStopMayBeAcknowledged(const MqttClientState* states, int count) {
|
||||
// An empty set is trivially proven (no slots, nothing to stop); a null array
|
||||
// with a nonzero count is a caller bug and must not read as proof.
|
||||
if (count <= 0) return true;
|
||||
if (states == nullptr) return false;
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (!mqttClientStateIsProvenStopped(states[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// The complete, owned description of what a slot's MQTT client should be
|
||||
// configured with, plus the decision of whether the existing SDK client can be
|
||||
// reconfigured in place or has to be recreated.
|
||||
//
|
||||
// Pure logic: no Arduino, esp-mqtt or PsychicMqttClient dependency, so every
|
||||
// transition in the table below is exercised on the host
|
||||
// (test/test_mqtt_effective_config).
|
||||
//
|
||||
// Why this exists (F02/F03). The bridge used to apply configuration field by
|
||||
// field, skipping the cleanup of stale fields whenever
|
||||
// `slot.initial_connect_done` was false — which `teardownSlot()` had just
|
||||
// cleared, so normal live reconfiguration always skipped it. On hardware that
|
||||
// sent the previous broker's JWT username in the CONNECT to a newly configured
|
||||
// anonymous endpoint. Two rules fix it:
|
||||
//
|
||||
// 1. Every field is written on every apply. "Absent" is a value that gets
|
||||
// written (the empty string), never an omission — IDF's
|
||||
// `esp_mqtt_set_if_config()` treats NULL as "leave unchanged", so a
|
||||
// cleared wrapper pointer cannot erase an SDK-held credential, while an
|
||||
// empty string both overwrites it and leaves the CONNECT's username flag
|
||||
// clear (verified on an ESP32-S3 against a local broker, IDF 4.4).
|
||||
// 2. Where a field cannot be overwritten safely, the client is recreated.
|
||||
// That is the exception, not the rule: esp-mqtt's stop/start cycle is the
|
||||
// fork's documented internal-heap fragmentation driver, so recreation must
|
||||
// never happen on the reconnect or token-renewal path.
|
||||
|
||||
// Matches MQTTSlot::broker_uri so an effective config can hold its own copy.
|
||||
#define MQTT_EFFECTIVE_URI_MAX 128
|
||||
|
||||
enum class MqttTransport : uint8_t {
|
||||
Unknown = 0,
|
||||
Tcp, // mqtt://
|
||||
Tls, // mqtts://
|
||||
Ws, // ws://
|
||||
Wss, // wss://
|
||||
};
|
||||
|
||||
enum class MqttTrust : uint8_t {
|
||||
Plaintext = 0, // unencrypted transport: no server verification exists
|
||||
Bundle, // shared CA bundle attach callback
|
||||
PemCert, // one specific CA certificate
|
||||
};
|
||||
|
||||
enum class MqttAuth : uint8_t {
|
||||
None = 0,
|
||||
UserPass,
|
||||
Jwt,
|
||||
};
|
||||
|
||||
struct MqttEffectiveConfig {
|
||||
char uri[MQTT_EFFECTIVE_URI_MAX] = {0};
|
||||
MqttTransport transport = MqttTransport::Unknown;
|
||||
MqttTrust trust = MqttTrust::Plaintext;
|
||||
MqttAuth auth = MqttAuth::None;
|
||||
// Borrowed pointers with a lifetime at least as long as the client's: preset
|
||||
// certificates live in flash, credentials in the slot/bridge storage.
|
||||
const char* pem = nullptr;
|
||||
const char* username = nullptr; // nullptr == absent, written as ""
|
||||
const char* password = nullptr;
|
||||
uint16_t buffer_size = 0;
|
||||
uint16_t keepalive = 0;
|
||||
bool valid = false; // false until successfully built
|
||||
};
|
||||
|
||||
// Client certificates are deliberately absent: `setClientCertificate()` has no
|
||||
// caller in the firmware (no broker preset uses mutual TLS), so modelling it
|
||||
// here would be untested configuration surface. Adding mutual TLS means adding
|
||||
// it to this struct and to the recreate decision below.
|
||||
|
||||
static inline MqttTransport mqttTransportFromUri(const char* uri) {
|
||||
if (uri == nullptr) return MqttTransport::Unknown;
|
||||
if (strncmp(uri, "mqtts://", 8) == 0) return MqttTransport::Tls;
|
||||
if (strncmp(uri, "mqtt://", 7) == 0) return MqttTransport::Tcp;
|
||||
if (strncmp(uri, "wss://", 6) == 0) return MqttTransport::Wss;
|
||||
if (strncmp(uri, "ws://", 5) == 0) return MqttTransport::Ws;
|
||||
return MqttTransport::Unknown;
|
||||
}
|
||||
|
||||
static inline bool mqttTransportIsEncrypted(MqttTransport t) {
|
||||
return t == MqttTransport::Tls || t == MqttTransport::Wss;
|
||||
}
|
||||
|
||||
static inline const char* mqttTransportName(MqttTransport t) {
|
||||
switch (t) {
|
||||
case MqttTransport::Tcp: return "mqtt";
|
||||
case MqttTransport::Tls: return "mqtts";
|
||||
case MqttTransport::Ws: return "ws";
|
||||
case MqttTransport::Wss: return "wss";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
// A credential the SDK must be told to forget is written as "" rather than
|
||||
// left NULL. See rule 1 above.
|
||||
static inline const char* mqttFieldOrEmpty(const char* v) { return v ? v : ""; }
|
||||
|
||||
// Builds an effective config, deriving the transport from the URI and
|
||||
// normalising the trust policy against it: an unencrypted transport verifies
|
||||
// nothing, whatever certificate material was requested, so recording anything
|
||||
// else would make a plaintext endpoint look like a trust change away from a
|
||||
// verified one (and vice versa). Returns false for an empty or unrecognised
|
||||
// URI, leaving *out invalid.
|
||||
static inline bool mqttBuildEffectiveConfig(const char* uri,
|
||||
MqttAuth auth,
|
||||
const char* username,
|
||||
const char* password,
|
||||
MqttTrust requested_trust,
|
||||
const char* pem,
|
||||
uint16_t buffer_size,
|
||||
uint16_t keepalive,
|
||||
MqttEffectiveConfig* out) {
|
||||
if (out == nullptr) return false;
|
||||
*out = MqttEffectiveConfig();
|
||||
if (uri == nullptr || uri[0] == '\0') return false;
|
||||
if (strlen(uri) >= MQTT_EFFECTIVE_URI_MAX) return false;
|
||||
|
||||
const MqttTransport transport = mqttTransportFromUri(uri);
|
||||
if (transport == MqttTransport::Unknown) return false;
|
||||
|
||||
strncpy(out->uri, uri, MQTT_EFFECTIVE_URI_MAX - 1);
|
||||
out->uri[MQTT_EFFECTIVE_URI_MAX - 1] = '\0';
|
||||
out->transport = transport;
|
||||
out->auth = auth;
|
||||
out->username = username;
|
||||
out->password = password;
|
||||
out->buffer_size = buffer_size;
|
||||
out->keepalive = keepalive;
|
||||
|
||||
if (!mqttTransportIsEncrypted(transport)) {
|
||||
out->trust = MqttTrust::Plaintext;
|
||||
out->pem = nullptr;
|
||||
} else if (requested_trust == MqttTrust::PemCert && pem != nullptr) {
|
||||
out->trust = MqttTrust::PemCert;
|
||||
out->pem = pem;
|
||||
} else if (requested_trust == MqttTrust::Bundle) {
|
||||
out->trust = MqttTrust::Bundle;
|
||||
} else {
|
||||
// Encrypted transport with no usable trust material. Recorded as Plaintext
|
||||
// trust so it is never confused with a verified policy; whether to connect
|
||||
// at all is the caller's decision.
|
||||
out->trust = MqttTrust::Plaintext;
|
||||
}
|
||||
|
||||
out->valid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct MqttRecreateDecision {
|
||||
bool recreate = false;
|
||||
const char* reason = "reuse"; // static literal, for logs and tests
|
||||
};
|
||||
|
||||
// Whether the SDK client that `applied` was written to can be reconfigured in
|
||||
// place to reach `desired`.
|
||||
//
|
||||
// transport (scheme) change -> recreate. One `wss`->`mqtt` transition was
|
||||
// observed working by reuse on hardware, but that proves one direction
|
||||
// once, not that no websocket transport state survives the switch; the
|
||||
// retained-`frame_state` bug class is real and unfixed upstream even in
|
||||
// IDF 5.3, and this transition only happens when an operator changes the
|
||||
// endpoint.
|
||||
// trust change -> recreate. `cert_pem` cannot be cleared by
|
||||
// writing "" (an empty PEM is a parse failure, not "no certificate"), and
|
||||
// the bundle attach is a function pointer whose set_config semantics are
|
||||
// not established on this build. Verification policy is the one field
|
||||
// where a stale value silently weakens security.
|
||||
// capacity growth -> recreate. IDF 4.4 allocates the MQTT buffers
|
||||
// in `esp_mqtt_client_init()` and `esp_mqtt_set_config()` does not resize
|
||||
// them; the wrapper's own reassembly buffer is likewise allocated once.
|
||||
// everything else -> reuse, including every credential and
|
||||
// auth-mode change, because those are rewritten unconditionally.
|
||||
static inline MqttRecreateDecision mqttConfigRecreateDecision(
|
||||
const MqttEffectiveConfig& applied,
|
||||
const MqttEffectiveConfig& desired,
|
||||
uint16_t allocated_buffer_size) {
|
||||
MqttRecreateDecision d;
|
||||
if (!desired.valid) {
|
||||
d.recreate = false;
|
||||
d.reason = "invalid-desired";
|
||||
return d;
|
||||
}
|
||||
if (!applied.valid) {
|
||||
// Nothing applied yet: a fresh client needs configuring, not recreating.
|
||||
d.reason = "first-apply";
|
||||
return d;
|
||||
}
|
||||
if (applied.transport != desired.transport) {
|
||||
d.recreate = true;
|
||||
d.reason = "transport-change";
|
||||
return d;
|
||||
}
|
||||
if (applied.trust != desired.trust) {
|
||||
d.recreate = true;
|
||||
d.reason = "trust-change";
|
||||
return d;
|
||||
}
|
||||
if (desired.trust == MqttTrust::PemCert && applied.pem != desired.pem) {
|
||||
d.recreate = true;
|
||||
d.reason = "ca-cert-change";
|
||||
return d;
|
||||
}
|
||||
if (desired.buffer_size > allocated_buffer_size) {
|
||||
d.recreate = true;
|
||||
d.reason = "buffer-growth";
|
||||
return d;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "MQTTPresets.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
// Policy that keys off a preset rather than describing one.
|
||||
//
|
||||
// MQTTPresets.h is data: it is the broker table, and it is kept byte-identical
|
||||
// between the observer-firmware and observer-firmware-dev channels so a node
|
||||
// that rolls back cannot meet a preset name its firmware does not know. An
|
||||
// unknown name is not merely ignored — MQTTPrefsSerializer repairs it to "none"
|
||||
// and the repaired /mqtt.json is written back, so the operator's slot is gone
|
||||
// for good. Channel-specific behaviour therefore lives here instead, where the
|
||||
// two channels are free to differ.
|
||||
|
||||
// True when the broker tears down a live session once its JWT passes exp, so the
|
||||
// renewal must proactively bounce the connection to present a fresh token.
|
||||
//
|
||||
// Default true, because getting this wrong the safe way costs a re-handshake and
|
||||
// getting it wrong the unsafe way costs an outage. waev is the exception: its
|
||||
// operator confirmed (2026-08-11) that their servers do not disconnect on expiry,
|
||||
// so a live session there needs only its credentials refreshed for the next
|
||||
// reconnect. waev is also the only preset with a short token_lifetime, so it was
|
||||
// the only one bouncing often — every ~47 min, and each bounce's re-handshake can
|
||||
// cost ~10 KB of contiguous internal DRAM on a non-PSRAM board.
|
||||
//
|
||||
// Keyed by name rather than a struct field on purpose: adding a field would mean
|
||||
// re-ordering a dozen positional initialisers in the table, where a mistake is
|
||||
// silent.
|
||||
static inline bool mqttPresetEnforcesTokenExp(const MQTTPresetDef* preset) {
|
||||
if (!preset || !preset->name) return true; // custom/audience slots: assume enforced
|
||||
return strcmp(preset->name, "waev") != 0;
|
||||
}
|
||||
@@ -87,7 +87,7 @@ static inline bool mqttPresetNeedsSlotCredentials(const MQTTPresetDef* preset) {
|
||||
}
|
||||
|
||||
// Number of built-in presets
|
||||
static const int MQTT_PRESET_COUNT = 36;
|
||||
static const int MQTT_PRESET_COUNT = 37;
|
||||
|
||||
// Keep the certificate and preset tables in one translation unit. Defining
|
||||
// these as header-local constants created a complete flash copy in every MQTT
|
||||
@@ -199,6 +199,7 @@ extern const MQTTPresetDef MQTT_PRESETS[MQTT_PRESET_COUNT] = {
|
||||
{ "idahomesh", "wss://mqtt.idahomesh.org:443/mqtt", "mqtt.idahomesh.org", ISRG_ROOT_X1, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE, 0, true, 55, nullptr, nullptr },
|
||||
{ "ntxmesh", "wss://ntxmesh.dhovin.me:8883", "ntxmesh.dhovin.me", ISRG_ROOT_X1, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE, 0, true, 55, nullptr, nullptr },
|
||||
{ "bsmesh", "wss://mqtt.bsmesh.de:8885", "mqtt.bsmesh.de", ISRG_ROOT_X1, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE, 0, true, 55, nullptr, nullptr },
|
||||
{ "marwoj", "mqtts://mqtt.marwoj.net:8883", nullptr, ISRG_ROOT_X1, MQTT_AUTH_USERPASS, MQTT_TOPIC_MESHCORE, 0, true, 55, "observer-agessaman", "ipRwCEclZkX47K" },
|
||||
};
|
||||
|
||||
#else
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace NetworkHostname {
|
||||
|
||||
// ESP-IDF documents a 32-byte hostname limit. Keep one byte for the trailing
|
||||
// NUL so the same buffer is safe through Arduino and lwIP APIs.
|
||||
static constexpr size_t kMaxLength = 31;
|
||||
static constexpr size_t kBufferSize = kMaxLength + 1;
|
||||
|
||||
static inline bool isAsciiAlphaNumeric(uint8_t ch) {
|
||||
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9');
|
||||
}
|
||||
|
||||
static inline char asciiLower(uint8_t ch) {
|
||||
return ch >= 'A' && ch <= 'Z' ? static_cast<char>(ch + ('a' - 'A'))
|
||||
: static_cast<char>(ch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a DHCP-safe hostname from the MeshCore node name.
|
||||
*
|
||||
* The result is lowercase, starts with "meshcore-", contains only letters,
|
||||
* digits and hyphens, and never exceeds ESP-IDF's practical 31-character
|
||||
* payload limit. Six hex digits from the stable node identity are retained
|
||||
* whenever non-ASCII bytes are removed, a fallback is needed, or the readable
|
||||
* name must be shortened. This keeps lossy sanitization from assigning the
|
||||
* same DHCP identity to unrelated nodes.
|
||||
*/
|
||||
static inline bool build(char* dest, size_t dest_size, const char* node_name,
|
||||
const uint8_t* stable_id, size_t stable_id_size) {
|
||||
if (!dest || dest_size == 0) return false;
|
||||
dest[0] = '\0';
|
||||
|
||||
static constexpr char kPrefix[] = "meshcore-";
|
||||
static constexpr char kFallback[] = "node";
|
||||
static constexpr char kHex[] = "0123456789abcdef";
|
||||
static constexpr size_t kPrefixLength = sizeof(kPrefix) - 1;
|
||||
static constexpr size_t kSuffixLength = 7; // '-' plus six hex digits.
|
||||
|
||||
// NodePrefs::node_name currently holds at most 31 bytes. A larger scratch
|
||||
// buffer keeps this helper safe and independently testable with other input.
|
||||
char slug[64];
|
||||
size_t slug_length = 0;
|
||||
bool separator_pending = false;
|
||||
bool removed_non_ascii = false;
|
||||
if (node_name) {
|
||||
for (size_t i = 0; node_name[i] != '\0' && slug_length < sizeof(slug) - 1;
|
||||
++i) {
|
||||
const uint8_t ch = static_cast<uint8_t>(node_name[i]);
|
||||
if (isAsciiAlphaNumeric(ch)) {
|
||||
if (separator_pending && slug_length > 0 &&
|
||||
slug_length < sizeof(slug) - 1) {
|
||||
slug[slug_length++] = '-';
|
||||
}
|
||||
if (slug_length < sizeof(slug) - 1) {
|
||||
slug[slug_length++] = asciiLower(ch);
|
||||
}
|
||||
separator_pending = false;
|
||||
} else {
|
||||
if (ch >= 0x80) removed_non_ascii = true;
|
||||
if (slug_length > 0) separator_pending = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const bool used_fallback = slug_length == 0;
|
||||
if (slug_length == 0) {
|
||||
for (size_t i = 0; i < sizeof(kFallback) - 1; ++i) {
|
||||
slug[slug_length++] = kFallback[i];
|
||||
}
|
||||
}
|
||||
slug[slug_length] = '\0';
|
||||
|
||||
size_t max_length = dest_size - 1;
|
||||
if (max_length > kMaxLength) max_length = kMaxLength;
|
||||
if (max_length == 0) return false;
|
||||
|
||||
const bool needs_truncation = kPrefixLength + slug_length > max_length;
|
||||
const bool needs_identity = needs_truncation || removed_non_ascii || used_fallback;
|
||||
const bool can_add_identity = needs_identity && stable_id &&
|
||||
stable_id_size >= 3 && max_length > kPrefixLength + kSuffixLength;
|
||||
const size_t suffix_length = can_add_identity ? kSuffixLength : 0;
|
||||
const size_t prefix_length = kPrefixLength < max_length
|
||||
? kPrefixLength : max_length;
|
||||
size_t slug_budget = max_length - prefix_length - suffix_length;
|
||||
if (slug_budget > slug_length) slug_budget = slug_length;
|
||||
while (slug_budget > 0 && slug[slug_budget - 1] == '-') --slug_budget;
|
||||
|
||||
size_t out = 0;
|
||||
for (size_t i = 0; i < prefix_length; ++i) dest[out++] = kPrefix[i];
|
||||
for (size_t i = 0; i < slug_budget; ++i) dest[out++] = slug[i];
|
||||
if (can_add_identity) {
|
||||
dest[out++] = '-';
|
||||
for (size_t i = 0; i < 3; ++i) {
|
||||
dest[out++] = kHex[(stable_id[i] >> 4) & 0x0f];
|
||||
dest[out++] = kHex[stable_id[i] & 0x0f];
|
||||
}
|
||||
}
|
||||
dest[out] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace NetworkHostname
|
||||
@@ -0,0 +1,979 @@
|
||||
#include "NetworkLink.h"
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
|
||||
#include "MQTTConnectionPolicy.h"
|
||||
#include "WifiPowerSavePolicy.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <esp_netif.h>
|
||||
#include <lwip/dns.h>
|
||||
|
||||
#if defined(NETWORK_PREFER_ETHERNET)
|
||||
#include "ethernet/ch390/CH390Config.h"
|
||||
|
||||
// Arduino-ESP32's built-in ETH implementation calls this before bringing up
|
||||
// Ethernet. It creates the shared Arduino network event group/task used by
|
||||
// WiFiGenericClass::hostByName(), even when no Wi-Fi interface is started.
|
||||
// ESP32-CH390 initializes esp_netif directly and omits this Arduino layer.
|
||||
extern void tcpipInit();
|
||||
#endif
|
||||
|
||||
// Same "MQTT: " prefix as MQTT_DEBUG_PRINTLN so existing log greps keep matching.
|
||||
#if defined(MQTT_DEBUG)
|
||||
#define NETWORK_DEBUG_PRINTLN(F, ...) do { if (Serial.availableForWrite() > 0) { Serial.printf("MQTT: " F "\n", ##__VA_ARGS__); } } while (0)
|
||||
#else
|
||||
#define NETWORK_DEBUG_PRINTLN(...) do {} while (0)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
class NetworkLinkBase : public NetworkLink {
|
||||
protected:
|
||||
std::atomic<uint64_t> _outage_bits{AlertFaultPolicy::packOutageSnapshot({false, 0, 0})};
|
||||
std::atomic<unsigned long> _connected_at{0};
|
||||
std::atomic<unsigned long> _last_disconnect_time{0};
|
||||
std::atomic<uint8_t> _last_disconnect_reason{0};
|
||||
bool _status_initialized = false;
|
||||
bool _last_connected = false;
|
||||
unsigned long _last_status_check = 0;
|
||||
static constexpr int kDnsServers = 2;
|
||||
// Only ever touched on the lwIP thread (see snapshotDns()), so no atomics.
|
||||
ip_addr_t _dns_snapshot[kDnsServers] = {};
|
||||
bool _dns_captured = false;
|
||||
|
||||
AlertFaultPolicy::OutageSnapshot outage() const {
|
||||
return AlertFaultPolicy::unpackOutageSnapshot(
|
||||
_outage_bits.load(std::memory_order_acquire));
|
||||
}
|
||||
|
||||
void setOutage(AlertFaultPolicy::OutageSnapshot snapshot) {
|
||||
_outage_bits.store(AlertFaultPolicy::packOutageSnapshot(snapshot),
|
||||
std::memory_order_release);
|
||||
}
|
||||
|
||||
void noteConnected(unsigned long now_ms) {
|
||||
if (_connected_at.load(std::memory_order_relaxed) == 0) {
|
||||
_connected_at.store(now_ms, std::memory_order_relaxed);
|
||||
}
|
||||
setOutage(AlertFaultPolicy::applyWifiGotIp(outage()));
|
||||
}
|
||||
|
||||
void noteDisconnected(unsigned long now_ms, uint8_t reason) {
|
||||
_last_disconnect_reason.store(reason, std::memory_order_relaxed);
|
||||
_last_disconnect_time.store(now_ms, std::memory_order_relaxed);
|
||||
setOutage(AlertFaultPolicy::applyWifiDisconnectEvent(
|
||||
(uint32_t)now_ms, reason, outage()));
|
||||
}
|
||||
|
||||
|
||||
public:
|
||||
unsigned long connectedAtMillis() const override {
|
||||
return _connected_at.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
uint8_t lastDisconnectReason() const override {
|
||||
return _last_disconnect_reason.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
unsigned long lastDisconnectTime() const override {
|
||||
return _last_disconnect_time.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
AlertFaultPolicy::OutageSnapshot outageSnapshot() const override {
|
||||
return outage();
|
||||
}
|
||||
|
||||
private:
|
||||
// Remember the resolver this link's DHCP lease installed, so switching back
|
||||
// to it can put that resolver back.
|
||||
//
|
||||
// lwIP keeps ONE global server list, not one per interface: a DHCP lease on
|
||||
// any medium calls dns_setserver() and overwrites whatever the other medium
|
||||
// had. IDF 4.4 has no per-interface retention either — esp_netif_get_dns_info()
|
||||
// reads the same globals — so the medium that leased last owns DNS for every
|
||||
// socket. Without this, an Ethernet node that falls back to Wi-Fi and then
|
||||
// fails back keeps asking the Wi-Fi network's DNS server. When the two are on
|
||||
// different subnets that server is unreachable from Ethernet, and the node
|
||||
// reads as connected while every broker and NTP hostname fails to resolve,
|
||||
// until Ethernet's own DHCP renewal happens to fix it hours later.
|
||||
//
|
||||
// Both halves run through esp_netif_tcpip_exec() because lwIP's DNS functions
|
||||
// belong to the TCP/IP thread, and these are called from the Arduino event
|
||||
// task (Ethernet GOT_IP) and the MQTT task (Wi-Fi edge, and select()). That
|
||||
// also serializes the snapshot itself, so it needs no atomics. Neither caller
|
||||
// is the TCP/IP thread, so the call cannot deadlock on itself.
|
||||
//
|
||||
// The whole ip_addr_t is kept, not an IPv4 word: these builds compile lwIP
|
||||
// with IPv6 on, and reinterpreting a v6 server as v4 would install four
|
||||
// meaningless bytes as a resolver. (RDNSS is disabled here, so a v6 server
|
||||
// should never appear — storing the tagged value means it stays correct if
|
||||
// that ever changes.)
|
||||
static esp_err_t snapshotDnsOnTcpipThread(void* ctx) {
|
||||
NetworkLinkBase* self = static_cast<NetworkLinkBase*>(ctx);
|
||||
bool any = false;
|
||||
for (int i = 0; i < kDnsServers; i++) {
|
||||
const ip_addr_t* server = dns_getserver(i);
|
||||
self->_dns_snapshot[i] = (server != nullptr) ? *server : *IP_ADDR_ANY;
|
||||
if (!ip_addr_isany_val(self->_dns_snapshot[i])) any = true;
|
||||
}
|
||||
// A lease that carried no resolver at all (static configuration, or a
|
||||
// server that offered none) must not be remembered as "this medium's DNS is
|
||||
// nothing" — restoring that would wipe a working resolver for no gain.
|
||||
if (any) self->_dns_captured = true;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t restoreDnsOnTcpipThread(void* ctx) {
|
||||
NetworkLinkBase* self = static_cast<NetworkLinkBase*>(ctx);
|
||||
if (!self->_dns_captured) return ESP_OK;
|
||||
// Every slot is written, empty ones included: returning to a network with
|
||||
// one server must not leave the other medium's second server behind as a
|
||||
// fallback that only fails slowly.
|
||||
for (int i = 0; i < kDnsServers; i++) {
|
||||
dns_setserver(i, &self->_dns_snapshot[i]);
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
public:
|
||||
void snapshotDns() { esp_netif_tcpip_exec(snapshotDnsOnTcpipThread, this); }
|
||||
|
||||
// A medium that has never held a lease with a resolver leaves the current one
|
||||
// alone rather than blanking it.
|
||||
void restoreDns() { esp_netif_tcpip_exec(restoreDnsOnTcpipThread, this); }
|
||||
|
||||
};
|
||||
|
||||
class WiFiNetworkLink final : public NetworkLinkBase {
|
||||
bool _event_registered = false;
|
||||
char _hostname[32] = {};
|
||||
char _ssid[33] = {};
|
||||
char _password[65] = {};
|
||||
unsigned long _last_reconnect_attempt = 0;
|
||||
uint8_t _reconnect_backoff_attempt = 0;
|
||||
|
||||
// One mapping for startup, reconnect and CLI (see WifiPowerSavePolicy). The
|
||||
// stored default is `none`; `min` means MIN_MODEM here exactly as the CLI
|
||||
// says it does. Mapping the stored value locally is what let a node set to
|
||||
// `min` silently run with power save off after its first reconnect.
|
||||
void applyPowerPrefs(uint8_t wifi_power_save) {
|
||||
static_assert((int)WifiPowerSavePolicy::kModeNone == (int)WIFI_PS_NONE, "wifi_ps_type_t drift");
|
||||
static_assert((int)WifiPowerSavePolicy::kModeMinModem == (int)WIFI_PS_MIN_MODEM, "wifi_ps_type_t drift");
|
||||
static_assert((int)WifiPowerSavePolicy::kModeMaxModem == (int)WIFI_PS_MAX_MODEM, "wifi_ps_type_t drift");
|
||||
esp_wifi_set_ps((wifi_ps_type_t)WifiPowerSavePolicy::modeFor(wifi_power_save));
|
||||
// Read back rather than logging what we asked for: this is the only place
|
||||
// the mode is observable on a running node, and the setting used to change
|
||||
// meaning between the CLI and this path.
|
||||
wifi_ps_type_t applied = WIFI_PS_NONE;
|
||||
esp_wifi_get_ps(&applied);
|
||||
NETWORK_DEBUG_PRINTLN("WiFi power save: %s (mode=%d)",
|
||||
WifiPowerSavePolicy::nameFor(wifi_power_save), (int)applied);
|
||||
#ifdef MQTT_WIFI_TX_POWER
|
||||
WiFi.setTxPower(MQTT_WIFI_TX_POWER);
|
||||
#else
|
||||
WiFi.setTxPower(WIFI_POWER_11dBm);
|
||||
#endif
|
||||
}
|
||||
|
||||
public:
|
||||
const char* mediumName() const override { return "wifi"; }
|
||||
NetworkMedium medium() const override { return NetworkMedium::WiFi; }
|
||||
const char* statusName() const override {
|
||||
switch (WiFi.status()) {
|
||||
case WL_CONNECTED: return "connected";
|
||||
case WL_NO_SSID_AVAIL: return "no_ssid";
|
||||
case WL_CONNECT_FAILED: return "connect_failed";
|
||||
case WL_CONNECTION_LOST: return "connection_lost";
|
||||
case WL_DISCONNECTED: return "disconnected";
|
||||
case 255: return "not_started";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
int statusCode() const override { return (int)WiFi.status(); }
|
||||
|
||||
bool configValid(const char* wifi_ssid) const override {
|
||||
return wifi_ssid && wifi_ssid[0] != '\0';
|
||||
}
|
||||
|
||||
void setHostname(const char* hostname) override {
|
||||
strncpy(_hostname, hostname ? hostname : "", sizeof(_hostname) - 1);
|
||||
_hostname[sizeof(_hostname) - 1] = '\0';
|
||||
}
|
||||
|
||||
void updateWifiCredentials(const char* wifi_ssid, const char* wifi_password) override {
|
||||
strncpy(_ssid, wifi_ssid ? wifi_ssid : "", sizeof(_ssid) - 1);
|
||||
_ssid[sizeof(_ssid) - 1] = '\0';
|
||||
strncpy(_password, wifi_password ? wifi_password : "", sizeof(_password) - 1);
|
||||
_password[sizeof(_password) - 1] = '\0';
|
||||
}
|
||||
|
||||
bool begin(const char* wifi_ssid, const char* wifi_password) override {
|
||||
if (!configValid(wifi_ssid)) return false;
|
||||
updateWifiCredentials(wifi_ssid, wifi_password);
|
||||
|
||||
// Arduino-ESP32 applies this stored value when it creates the STA netif.
|
||||
// It must be set before WiFi.mode()/begin() for the first DHCP exchange.
|
||||
if (_hostname[0] != '\0') WiFi.setHostname(_hostname);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.setAutoReconnect(true);
|
||||
|
||||
if (!_event_registered) {
|
||||
WiFi.onEvent([this](WiFiEvent_t event, WiFiEventInfo_t info) {
|
||||
switch (event) {
|
||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
||||
NETWORK_DEBUG_PRINTLN("WiFi connected: %s",
|
||||
IPAddress(info.got_ip.ip_info.ip.addr).toString().c_str());
|
||||
noteConnected(millis());
|
||||
_reconnect_backoff_attempt = 0;
|
||||
break;
|
||||
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
||||
noteDisconnected(millis(), info.wifi_sta_disconnected.reason);
|
||||
NETWORK_DEBUG_PRINTLN("WiFi disconnected: reason %d",
|
||||
info.wifi_sta_disconnected.reason);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
_event_registered = true;
|
||||
}
|
||||
|
||||
// Preserve the existing restart behavior: MQTT stop leaves the station up,
|
||||
// and begin() must not force a disconnect that races the first DNS lookup.
|
||||
if (!isConnected()) {
|
||||
WiFi.begin(_ssid, _password);
|
||||
} else {
|
||||
noteConnected(millis());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
NetworkTransition maintain(uint32_t now_ms, uint8_t wifi_power_save) override {
|
||||
const bool connected = isConnected();
|
||||
if (connected && connectedAtMillis() == 0) noteConnected(now_ms);
|
||||
|
||||
if (!_status_initialized) {
|
||||
_last_connected = connected;
|
||||
_status_initialized = true;
|
||||
setOutage(AlertFaultPolicy::applyWifiStatus(
|
||||
now_ms, connected, outage(), false));
|
||||
// Already associated when the link started (end()/begin() leaves STA up):
|
||||
// there is no connect transition below to carry the setting, so apply it
|
||||
// here or the node keeps running whatever mode was set before.
|
||||
if (connected) {
|
||||
applyPowerPrefs(wifi_power_save);
|
||||
snapshotDns();
|
||||
}
|
||||
}
|
||||
|
||||
if ((uint32_t)(now_ms - _last_status_check) <= 10000) {
|
||||
if (connected && outage().down) noteConnected(now_ms);
|
||||
return NetworkTransition::None;
|
||||
}
|
||||
_last_status_check = now_ms;
|
||||
|
||||
if (connected) {
|
||||
const bool transitioned = !_last_connected;
|
||||
if (transitioned) {
|
||||
setOutage(AlertFaultPolicy::applyWifiStatus(
|
||||
now_ms, true, outage(), true));
|
||||
_connected_at.store(now_ms, std::memory_order_relaxed);
|
||||
_reconnect_backoff_attempt = 0;
|
||||
applyPowerPrefs(wifi_power_save);
|
||||
snapshotDns();
|
||||
}
|
||||
_last_connected = true;
|
||||
return transitioned ? NetworkTransition::Up : NetworkTransition::None;
|
||||
}
|
||||
|
||||
AlertFaultPolicy::OutageSnapshot snapshot = AlertFaultPolicy::applyWifiStatus(
|
||||
now_ms, false, outage(), true);
|
||||
setOutage(snapshot);
|
||||
const bool transitioned = _last_connected;
|
||||
if (transitioned) {
|
||||
_connected_at.store(0, std::memory_order_relaxed);
|
||||
} else if (snapshot.down && _ssid[0] != '\0' && MQTTConnectionPolicy::wifiReconnectDue(
|
||||
now_ms, snapshot.started_ms, (uint32_t)_last_reconnect_attempt,
|
||||
_reconnect_backoff_attempt)) {
|
||||
_last_reconnect_attempt = now_ms;
|
||||
_reconnect_backoff_attempt =
|
||||
MQTTConnectionPolicy::nextWifiBackoffAttempt(_reconnect_backoff_attempt);
|
||||
WiFi.disconnect();
|
||||
WiFi.begin(_ssid, _password);
|
||||
}
|
||||
_last_connected = false;
|
||||
return transitioned ? NetworkTransition::Down : NetworkTransition::None;
|
||||
}
|
||||
|
||||
bool isConnected() const override { return WiFi.status() == WL_CONNECTED; }
|
||||
IPAddress localIP() const override { return WiFi.localIP(); }
|
||||
int rssi() const override { return isConnected() ? WiFi.RSSI() : INT_MIN; }
|
||||
bool resolveHost(const char* hostname, IPAddress& address) const override {
|
||||
return WiFi.hostByName(hostname, address);
|
||||
}
|
||||
void formatDiagnostics(char* reply, size_t reply_size) const override {
|
||||
snprintf(reply, reply_size,
|
||||
"> why:ethernet-not-enabled selected:wifi\n"
|
||||
"wifi:state:%s ip:%s",
|
||||
statusName(),
|
||||
localIP().toString().c_str());
|
||||
}
|
||||
};
|
||||
|
||||
#if defined(NETWORK_PREFER_ETHERNET)
|
||||
class EthernetNetworkLink final : public NetworkLinkBase {
|
||||
public:
|
||||
enum class EventState : uint8_t {
|
||||
None,
|
||||
Started,
|
||||
LinkDown,
|
||||
LinkUp,
|
||||
GotIp,
|
||||
Stopped,
|
||||
};
|
||||
|
||||
private:
|
||||
std::atomic<bool> _started{false};
|
||||
bool _event_registered = false;
|
||||
char _hostname[32] = {};
|
||||
std::atomic<uint8_t> _event_state{static_cast<uint8_t>(EventState::None)};
|
||||
|
||||
public:
|
||||
const char* mediumName() const override { return "ethernet"; }
|
||||
NetworkMedium medium() const override { return NetworkMedium::Ethernet; }
|
||||
const char* statusName() const override {
|
||||
return isConnected() ? "connected" : "disconnected";
|
||||
}
|
||||
int statusCode() const override { return isConnected() ? 1 : 0; }
|
||||
bool configValid(const char*) const override { return true; }
|
||||
|
||||
void setHostname(const char* hostname) override {
|
||||
strncpy(_hostname, hostname ? hostname : "", sizeof(_hostname) - 1);
|
||||
_hostname[sizeof(_hostname) - 1] = '\0';
|
||||
}
|
||||
|
||||
bool begin(const char*, const char*) override {
|
||||
if (_started.load(std::memory_order_acquire)) return true;
|
||||
// DNS and WiFiClientSecure are transport-neutral sockets in this Arduino
|
||||
// core, but their hostname path still uses WiFiGeneric's event group.
|
||||
// Initialize that shared runtime without enabling or associating Wi-Fi.
|
||||
tcpipInit();
|
||||
if (!_event_registered) {
|
||||
WiFi.onEvent([this](WiFiEvent_t event, WiFiEventInfo_t) {
|
||||
switch (event) {
|
||||
case ARDUINO_EVENT_ETH_START:
|
||||
_event_state.store(static_cast<uint8_t>(EventState::Started),
|
||||
std::memory_order_relaxed);
|
||||
break;
|
||||
case ARDUINO_EVENT_ETH_CONNECTED:
|
||||
_event_state.store(static_cast<uint8_t>(EventState::LinkUp),
|
||||
std::memory_order_relaxed);
|
||||
break;
|
||||
case ARDUINO_EVENT_ETH_GOT_IP:
|
||||
_event_state.store(static_cast<uint8_t>(EventState::GotIp),
|
||||
std::memory_order_relaxed);
|
||||
noteConnected(millis());
|
||||
// Taken here rather than at the maintain() edge: this is the moment
|
||||
// the lease installed the resolver, before a Wi-Fi fallback lease
|
||||
// can overwrite it.
|
||||
snapshotDns();
|
||||
break;
|
||||
case ARDUINO_EVENT_ETH_DISCONNECTED:
|
||||
_event_state.store(static_cast<uint8_t>(EventState::LinkDown),
|
||||
std::memory_order_relaxed);
|
||||
// Ethernet has no 802.11 reason code; zero means unavailable.
|
||||
noteDisconnected(millis(), 0);
|
||||
_connected_at.store(0, std::memory_order_relaxed);
|
||||
break;
|
||||
case ARDUINO_EVENT_ETH_STOP:
|
||||
_event_state.store(static_cast<uint8_t>(EventState::Stopped),
|
||||
std::memory_order_relaxed);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
_event_registered = true;
|
||||
}
|
||||
_event_state.store(static_cast<uint8_t>(EventState::None),
|
||||
std::memory_order_relaxed);
|
||||
const bool started = beginConfiguredCH390(_hostname);
|
||||
_started.store(started, std::memory_order_release);
|
||||
if (started && isConnected()) noteConnected(millis());
|
||||
return started;
|
||||
}
|
||||
|
||||
bool restart() {
|
||||
CH390.end();
|
||||
_started.store(false, std::memory_order_release);
|
||||
// Preserve status/outage history across attempts. maintain() observes the
|
||||
// resulting edge in this same task iteration, so a retry cannot reset a
|
||||
// prolonged-down alert timer or hide a previously connected transition.
|
||||
return begin(nullptr, nullptr);
|
||||
}
|
||||
|
||||
NetworkTransition maintain(uint32_t now_ms, uint8_t) override {
|
||||
const bool connected = isConnected();
|
||||
if (!_status_initialized) {
|
||||
_last_connected = connected;
|
||||
_status_initialized = true;
|
||||
setOutage(AlertFaultPolicy::applyWifiStatus(
|
||||
now_ms, connected, outage(), false));
|
||||
if (connected) {
|
||||
noteConnected(now_ms);
|
||||
snapshotDns();
|
||||
}
|
||||
return NetworkTransition::None;
|
||||
}
|
||||
|
||||
if (connected == _last_connected) {
|
||||
if (connected && outage().down) noteConnected(now_ms);
|
||||
return NetworkTransition::None;
|
||||
}
|
||||
|
||||
_last_connected = connected;
|
||||
if (connected) {
|
||||
_connected_at.store(now_ms, std::memory_order_relaxed);
|
||||
setOutage(AlertFaultPolicy::applyWifiStatus(
|
||||
now_ms, true, outage(), true));
|
||||
snapshotDns();
|
||||
return NetworkTransition::Up;
|
||||
}
|
||||
|
||||
const bool outage_was_down = outage().down;
|
||||
_connected_at.store(0, std::memory_order_relaxed);
|
||||
AlertFaultPolicy::OutageSnapshot snapshot = AlertFaultPolicy::applyWifiStatus(
|
||||
now_ms, false, outage(), true);
|
||||
setOutage(snapshot);
|
||||
if (!outage_was_down) {
|
||||
_last_disconnect_time.store(now_ms, std::memory_order_relaxed);
|
||||
}
|
||||
return NetworkTransition::Down;
|
||||
}
|
||||
|
||||
bool isConnected() const override {
|
||||
return _started.load(std::memory_order_acquire) && CH390.isConnected();
|
||||
}
|
||||
IPAddress localIP() const override { return CH390.localIP(); }
|
||||
int rssi() const override { return INT_MIN; }
|
||||
bool resolveHost(const char* hostname, IPAddress& address) const override {
|
||||
// Arduino's hostByName is a thin wrapper over the process-wide lwIP resolver;
|
||||
// DNS follows the selected esp_netif even though this entry point is named WiFi.
|
||||
return WiFi.hostByName(hostname, address);
|
||||
}
|
||||
void formatDiagnostics(char* reply, size_t reply_size) const override {
|
||||
snprintf(reply, reply_size, "> ethernet:%s ip=%s",
|
||||
statusName(), localIP().toString().c_str());
|
||||
}
|
||||
|
||||
EventState eventState() const {
|
||||
return static_cast<EventState>(
|
||||
_event_state.load(std::memory_order_relaxed));
|
||||
}
|
||||
bool started() const { return _started.load(std::memory_order_acquire); }
|
||||
bool sampleLink(bool& known) const {
|
||||
known = false;
|
||||
if (!_started.load(std::memory_order_acquire)) return false;
|
||||
|
||||
// IEEE 802.3 BMSR link status is latch-low. Read it twice so the second
|
||||
// value is the current carrier state rather than a remembered link flap.
|
||||
(void)CH390.readPHY(0x01);
|
||||
const uint32_t bmsr = CH390.readPHY(0x01) & 0xffffu;
|
||||
if (bmsr != 0 && bmsr != 0xffffu) {
|
||||
known = true;
|
||||
return (bmsr & (1u << 2)) != 0;
|
||||
}
|
||||
|
||||
// A failed/unsupported direct PHY read can still use the driver's events.
|
||||
const EventState state = eventState();
|
||||
known = state == EventState::LinkDown || state == EventState::LinkUp ||
|
||||
state == EventState::GotIp || state == EventState::Stopped;
|
||||
return state == EventState::LinkUp || state == EventState::GotIp;
|
||||
}
|
||||
bool linkUp() const {
|
||||
bool known = false;
|
||||
return sampleLink(known);
|
||||
}
|
||||
const char* eventName() const {
|
||||
switch (eventState()) {
|
||||
case EventState::None: return "none";
|
||||
case EventState::Started: return "started";
|
||||
case EventState::LinkDown: return "link-down";
|
||||
case EventState::LinkUp: return "link-up";
|
||||
case EventState::GotIp: return "got-ip";
|
||||
case EventState::Stopped: return "stopped";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
class AutomaticNetworkLink final : public NetworkLink {
|
||||
EthernetNetworkLink _ethernet;
|
||||
WiFiNetworkLink _wifi;
|
||||
std::atomic<NetworkMedium> _selected{NetworkMedium::None};
|
||||
std::atomic<bool> _ethernet_started{false};
|
||||
std::atomic<bool> _wifi_started{false};
|
||||
char _wifi_ssid[33] = {};
|
||||
char _wifi_password[65] = {};
|
||||
std::atomic<uint32_t> _ethernet_stable_since{0};
|
||||
std::atomic<uint32_t> _selected_down_since{0};
|
||||
std::atomic<uint32_t> _last_ethernet_init_attempt{0};
|
||||
std::atomic<uint8_t> _ethernet_retry_attempt{0};
|
||||
std::atomic<uint32_t> _ethernet_no_ip_since{0};
|
||||
std::atomic<uint8_t> _switch_locks{0};
|
||||
std::atomic<bool> _switch_in_progress{false};
|
||||
std::atomic<bool> _ethernet_seen{false}; // held a lease at least once this boot
|
||||
|
||||
// Ethernet is the primary for alerts once it has carried traffic, or when it
|
||||
// is the only configured medium; a Wi-Fi-only install keeps Wi-Fi alerts.
|
||||
bool ethernetIsAlertPrimary() const {
|
||||
return _ethernet_seen.load(std::memory_order_acquire) || !wifiConfigured();
|
||||
}
|
||||
|
||||
NetworkLink& selectedInterface(NetworkMedium selected) {
|
||||
return selected == NetworkMedium::Ethernet
|
||||
? static_cast<NetworkLink&>(_ethernet)
|
||||
: static_cast<NetworkLink&>(_wifi);
|
||||
}
|
||||
const NetworkLink& selectedInterface(NetworkMedium selected) const {
|
||||
return selected == NetworkMedium::Ethernet
|
||||
? static_cast<const NetworkLink&>(_ethernet)
|
||||
: static_cast<const NetworkLink&>(_wifi);
|
||||
}
|
||||
|
||||
bool wifiConfigured() const { return _wifi_ssid[0] != '\0'; }
|
||||
|
||||
void rememberWifi(const char* ssid, const char* password) {
|
||||
strncpy(_wifi_ssid, ssid ? ssid : "", sizeof(_wifi_ssid) - 1);
|
||||
_wifi_ssid[sizeof(_wifi_ssid) - 1] = '\0';
|
||||
strncpy(_wifi_password, password ? password : "", sizeof(_wifi_password) - 1);
|
||||
_wifi_password[sizeof(_wifi_password) - 1] = '\0';
|
||||
}
|
||||
|
||||
void startWifiFallback() {
|
||||
if (_wifi_started.load(std::memory_order_acquire) || !wifiConfigured()) return;
|
||||
_wifi_started.store(_wifi.begin(_wifi_ssid, _wifi_password),
|
||||
std::memory_order_release);
|
||||
}
|
||||
|
||||
// Lock and mutation each publish one flag then read the other; seq_cst keeps
|
||||
// both sides from missing each other.
|
||||
bool beginUnlockedMutation() {
|
||||
bool expected = false;
|
||||
if (!_switch_in_progress.compare_exchange_strong(expected, true)) {
|
||||
return false;
|
||||
}
|
||||
if (_switch_locks.load() != 0) {
|
||||
_switch_in_progress.store(false, std::memory_order_release);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void endUnlockedMutation() {
|
||||
_switch_in_progress.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
bool selectIfUnlocked(NetworkMedium medium) {
|
||||
if (!beginUnlockedMutation()) return false;
|
||||
select(medium);
|
||||
endUnlockedMutation();
|
||||
return true;
|
||||
}
|
||||
|
||||
void startWifiFallbackIfUnlocked() {
|
||||
if (!beginUnlockedMutation()) return;
|
||||
startWifiFallback();
|
||||
endUnlockedMutation();
|
||||
}
|
||||
|
||||
void select(NetworkMedium medium) {
|
||||
if (medium == NetworkMedium::Ethernet) {
|
||||
// ESP-IDF gives Wi-Fi a higher default-route priority than Ethernet.
|
||||
// Keep only the selected STA associated so sockets cannot silently stay
|
||||
// on Wi-Fi after the manager has declared Ethernet active.
|
||||
WiFi.setAutoReconnect(false);
|
||||
WiFi.disconnect(false, false);
|
||||
_wifi_started.store(false, std::memory_order_release);
|
||||
}
|
||||
_selected_down_since.store(0, std::memory_order_relaxed);
|
||||
_selected.store(medium, std::memory_order_release);
|
||||
// Put back the resolver this medium leased. lwIP's server list is global,
|
||||
// so whichever medium leased last still owns it here (see snapshotDns()).
|
||||
if (medium == NetworkMedium::Ethernet) {
|
||||
_ethernet.restoreDns();
|
||||
} else if (medium == NetworkMedium::WiFi) {
|
||||
_wifi.restoreDns();
|
||||
}
|
||||
}
|
||||
|
||||
bool startOrRetryEthernet(uint32_t now_ms, bool restart) {
|
||||
const bool started = restart ? _ethernet.restart()
|
||||
: _ethernet.begin(nullptr, nullptr);
|
||||
_last_ethernet_init_attempt.store(now_ms, std::memory_order_relaxed);
|
||||
_ethernet_started.store(started, std::memory_order_release);
|
||||
if (started) {
|
||||
_ethernet_retry_attempt.store(0, std::memory_order_relaxed);
|
||||
} else {
|
||||
uint8_t attempt = _ethernet_retry_attempt.load(std::memory_order_relaxed);
|
||||
if (attempt != UINT8_MAX) ++attempt;
|
||||
_ethernet_retry_attempt.store(attempt, std::memory_order_relaxed);
|
||||
}
|
||||
return started;
|
||||
}
|
||||
|
||||
public:
|
||||
const char* mediumName() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
if (selected == NetworkMedium::Ethernet) return "ethernet";
|
||||
if (selected == NetworkMedium::WiFi) return "wifi";
|
||||
return "none";
|
||||
}
|
||||
NetworkMedium medium() const override {
|
||||
return _selected.load(std::memory_order_acquire);
|
||||
}
|
||||
const char* statusName() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None ? "not_selected"
|
||||
: selectedInterface(selected).statusName();
|
||||
}
|
||||
int statusCode() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None ? 0
|
||||
: selectedInterface(selected).statusCode();
|
||||
}
|
||||
bool configValid(const char* wifi_ssid) const override {
|
||||
// Hardware availability and stored credentials are configuration. Current
|
||||
// link/DHCP state is runtime state and must not permanently suppress the
|
||||
// MQTT task that monitors for a late cable or lease.
|
||||
(void)wifi_ssid;
|
||||
return true;
|
||||
}
|
||||
bool isAutomatic() const override { return true; }
|
||||
|
||||
void updateWifiCredentials(const char* wifi_ssid, const char* wifi_password) override {
|
||||
rememberWifi(wifi_ssid, wifi_password);
|
||||
_wifi.updateWifiCredentials(_wifi_ssid, _wifi_password);
|
||||
}
|
||||
|
||||
void setHostname(const char* hostname) override {
|
||||
// Whichever medium wins now or during a later failover presents the same
|
||||
// stable DHCP identity to the LAN.
|
||||
_ethernet.setHostname(hostname);
|
||||
_wifi.setHostname(hostname);
|
||||
}
|
||||
|
||||
bool begin(const char* wifi_ssid, const char* wifi_password) override {
|
||||
rememberWifi(wifi_ssid, wifi_password);
|
||||
if (!_ethernet_started.load(std::memory_order_acquire)) {
|
||||
const uint32_t now_ms = millis();
|
||||
const uint8_t attempt =
|
||||
_ethernet_retry_attempt.load(std::memory_order_relaxed);
|
||||
if (NetworkPolicy::ethernetInitRetryDue(
|
||||
attempt, now_ms,
|
||||
_last_ethernet_init_attempt.load(std::memory_order_relaxed)) &&
|
||||
beginUnlockedMutation()) {
|
||||
startOrRetryEthernet(now_ms, attempt != 0);
|
||||
endUnlockedMutation();
|
||||
}
|
||||
}
|
||||
// bootstrap() owns the initial choice. MQTT begin() is intentionally
|
||||
// idempotent and cannot demote a boot-selected Ethernet link because of a
|
||||
// momentary status sample between tasks.
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
if (selected == NetworkMedium::None) {
|
||||
if (_ethernet.isConnected()) {
|
||||
select(NetworkMedium::Ethernet);
|
||||
} else if (wifiConfigured()) {
|
||||
startWifiFallback();
|
||||
_selected.store(NetworkMedium::WiFi, std::memory_order_release);
|
||||
}
|
||||
} else if (selected == NetworkMedium::WiFi) {
|
||||
startWifiFallback();
|
||||
}
|
||||
return _ethernet_started.load(std::memory_order_acquire) ||
|
||||
_wifi_started.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
bool bootstrap(const char* wifi_ssid, const char* wifi_password,
|
||||
uint32_t wait_ms) override {
|
||||
rememberWifi(wifi_ssid, wifi_password);
|
||||
if (!_ethernet_started.load(std::memory_order_acquire)) {
|
||||
startOrRetryEthernet(millis(), false);
|
||||
}
|
||||
|
||||
const uint32_t started_at = millis();
|
||||
for (;;) {
|
||||
bool link_known = false;
|
||||
const bool link_up = _ethernet.sampleLink(link_known);
|
||||
if (!NetworkPolicy::ethernetBootProbePending(
|
||||
_ethernet_started.load(std::memory_order_acquire),
|
||||
_ethernet.isConnected(), link_known, link_up,
|
||||
(uint32_t)(millis() - started_at), wait_ms)) {
|
||||
break;
|
||||
}
|
||||
delay(25);
|
||||
}
|
||||
|
||||
if (_ethernet.isConnected()) _ethernet_seen.store(true, std::memory_order_release);
|
||||
const NetworkMedium initial = NetworkPolicy::bootSelection(
|
||||
_ethernet.isConnected(), wifiConfigured());
|
||||
if (initial == NetworkMedium::Ethernet) {
|
||||
select(initial);
|
||||
} else {
|
||||
startWifiFallback();
|
||||
_selected.store(initial, std::memory_order_release);
|
||||
}
|
||||
return initial != NetworkMedium::None;
|
||||
}
|
||||
|
||||
NetworkTransition maintain(uint32_t now_ms, uint8_t wifi_power_save) override {
|
||||
bool ethernet_started = _ethernet_started.load(std::memory_order_acquire);
|
||||
const bool switching_locked =
|
||||
_switch_locks.load(std::memory_order_acquire) != 0;
|
||||
const bool ethernet_stopped =
|
||||
ethernet_started &&
|
||||
_ethernet.eventState() == EthernetNetworkLink::EventState::Stopped;
|
||||
if (ethernet_stopped) {
|
||||
_ethernet_started.store(false, std::memory_order_release);
|
||||
ethernet_started = false;
|
||||
if (_ethernet_retry_attempt.load(std::memory_order_relaxed) == 0) {
|
||||
_ethernet_retry_attempt.store(1, std::memory_order_relaxed);
|
||||
_last_ethernet_init_attempt.store(now_ms, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
const EthernetNetworkLink::EventState ethernet_event =
|
||||
_ethernet.eventState();
|
||||
const bool ethernet_link_up =
|
||||
ethernet_event == EthernetNetworkLink::EventState::LinkUp ||
|
||||
ethernet_event == EthernetNetworkLink::EventState::GotIp;
|
||||
if (ethernet_started && ethernet_link_up && !_ethernet.isConnected()) {
|
||||
if (_ethernet_no_ip_since.load(std::memory_order_relaxed) == 0) {
|
||||
uint32_t started_at = now_ms;
|
||||
if (started_at == 0) started_at = 1;
|
||||
_ethernet_no_ip_since.store(started_at, std::memory_order_relaxed);
|
||||
}
|
||||
} else {
|
||||
_ethernet_no_ip_since.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
// Restarts rebuild the CH390 netif, so they take the same mutation gate as
|
||||
// a route switch: an OTA/WebConfig lock taken after the sample above wins.
|
||||
if (!switching_locked && NetworkPolicy::ethernetNoIpRecoveryDue(
|
||||
ethernet_started, ethernet_link_up, _ethernet.isConnected(),
|
||||
now_ms, _ethernet_no_ip_since.load(std::memory_order_relaxed)) &&
|
||||
beginUnlockedMutation()) {
|
||||
ethernet_started = startOrRetryEthernet(now_ms, true);
|
||||
_ethernet_no_ip_since.store(0, std::memory_order_relaxed);
|
||||
endUnlockedMutation();
|
||||
}
|
||||
if (!ethernet_started && !switching_locked) {
|
||||
const uint8_t attempt =
|
||||
_ethernet_retry_attempt.load(std::memory_order_relaxed);
|
||||
if (NetworkPolicy::ethernetInitRetryDue(
|
||||
attempt, now_ms,
|
||||
_last_ethernet_init_attempt.load(std::memory_order_relaxed)) &&
|
||||
beginUnlockedMutation()) {
|
||||
ethernet_started = startOrRetryEthernet(now_ms, true);
|
||||
endUnlockedMutation();
|
||||
}
|
||||
}
|
||||
|
||||
const NetworkTransition ethernet_transition =
|
||||
_ethernet.maintain(now_ms, wifi_power_save);
|
||||
if (_ethernet.isConnected()) _ethernet_seen.store(true, std::memory_order_release);
|
||||
const bool wifi_started = _wifi_started.load(std::memory_order_acquire);
|
||||
const NetworkTransition wifi_transition = wifi_started
|
||||
? _wifi.maintain(now_ms, wifi_power_save)
|
||||
: NetworkTransition::None;
|
||||
|
||||
// Ethernet may recover while a Wi-Fi fallback is still associating. In
|
||||
// that sequence the selected enum never changes, but Wi-Fi would win
|
||||
// ESP-IDF's default-route priority once it came up. Tear the unused STA
|
||||
// down even without a selection edge, and force MQTT to reconnect if it
|
||||
// had already become reachable.
|
||||
NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
if (selected == NetworkMedium::Ethernet && _ethernet.isConnected() &&
|
||||
wifi_started) {
|
||||
const bool wifi_had_route = _wifi.isConnected();
|
||||
if (selectIfUnlocked(NetworkMedium::Ethernet) && wifi_had_route) {
|
||||
return NetworkTransition::Switched;
|
||||
}
|
||||
}
|
||||
|
||||
if (_ethernet.isConnected()) {
|
||||
if (_ethernet_stable_since.load(std::memory_order_relaxed) == 0) {
|
||||
_ethernet_stable_since.store(now_ms, std::memory_order_relaxed);
|
||||
}
|
||||
} else {
|
||||
_ethernet_stable_since.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
const bool selected_connected = isConnected();
|
||||
if (!selected_connected) {
|
||||
if (_selected_down_since.load(std::memory_order_relaxed) == 0) {
|
||||
_selected_down_since.store(now_ms, std::memory_order_relaxed);
|
||||
}
|
||||
} else {
|
||||
_selected_down_since.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
const uint32_t selected_down_since =
|
||||
_selected_down_since.load(std::memory_order_relaxed);
|
||||
const uint32_t selected_down_ms = selected_down_since == 0
|
||||
? 0 : (uint32_t)(now_ms - selected_down_since);
|
||||
selected = _selected.load(std::memory_order_acquire);
|
||||
if (selected == NetworkMedium::Ethernet && !_ethernet.isConnected() &&
|
||||
selected_down_ms >= NetworkPolicy::kEthernetDownGraceMs) {
|
||||
startWifiFallbackIfUnlocked();
|
||||
}
|
||||
|
||||
const uint32_t ethernet_stable_since =
|
||||
_ethernet_stable_since.load(std::memory_order_relaxed);
|
||||
const uint32_t ethernet_stable_ms = ethernet_stable_since == 0
|
||||
? 0 : (uint32_t)(now_ms - ethernet_stable_since);
|
||||
const bool selection_locked =
|
||||
_switch_locks.load(std::memory_order_acquire) != 0;
|
||||
const NetworkPolicy::AutomaticSelectionInput input = {
|
||||
selected, _ethernet.isConnected(),
|
||||
_wifi_started.load(std::memory_order_acquire) && _wifi.isConnected(),
|
||||
wifiConfigured(), selection_locked,
|
||||
ethernet_stable_ms, selected_down_ms};
|
||||
const NetworkMedium next = NetworkPolicy::automaticSelection(input);
|
||||
|
||||
if (next != selected) {
|
||||
if (selectIfUnlocked(next)) {
|
||||
return selected == NetworkMedium::None ? NetworkTransition::Up
|
||||
: NetworkTransition::Switched;
|
||||
}
|
||||
}
|
||||
|
||||
if (selected == NetworkMedium::Ethernet) return ethernet_transition;
|
||||
if (selected == NetworkMedium::WiFi) return wifi_transition;
|
||||
return NetworkTransition::None;
|
||||
}
|
||||
|
||||
void lockSwitching() override {
|
||||
uint8_t value = _switch_locks.load(std::memory_order_relaxed);
|
||||
while (value != UINT8_MAX && !_switch_locks.compare_exchange_weak(
|
||||
value, static_cast<uint8_t>(value + 1))) {}
|
||||
while (_switch_in_progress.load()) delay(1);
|
||||
}
|
||||
void unlockSwitching() override {
|
||||
uint8_t value = _switch_locks.load(std::memory_order_relaxed);
|
||||
while (value != 0 && !_switch_locks.compare_exchange_weak(
|
||||
value, static_cast<uint8_t>(value - 1),
|
||||
std::memory_order_relaxed, std::memory_order_relaxed)) {}
|
||||
}
|
||||
|
||||
bool isConnected() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected != NetworkMedium::None &&
|
||||
selectedInterface(selected).isConnected();
|
||||
}
|
||||
IPAddress localIP() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None ? IPAddress()
|
||||
: selectedInterface(selected).localIP();
|
||||
}
|
||||
int rssi() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None ? INT_MIN
|
||||
: selectedInterface(selected).rssi();
|
||||
}
|
||||
bool resolveHost(const char* hostname, IPAddress& address) const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected != NetworkMedium::None &&
|
||||
selectedInterface(selected).resolveHost(hostname, address);
|
||||
}
|
||||
void formatDiagnostics(char* reply, size_t reply_size) const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
const bool ethernet_started =
|
||||
_ethernet_started.load(std::memory_order_acquire);
|
||||
const bool wifi_started = _wifi_started.load(std::memory_order_acquire);
|
||||
const bool ethernet_connected = _ethernet.isConnected();
|
||||
bool ethernet_link_known = false;
|
||||
bool ethernet_link_up = _ethernet.sampleLink(ethernet_link_known);
|
||||
ethernet_link_known = ethernet_link_known || ethernet_connected;
|
||||
ethernet_link_up = ethernet_link_up || ethernet_connected;
|
||||
const bool switching_locked =
|
||||
_switch_locks.load(std::memory_order_acquire) != 0;
|
||||
const uint32_t now_ms = millis();
|
||||
const uint32_t ethernet_stable_since =
|
||||
_ethernet_stable_since.load(std::memory_order_relaxed);
|
||||
const uint32_t ethernet_stable_ms = ethernet_stable_since == 0
|
||||
? 0 : (uint32_t)(now_ms - ethernet_stable_since);
|
||||
const uint8_t retry_attempt =
|
||||
_ethernet_retry_attempt.load(std::memory_order_relaxed);
|
||||
const uint32_t retry_delay =
|
||||
NetworkPolicy::ethernetInitRetryDelayMs(retry_attempt);
|
||||
const uint32_t since_attempt = (uint32_t)(
|
||||
now_ms - _last_ethernet_init_attempt.load(std::memory_order_relaxed));
|
||||
const uint32_t retry_in = !ethernet_started && retry_delay > since_attempt
|
||||
? retry_delay - since_attempt : 0;
|
||||
const NetworkDiagnosticReason reason =
|
||||
NetworkPolicy::automaticDiagnosticReason(
|
||||
ethernet_started, ethernet_link_known, ethernet_link_up,
|
||||
ethernet_connected, selected, switching_locked,
|
||||
ethernet_stable_ms);
|
||||
snprintf(reply, reply_size,
|
||||
"> why:%s selected:%s lock:%s\n"
|
||||
"eth:init:%s retry:%u/%lums evt:%s link:%s ip:%s\n"
|
||||
"wifi:cfg:%s started:%s link:%s",
|
||||
NetworkPolicy::diagnosticReasonName(reason),
|
||||
NetworkPolicy::mediumName(selected),
|
||||
switching_locked ? "yes" : "no",
|
||||
ethernet_started ? "ok" : "failed", retry_attempt,
|
||||
(unsigned long)retry_in, _ethernet.eventName(),
|
||||
ethernet_link_known ? (ethernet_link_up ? "up" : "down")
|
||||
: "unknown",
|
||||
_ethernet.localIP().toString().c_str(),
|
||||
wifiConfigured() ? "yes" : "no", wifi_started ? "yes" : "no",
|
||||
(wifi_started && _wifi.isConnected()) ? "up" : "down");
|
||||
}
|
||||
unsigned long connectedAtMillis() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None
|
||||
? 0 : selectedInterface(selected).connectedAtMillis();
|
||||
}
|
||||
uint8_t lastDisconnectReason() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None
|
||||
? 0 : selectedInterface(selected).lastDisconnectReason();
|
||||
}
|
||||
unsigned long lastDisconnectTime() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None
|
||||
? 0 : selectedInterface(selected).lastDisconnectTime();
|
||||
}
|
||||
AlertFaultPolicy::OutageSnapshot outageSnapshot() const override {
|
||||
const NetworkMedium selected = _selected.load(std::memory_order_acquire);
|
||||
return selected == NetworkMedium::None
|
||||
? AlertFaultPolicy::OutageSnapshot{false, 0, 0}
|
||||
: selectedInterface(selected).outageSnapshot();
|
||||
}
|
||||
NetworkMedium alertMedium() const override {
|
||||
return ethernetIsAlertPrimary() ? NetworkMedium::Ethernet : NetworkMedium::WiFi;
|
||||
}
|
||||
AlertFaultPolicy::OutageSnapshot alertOutageSnapshot() const override {
|
||||
return ethernetIsAlertPrimary() ? _ethernet.outageSnapshot() : _wifi.outageSnapshot();
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
NetworkLink& activeNetworkLink() {
|
||||
#if defined(NETWORK_PREFER_ETHERNET)
|
||||
static AutomaticNetworkLink network;
|
||||
#else
|
||||
static WiFiNetworkLink network;
|
||||
#endif
|
||||
return network;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include "NetworkPolicy.h"
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <IPAddress.h>
|
||||
#include "AlertFaultPolicy.h"
|
||||
|
||||
#ifndef NETWORK_ETHERNET_BOOT_WAIT_MS
|
||||
#define NETWORK_ETHERNET_BOOT_WAIT_MS 8000UL
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Physical network selected for IP-based services.
|
||||
*
|
||||
* The interface owns link bring-up and medium-specific maintenance. MQTT, NTP,
|
||||
* OTA, and other socket users only consume connectivity and addressing. Normal
|
||||
* MQTT shutdown deliberately does not stop this interface because an OTA
|
||||
* download runs after the broker clients have been released.
|
||||
*/
|
||||
class NetworkLink {
|
||||
public:
|
||||
virtual ~NetworkLink() = default;
|
||||
|
||||
virtual const char* mediumName() const = 0;
|
||||
virtual NetworkMedium medium() const = 0;
|
||||
virtual const char* statusName() const = 0;
|
||||
virtual int statusCode() const = 0;
|
||||
virtual bool configValid(const char* wifi_ssid) const = 0;
|
||||
// Configure the DHCP hostname before begin()/bootstrap(). Implementations
|
||||
// retain it for any later fallback interface start.
|
||||
virtual void setHostname(const char* hostname) = 0;
|
||||
virtual bool begin(const char* wifi_ssid, const char* wifi_password) = 0;
|
||||
// Latest stored credentials; the next reconnect attempt uses them without a reboot.
|
||||
virtual void updateWifiCredentials(const char* wifi_ssid, const char* wifi_password) {
|
||||
(void)wifi_ssid;
|
||||
(void)wifi_password;
|
||||
}
|
||||
virtual NetworkTransition maintain(uint32_t now_ms, uint8_t wifi_power_save) = 0;
|
||||
|
||||
// Automatic selectors are boot-owned so first-run services can use the
|
||||
// chosen link before MQTT starts. Compatibility Wi-Fi builds keep the
|
||||
// original MQTT-task-owned begin() path.
|
||||
virtual bool isAutomatic() const { return false; }
|
||||
virtual bool bootstrap(const char* wifi_ssid, const char* wifi_password,
|
||||
uint32_t wait_ms) {
|
||||
(void)wait_ms;
|
||||
return begin(wifi_ssid, wifi_password);
|
||||
}
|
||||
|
||||
// WebConfig and OTA pin the current route for the lifetime of their session.
|
||||
virtual void lockSwitching() {}
|
||||
virtual void unlockSwitching() {}
|
||||
|
||||
virtual bool isConnected() const = 0;
|
||||
virtual IPAddress localIP() const = 0;
|
||||
virtual int rssi() const = 0; // INT_MIN when the selected medium has no RSSI.
|
||||
virtual bool resolveHost(const char* hostname, IPAddress& address) const = 0;
|
||||
virtual void formatDiagnostics(char* reply, size_t reply_size) const = 0;
|
||||
|
||||
virtual unsigned long connectedAtMillis() const = 0;
|
||||
virtual uint8_t lastDisconnectReason() const = 0;
|
||||
virtual unsigned long lastDisconnectTime() const = 0;
|
||||
virtual AlertFaultPolicy::OutageSnapshot outageSnapshot() const = 0;
|
||||
|
||||
// Fault reporting normally follows the selected interface. Automatic
|
||||
// Ethernet-preferred builds instead keep reporting the primary Ethernet
|
||||
// outage while healthy Wi-Fi carries traffic, so prolonged degradation is
|
||||
// not hidden by a successful fallback.
|
||||
virtual NetworkMedium alertMedium() const { return medium(); }
|
||||
virtual AlertFaultPolicy::OutageSnapshot alertOutageSnapshot() const {
|
||||
return outageSnapshot();
|
||||
}
|
||||
};
|
||||
|
||||
/** Build-selected singleton. Wi-Fi is the compatibility default. */
|
||||
NetworkLink& activeNetworkLink();
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,225 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
enum class NetworkTransition : uint8_t {
|
||||
None,
|
||||
Up,
|
||||
Down,
|
||||
Switched,
|
||||
};
|
||||
|
||||
enum class NetworkMedium : uint8_t {
|
||||
None,
|
||||
Ethernet,
|
||||
WiFi,
|
||||
};
|
||||
|
||||
enum class NetworkDiagnosticReason : uint8_t {
|
||||
EthernetActive,
|
||||
EthernetInitFailed,
|
||||
EthernetLinkUnknown,
|
||||
EthernetLinkDown,
|
||||
EthernetAwaitingIp,
|
||||
EthernetStabilizing,
|
||||
SwitchingLocked,
|
||||
EthernetReady,
|
||||
};
|
||||
|
||||
namespace NetworkPolicy {
|
||||
|
||||
struct MQTTTransitionActions {
|
||||
bool disconnect_started_slots;
|
||||
bool retry_disconnected_slots_now;
|
||||
bool reset_reconnect_backoff;
|
||||
};
|
||||
|
||||
static constexpr MQTTTransitionActions mqttActions(NetworkTransition transition) {
|
||||
return {
|
||||
transition == NetworkTransition::Down || transition == NetworkTransition::Switched,
|
||||
transition == NetworkTransition::Up || transition == NetworkTransition::Switched,
|
||||
transition == NetworkTransition::Switched,
|
||||
};
|
||||
}
|
||||
|
||||
static constexpr const char* mediumName(NetworkMedium medium) {
|
||||
return medium == NetworkMedium::Ethernet ? "ethernet"
|
||||
: medium == NetworkMedium::WiFi ? "wifi"
|
||||
: "none";
|
||||
}
|
||||
|
||||
struct AutomaticSelectionInput {
|
||||
NetworkMedium selected;
|
||||
bool ethernet_connected;
|
||||
bool wifi_connected;
|
||||
bool wifi_configured;
|
||||
bool switching_locked;
|
||||
uint32_t ethernet_stable_ms;
|
||||
uint32_t selected_down_ms;
|
||||
};
|
||||
|
||||
// Keep short link flaps from bouncing the default route. Ethernet is allowed
|
||||
// to recover before Wi-Fi is started, and must then remain usable before it can
|
||||
// preempt a working Wi-Fi fallback.
|
||||
static constexpr uint32_t kEthernetDownGraceMs = 3000;
|
||||
static constexpr uint32_t kEthernetFailbackStableMs = 10000;
|
||||
static constexpr uint32_t kEthernetNoLinkBootGraceMs = 750;
|
||||
static constexpr uint32_t kEthernetNoIpRecoveryMs = 120000;
|
||||
static constexpr uint32_t kEthernetInitRetryMinMs = 5000;
|
||||
static constexpr uint32_t kEthernetInitRetryMaxMs = 300000;
|
||||
static constexpr uint32_t kNtpRetryMs = 30000;
|
||||
static constexpr uint32_t kManualOtaSessionTimeoutMs =
|
||||
15UL * 60UL * 1000UL;
|
||||
|
||||
static inline uint32_t ethernetInitRetryDelayMs(uint8_t attempt) {
|
||||
if (attempt == 0) return 0;
|
||||
uint32_t delay_ms = kEthernetInitRetryMinMs;
|
||||
for (uint8_t i = 1; i < attempt && delay_ms < kEthernetInitRetryMaxMs; ++i) {
|
||||
delay_ms = delay_ms > kEthernetInitRetryMaxMs / 2
|
||||
? kEthernetInitRetryMaxMs : delay_ms * 2;
|
||||
}
|
||||
return delay_ms;
|
||||
}
|
||||
|
||||
static inline bool ethernetInitRetryDue(uint8_t attempt,
|
||||
uint32_t now_ms,
|
||||
uint32_t last_attempt_ms) {
|
||||
return attempt == 0 ||
|
||||
(uint32_t)(now_ms - last_attempt_ms) >=
|
||||
ethernetInitRetryDelayMs(attempt);
|
||||
}
|
||||
|
||||
static constexpr bool ethernetNoIpRecoveryDue(bool initialized,
|
||||
bool link_up,
|
||||
bool connected,
|
||||
uint32_t now_ms,
|
||||
uint32_t no_ip_since_ms) {
|
||||
return initialized && link_up && !connected && no_ip_since_ms != 0 &&
|
||||
(uint32_t)(now_ms - no_ip_since_ms) >= kEthernetNoIpRecoveryMs;
|
||||
}
|
||||
|
||||
static inline NetworkDiagnosticReason automaticDiagnosticReason(
|
||||
bool ethernet_initialized, bool ethernet_link_known,
|
||||
bool ethernet_link_up, bool ethernet_connected, NetworkMedium selected,
|
||||
bool switching_locked, uint32_t ethernet_stable_ms) {
|
||||
if (!ethernet_initialized) {
|
||||
return NetworkDiagnosticReason::EthernetInitFailed;
|
||||
}
|
||||
if (!ethernet_link_known) {
|
||||
return NetworkDiagnosticReason::EthernetLinkUnknown;
|
||||
}
|
||||
if (!ethernet_link_up) {
|
||||
return NetworkDiagnosticReason::EthernetLinkDown;
|
||||
}
|
||||
if (!ethernet_connected) {
|
||||
return NetworkDiagnosticReason::EthernetAwaitingIp;
|
||||
}
|
||||
if (selected == NetworkMedium::Ethernet) {
|
||||
return NetworkDiagnosticReason::EthernetActive;
|
||||
}
|
||||
if (switching_locked) {
|
||||
return NetworkDiagnosticReason::SwitchingLocked;
|
||||
}
|
||||
if (selected == NetworkMedium::WiFi &&
|
||||
ethernet_stable_ms < kEthernetFailbackStableMs) {
|
||||
return NetworkDiagnosticReason::EthernetStabilizing;
|
||||
}
|
||||
return NetworkDiagnosticReason::EthernetReady;
|
||||
}
|
||||
|
||||
static inline const char* diagnosticReasonName(
|
||||
NetworkDiagnosticReason reason) {
|
||||
switch (reason) {
|
||||
case NetworkDiagnosticReason::EthernetActive:
|
||||
return "ethernet-active";
|
||||
case NetworkDiagnosticReason::EthernetInitFailed:
|
||||
return "ethernet-init-failed";
|
||||
case NetworkDiagnosticReason::EthernetLinkUnknown:
|
||||
return "ethernet-link-unknown";
|
||||
case NetworkDiagnosticReason::EthernetLinkDown:
|
||||
return "ethernet-link-down";
|
||||
case NetworkDiagnosticReason::EthernetAwaitingIp:
|
||||
return "ethernet-awaiting-ip";
|
||||
case NetworkDiagnosticReason::EthernetStabilizing:
|
||||
return "ethernet-stabilizing";
|
||||
case NetworkDiagnosticReason::SwitchingLocked:
|
||||
return "switching-locked";
|
||||
case NetworkDiagnosticReason::EthernetReady:
|
||||
return "ethernet-ready";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
static constexpr bool ntpPendingAfterConnectivitySample(
|
||||
bool synced, bool pending, bool was_connected, bool connected) {
|
||||
return pending || (!synced && connected && !was_connected);
|
||||
}
|
||||
|
||||
static constexpr bool ntpRetryDue(bool synced, bool connected,
|
||||
uint32_t now_ms, uint32_t last_attempt_ms) {
|
||||
return !synced && connected &&
|
||||
(uint32_t)(now_ms - last_attempt_ms) >= kNtpRetryMs;
|
||||
}
|
||||
|
||||
static constexpr NetworkMedium bootSelection(bool ethernet_connected,
|
||||
bool wifi_configured) {
|
||||
return ethernet_connected ? NetworkMedium::Ethernet
|
||||
: wifi_configured ? NetworkMedium::WiFi
|
||||
: NetworkMedium::None;
|
||||
}
|
||||
|
||||
// Give the PHY a short window to report carrier. Once a definitive link-down
|
||||
// sample arrives, do not stall mesh startup for the full DHCP deadline. A
|
||||
// present link (or an unknown PHY state) still receives the entire probe.
|
||||
static constexpr bool ethernetBootProbePending(bool ethernet_initialized,
|
||||
bool ethernet_connected,
|
||||
bool link_known,
|
||||
bool link_up,
|
||||
uint32_t elapsed_ms,
|
||||
uint32_t wait_ms) {
|
||||
return ethernet_initialized && !ethernet_connected && elapsed_ms < wait_ms &&
|
||||
(!link_known || link_up || elapsed_ms < kEthernetNoLinkBootGraceMs);
|
||||
}
|
||||
|
||||
static inline NetworkMedium automaticSelection(
|
||||
const AutomaticSelectionInput& input) {
|
||||
if (input.switching_locked) return input.selected;
|
||||
|
||||
if (input.selected == NetworkMedium::Ethernet) {
|
||||
if (input.ethernet_connected) return NetworkMedium::Ethernet;
|
||||
if (input.wifi_configured && input.wifi_connected &&
|
||||
input.selected_down_ms >= kEthernetDownGraceMs) {
|
||||
return NetworkMedium::WiFi;
|
||||
}
|
||||
return NetworkMedium::Ethernet;
|
||||
}
|
||||
|
||||
if (input.selected == NetworkMedium::WiFi) {
|
||||
if (input.ethernet_connected &&
|
||||
(!input.wifi_connected ||
|
||||
input.ethernet_stable_ms >= kEthernetFailbackStableMs)) {
|
||||
return NetworkMedium::Ethernet;
|
||||
}
|
||||
return NetworkMedium::WiFi;
|
||||
}
|
||||
|
||||
if (input.ethernet_connected) return NetworkMedium::Ethernet;
|
||||
if (input.wifi_configured && input.wifi_connected) return NetworkMedium::WiFi;
|
||||
return NetworkMedium::None;
|
||||
}
|
||||
|
||||
// `start ota` uses the selected LAN only when reachable and not explicitly
|
||||
// forced to SoftAP. Manifest OTA has no fallback and checks connectivity itself.
|
||||
static constexpr bool startOtaUsesSelectedNetwork(bool force_ap,
|
||||
bool network_connected) {
|
||||
return !force_ap && network_connected;
|
||||
}
|
||||
|
||||
static constexpr bool manualOtaTimeoutDue(uint32_t now_ms,
|
||||
uint32_t started_ms,
|
||||
bool upload_in_progress) {
|
||||
return !upload_in_progress &&
|
||||
(uint32_t)(now_ms - started_ms) >= kManualOtaSessionTimeoutMs;
|
||||
}
|
||||
|
||||
} // namespace NetworkPolicy
|
||||
@@ -0,0 +1,141 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Client-side NTPv4 request building and response validation.
|
||||
//
|
||||
// Pure logic: no Arduino, WiFi or UDP headers, so every rejection case is
|
||||
// host-testable. The caller owns the socket and supplies the datagram plus
|
||||
// whether it arrived from the server it asked (see MQTTBridge::probeNtpServer).
|
||||
//
|
||||
// This exists because the NTPClient library accepted *any* non-empty datagram
|
||||
// on its fixed local port as time: it ignored the read length, the mode, the
|
||||
// stratum, the leap indicator and the request/response correlation, so a
|
||||
// one-byte packet from anywhere set the clock — which then feeds JWT issuance,
|
||||
// certificate validity and the RTC. Everything below is the validation that
|
||||
// path never had.
|
||||
namespace NtpValidation {
|
||||
|
||||
static const size_t kPacketSize = 48;
|
||||
|
||||
// Seconds between the NTP epoch (1900-01-01) and the Unix epoch (1970-01-01).
|
||||
static const uint32_t kUnixEpochOffset = 2208988800UL;
|
||||
// Wrap distance for NTP era 1, which starts 2036-02-07: era-1 seconds count
|
||||
// from there, so a small NTP seconds field is a *future* time, not a past one.
|
||||
static const uint32_t kEra1UnixOffset = 2085978496UL;
|
||||
|
||||
enum Reject : uint8_t {
|
||||
kAccepted = 0,
|
||||
kShortPacket, // fewer than 48 bytes: not an NTP response at all
|
||||
kWrongSource, // not from the address/port we queried
|
||||
kBadVersion, // NTP version outside 3..4
|
||||
kBadMode, // not mode 4 (server)
|
||||
kLeapAlarm, // LI=3: the server itself is unsynchronised
|
||||
kBadStratum, // 0 (kiss-of-death) or >= 16 (unsynchronised)
|
||||
kOriginMismatch, // did not echo the transmit timestamp we sent
|
||||
kZeroTransmit, // no transmit timestamp
|
||||
kEpochTooEarly, // before the caller's floor
|
||||
kEpochTooLate, // implausibly far in the future
|
||||
};
|
||||
|
||||
// The transmit timestamp we send and the server must echo back in its originate
|
||||
// field. Random, so an off-path sender cannot answer a query it never saw.
|
||||
struct Nonce {
|
||||
uint32_t seconds;
|
||||
uint32_t fraction;
|
||||
};
|
||||
|
||||
struct Result {
|
||||
Reject reject;
|
||||
uint32_t epoch; // Unix seconds; only meaningful when reject == kAccepted
|
||||
};
|
||||
|
||||
static inline uint32_t readU32(const uint8_t* p) {
|
||||
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
|
||||
((uint32_t)p[2] << 8) | (uint32_t)p[3];
|
||||
}
|
||||
|
||||
static inline void writeU32(uint8_t* p, uint32_t v) {
|
||||
p[0] = (uint8_t)(v >> 24);
|
||||
p[1] = (uint8_t)(v >> 16);
|
||||
p[2] = (uint8_t)(v >> 8);
|
||||
p[3] = (uint8_t)v;
|
||||
}
|
||||
|
||||
// LI=0 (no warning), VN=4, Mode=3 (client). The NTPClient request claimed LI=3,
|
||||
// advertising an alarm condition it had no business asserting.
|
||||
static inline void buildRequest(uint8_t out[kPacketSize], Nonce nonce) {
|
||||
memset(out, 0, kPacketSize);
|
||||
out[0] = 0x23;
|
||||
out[1] = 0; // stratum: unspecified
|
||||
out[2] = 6; // poll interval
|
||||
out[3] = 0xEC; // precision
|
||||
writeU32(out + 40, nonce.seconds); // transmit timestamp = our nonce
|
||||
writeU32(out + 44, nonce.fraction);
|
||||
}
|
||||
|
||||
// Unix time for an NTP seconds field, handling the 2036 era rollover instead of
|
||||
// wrapping into 1900 the way an unchecked subtraction does.
|
||||
static inline uint32_t unixFromNtpSeconds(uint32_t ntp_seconds) {
|
||||
return ntp_seconds >= kUnixEpochOffset ? (ntp_seconds - kUnixEpochOffset)
|
||||
: (ntp_seconds + kEra1UnixOffset);
|
||||
}
|
||||
|
||||
// `source_matches` is the caller's check that the datagram came from the
|
||||
// address and port it queried; it is a parameter rather than a lookup so this
|
||||
// stays free of socket types.
|
||||
static inline Result validate(const uint8_t* data, size_t len, bool source_matches,
|
||||
Nonce nonce, uint32_t min_epoch, uint32_t max_epoch) {
|
||||
Result r;
|
||||
r.epoch = 0;
|
||||
|
||||
if (data == nullptr || len < kPacketSize) { r.reject = kShortPacket; return r; }
|
||||
if (!source_matches) { r.reject = kWrongSource; return r; }
|
||||
|
||||
const uint8_t li = (uint8_t)((data[0] >> 6) & 0x03);
|
||||
const uint8_t version = (uint8_t)((data[0] >> 3) & 0x07);
|
||||
const uint8_t mode = (uint8_t)(data[0] & 0x07);
|
||||
const uint8_t stratum = data[1];
|
||||
|
||||
if (version < 3 || version > 4) { r.reject = kBadVersion; return r; }
|
||||
if (mode != 4) { r.reject = kBadMode; return r; }
|
||||
if (li == 3) { r.reject = kLeapAlarm; return r; }
|
||||
// Stratum 0 carries a kiss-of-death code (RATE/DENY/RSTR) rather than time;
|
||||
// 16 and above means the server has no time to give.
|
||||
if (stratum == 0 || stratum >= 16) { r.reject = kBadStratum; return r; }
|
||||
|
||||
if (readU32(data + 24) != nonce.seconds ||
|
||||
readU32(data + 28) != nonce.fraction) { r.reject = kOriginMismatch; return r; }
|
||||
|
||||
const uint32_t transmit_seconds = readU32(data + 40);
|
||||
if (transmit_seconds == 0) { r.reject = kZeroTransmit; return r; }
|
||||
|
||||
const uint32_t epoch = unixFromNtpSeconds(transmit_seconds);
|
||||
if (epoch < min_epoch) { r.reject = kEpochTooEarly; return r; }
|
||||
if (epoch > max_epoch) { r.reject = kEpochTooLate; return r; }
|
||||
|
||||
r.reject = kAccepted;
|
||||
r.epoch = epoch;
|
||||
return r;
|
||||
}
|
||||
|
||||
// Short enough for a LoRa-bounded diagnostic reply.
|
||||
static inline const char* rejectReason(Reject reject) {
|
||||
switch (reject) {
|
||||
case kAccepted: return "ok";
|
||||
case kShortPacket: return "short packet";
|
||||
case kWrongSource: return "wrong source";
|
||||
case kBadVersion: return "bad version";
|
||||
case kBadMode: return "not a server reply";
|
||||
case kLeapAlarm: return "server unsynced";
|
||||
case kBadStratum: return "bad stratum";
|
||||
case kOriginMismatch: return "unsolicited reply";
|
||||
case kZeroTransmit: return "no timestamp";
|
||||
case kEpochTooEarly: return "time too old";
|
||||
case kEpochTooLate: return "time too far ahead";
|
||||
default: return "invalid";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace NtpValidation
|
||||
@@ -0,0 +1,116 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// Decides when the observer radio watchdog should kick a radio that is parked in
|
||||
// RX but hearing nothing (see Dispatcher::loop()).
|
||||
//
|
||||
// Pure logic: no Arduino, radio or mesh headers. The caller feeds the raw 32-bit
|
||||
// activity timestamps it can see (last receive, last radio interrupt, last
|
||||
// successful transmit) plus its millis() counter.
|
||||
//
|
||||
// Why this is not a max() of those three timestamps: millis() wraps every ~49.7
|
||||
// days, and a pre-wrap timestamp is numerically larger than every fresh
|
||||
// post-wrap one. Picking the largest therefore latches onto an old transmit and
|
||||
// reports the radio silent while it is receiving continuously, resetting a
|
||||
// healthy radio once per watchdog interval until that timestamp stops winning.
|
||||
//
|
||||
// Instead the caller's timestamps are only ever compared with their own previous
|
||||
// values: any change is fresh activity, stamped against a monotonic 64-bit clock
|
||||
// extended from millis(). Nothing downstream has a rollover case, and evidence
|
||||
// older than one 32-bit cycle stays old instead of aliasing back to "recent".
|
||||
//
|
||||
// How far a timestamp may run behind the previous one and still count as an
|
||||
// out-of-order reading rather than a very long forward gap (same rule as
|
||||
// RadioActivityWindow).
|
||||
#define RADIO_WATCHDOG_BACKSTEP_TOLERANCE_MS 5000UL
|
||||
|
||||
struct RadioWatchdogDecision {
|
||||
bool recover; // trip now: idle + restart receive
|
||||
bool measurable; // false until some activity has been observed
|
||||
uint64_t silent_ms; // age of the most recent activity (0 when !measurable)
|
||||
};
|
||||
|
||||
class RadioWatchdog {
|
||||
public:
|
||||
RadioWatchdog() { reset(0); }
|
||||
|
||||
void reset(uint32_t now_ms) {
|
||||
_now_ms = now_ms;
|
||||
_last_input_ms = now_ms;
|
||||
_seeded = false;
|
||||
_has_activity = false;
|
||||
_last_recv = _last_irq = _last_tx = 0;
|
||||
_last_activity_ms = now_ms;
|
||||
_recovered = false;
|
||||
_last_recovery_ms = 0;
|
||||
}
|
||||
|
||||
// Call once per loop with the current activity timestamps. `in_recv_mode` and
|
||||
// `watchdog_ms` (0 disables) gate the decision; the silence measurement is
|
||||
// updated either way so a disabled or transmitting radio does not accumulate
|
||||
// phantom silence.
|
||||
RadioWatchdogDecision update(uint32_t now_ms, bool in_recv_mode, uint32_t watchdog_ms,
|
||||
uint32_t last_recv, uint32_t last_irq, uint32_t last_tx) {
|
||||
tick(now_ms);
|
||||
|
||||
if (!_seeded) {
|
||||
// First observation: the timestamps carry activity from before this
|
||||
// tracker existed, so date it to now rather than trusting a raw value we
|
||||
// cannot place on our own clock. Worst case that delays the first
|
||||
// possible trip by one watchdog interval.
|
||||
_seeded = true;
|
||||
_has_activity = (last_recv != 0 || last_irq != 0 || last_tx != 0);
|
||||
_last_activity_ms = _now_ms;
|
||||
} else if (last_recv != _last_recv || last_irq != _last_irq || last_tx != _last_tx) {
|
||||
_has_activity = true;
|
||||
_last_activity_ms = _now_ms;
|
||||
}
|
||||
_last_recv = last_recv;
|
||||
_last_irq = last_irq;
|
||||
_last_tx = last_tx;
|
||||
|
||||
RadioWatchdogDecision d;
|
||||
d.recover = false;
|
||||
d.measurable = _has_activity;
|
||||
d.silent_ms = _has_activity ? (_now_ms - _last_activity_ms) : 0;
|
||||
|
||||
if (!_has_activity || !in_recv_mode || watchdog_ms == 0) return d;
|
||||
if (d.silent_ms <= watchdog_ms) return d;
|
||||
// One recovery per watchdog interval: a radio that stays silent through a
|
||||
// reset must not be reset every loop.
|
||||
if (_recovered && (_now_ms - _last_recovery_ms) <= watchdog_ms) return d;
|
||||
|
||||
d.recover = true;
|
||||
return d;
|
||||
}
|
||||
|
||||
// Call after acting on a decision with recover set.
|
||||
void noteRecovery() {
|
||||
_recovered = true;
|
||||
_last_recovery_ms = _now_ms;
|
||||
}
|
||||
|
||||
uint64_t nowMs() const { return _now_ms; }
|
||||
|
||||
private:
|
||||
// Extends the caller's 32-bit millis() to a monotonic 64-bit clock.
|
||||
void tick(uint32_t now_ms) {
|
||||
uint32_t delta = now_ms - _last_input_ms;
|
||||
if (delta > 0x80000000u &&
|
||||
(uint32_t)(_last_input_ms - now_ms) <= RADIO_WATCHDOG_BACKSTEP_TOLERANCE_MS) {
|
||||
return; // out-of-order reading: no time has passed
|
||||
}
|
||||
_now_ms += delta;
|
||||
_last_input_ms = now_ms;
|
||||
}
|
||||
|
||||
uint64_t _now_ms;
|
||||
uint32_t _last_input_ms;
|
||||
bool _seeded;
|
||||
bool _has_activity;
|
||||
uint32_t _last_recv, _last_irq, _last_tx;
|
||||
uint64_t _last_activity_ms;
|
||||
bool _recovered;
|
||||
uint64_t _last_recovery_ms;
|
||||
};
|
||||
@@ -20,7 +20,7 @@ static const char* const WC_ALLOWED_SET_KEYS[] = {
|
||||
// NodePrefs (radio / node)
|
||||
"name", "bluetooth.name", "bluetooth.mac", "bluetooth.stealth",
|
||||
"lat", "lon", "radio", "tx", "af", "rxdelay", "txdelay",
|
||||
"cad", "radio.rxgain", "radio.fem.rxgain", "radio.rxps", "powersaving",
|
||||
"cad", "radio.rxgain", "radio.fem.rxgain", "radio.fem.txgain", "radio.rxps", "powersaving",
|
||||
"repeat",
|
||||
"display.mode", "display.timeout", "display.usb.mode", "display.usb.timeout",
|
||||
"display.inbox",
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// The single mapping between the stored `wifi.powersave` preference, its CLI
|
||||
// name, and the IDF power-save mode.
|
||||
//
|
||||
// Pure lookup so host tests can hold startup, reconnect, CLI and web config to
|
||||
// one table: they used to map the same stored value differently, so a node set
|
||||
// to `min` silently ran with power save off after its first reconnect while
|
||||
// `get wifi.powersave` still said min.
|
||||
//
|
||||
// Stored values are fleet state — never renumber them. 0 was the shipped
|
||||
// default from 2026-01-02 to 2026-03-28, and every association path ran it with
|
||||
// power save off, so it keeps meaning `none`; an explicit `min` is stored as 3.
|
||||
// Older firmware repairs 3 to `none` when it loads /mqtt.json.
|
||||
namespace WifiPowerSavePolicy {
|
||||
|
||||
enum StoredValue : uint8_t {
|
||||
kLegacyDefault = 0, // WIFI_PS_NONE: the old default, never an operator choice
|
||||
kNone = 1, // WIFI_PS_NONE (default)
|
||||
kMax = 2, // WIFI_PS_MAX_MODEM
|
||||
kMin = 3, // WIFI_PS_MIN_MODEM
|
||||
kMaxStoredValue = kMin,
|
||||
};
|
||||
|
||||
// Mirrors wifi_ps_type_t. MQTTBridge.cpp static_asserts these against the SDK.
|
||||
enum Mode : uint8_t {
|
||||
kModeNone = 0,
|
||||
kModeMinModem = 1,
|
||||
kModeMaxModem = 2,
|
||||
};
|
||||
|
||||
// Anything outside the known range reads as the default rather than as the
|
||||
// lowest-numbered mode, so a corrupt byte cannot silently enable modem sleep.
|
||||
static inline Mode modeFor(uint8_t stored) {
|
||||
switch (stored) {
|
||||
case kMin: return kModeMinModem;
|
||||
case kMax: return kModeMaxModem;
|
||||
case kNone: return kModeNone;
|
||||
default: return kModeNone;
|
||||
}
|
||||
}
|
||||
|
||||
static inline const char* nameFor(uint8_t stored) {
|
||||
switch (stored) {
|
||||
case kMin: return "min";
|
||||
case kMax: return "max";
|
||||
case kNone: return "none";
|
||||
default: return "none";
|
||||
}
|
||||
}
|
||||
|
||||
// Parses a CLI argument, which may be followed by trailing text (the observer
|
||||
// setters take the rest of the command line). Returns false and leaves *out
|
||||
// untouched for anything else.
|
||||
static inline bool parseName(const char* value, uint8_t* out) {
|
||||
if (value == nullptr || out == nullptr) return false;
|
||||
static const struct { const char* name; uint8_t stored; } kNames[] = {
|
||||
{ "min", kMin },
|
||||
{ "none", kNone },
|
||||
{ "max", kMax },
|
||||
};
|
||||
for (unsigned i = 0; i < sizeof(kNames) / sizeof(kNames[0]); i++) {
|
||||
const size_t len = strlen(kNames[i].name);
|
||||
if (strncmp(value, kNames[i].name, len) == 0 &&
|
||||
(value[len] == '\0' || value[len] == ' ')) {
|
||||
*out = kNames[i].stored;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace WifiPowerSavePolicy
|
||||
@@ -0,0 +1,125 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// Operator-facing labels for the SDK error codes the observer reports through
|
||||
// `get wifi.status`, `get mqttN.diag` and the web config panel.
|
||||
//
|
||||
// Pure lookup: no Arduino or ESP headers, so the table is host-testable. The
|
||||
// numeric values below are the installed SDK's; MQTTBridge.cpp static_asserts
|
||||
// every one of them against the real enum/#define, so a framework bump either
|
||||
// keeps these labels honest or fails the build. Codes with no entry return
|
||||
// nullptr and the caller prints the raw number — an unknown code must never be
|
||||
// given a neighbouring code's name.
|
||||
namespace MQTTErrorLabels {
|
||||
|
||||
// esp_wifi_types.h wifi_err_reason_t. Values below 200 are 802.11 reason codes
|
||||
// forwarded from the AP; 200+ are Espressif's own local failures.
|
||||
enum WifiReason : uint16_t {
|
||||
kWifiAuthExpire = 2,
|
||||
kWifiAssocExpire = 4,
|
||||
kWifiAssocLeave = 8,
|
||||
kWifi4WayHandshakeTimeout = 15,
|
||||
kWifiGroupCipherInvalid = 18,
|
||||
kWifiCipherSuiteRejected = 24,
|
||||
kWifiMissingAcks = 34,
|
||||
kWifiTimeout = 39,
|
||||
kWifiInvalidPmkid = 49,
|
||||
kWifiBssTransitionDisassoc = 12,
|
||||
kWifiBeaconTimeout = 200,
|
||||
kWifiNoApFound = 201,
|
||||
kWifiAuthFail = 202,
|
||||
kWifiAssocFail = 203,
|
||||
kWifiHandshakeTimeout = 204,
|
||||
kWifiConnectionFail = 205,
|
||||
kWifiApTsfReset = 206,
|
||||
kWifiRoaming = 207,
|
||||
kWifiSaQueryTimeout = 209,
|
||||
};
|
||||
|
||||
// esp_tls_errors.h, ESP_ERR_ESP_TLS_BASE (0x8000) + offset.
|
||||
enum TlsError : int32_t {
|
||||
kTlsCannotResolveHostname = 0x8001,
|
||||
kTlsCannotCreateSocket = 0x8002,
|
||||
kTlsUnsupportedProtoFamily= 0x8003,
|
||||
kTlsFailedConnectToHost = 0x8004,
|
||||
kTlsSocketSetoptFailed = 0x8005,
|
||||
kTlsConnectionTimeout = 0x8006,
|
||||
kTlsTcpClosedFin = 0x8008,
|
||||
kTlsMbedtlsCertPartlyOk = 0x8010,
|
||||
kTlsMbedtlsSetHostname = 0x8012,
|
||||
kTlsMbedtlsX509ParseFailed= 0x8015,
|
||||
kTlsMbedtlsSslSetupFailed = 0x8017,
|
||||
kTlsMbedtlsSslWriteFailed = 0x8018,
|
||||
kTlsMbedtlsHandshakeFailed= 0x801A,
|
||||
};
|
||||
|
||||
// MQTT 3.1.1 CONNACK return codes (esp_mqtt_error_codes.connect_return_code).
|
||||
enum ConnackCode : uint8_t {
|
||||
kConnackAccepted = 0,
|
||||
kConnackBadProtocol = 1,
|
||||
kConnackIdRejected = 2,
|
||||
kConnackServerUnavail = 3,
|
||||
kConnackBadCredentials = 4,
|
||||
kConnackNotAuthorized = 5,
|
||||
};
|
||||
|
||||
// Short enough to sit inside a LoRa-bounded diagnostic reply next to the raw code.
|
||||
static inline const char* wifiReason(uint8_t reason) {
|
||||
switch (reason) {
|
||||
case kWifiAuthExpire: return "auth expired";
|
||||
case kWifiAssocExpire: return "assoc expired";
|
||||
case kWifiAssocLeave: return "AP disconnected";
|
||||
case kWifiBssTransitionDisassoc: return "AP steered us away";
|
||||
case kWifi4WayHandshakeTimeout: return "4-way handshake timeout";
|
||||
case kWifiGroupCipherInvalid: return "group cipher mismatch";
|
||||
case kWifiCipherSuiteRejected: return "cipher suite rejected";
|
||||
case kWifiMissingAcks: return "AP saw no acks";
|
||||
case kWifiTimeout: return "802.11 timeout";
|
||||
case kWifiInvalidPmkid: return "invalid PMKID";
|
||||
case kWifiBeaconTimeout: return "beacon lost";
|
||||
case kWifiNoApFound: return "SSID not found";
|
||||
case kWifiAuthFail: return "auth failed (check password)";
|
||||
case kWifiAssocFail: return "association failed";
|
||||
case kWifiHandshakeTimeout: return "handshake timeout";
|
||||
case kWifiConnectionFail: return "connect failed";
|
||||
case kWifiApTsfReset: return "AP restarted";
|
||||
case kWifiRoaming: return "roaming";
|
||||
case kWifiSaQueryTimeout: return "SA query timeout (PMF)";
|
||||
default: return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
static inline const char* tlsError(int32_t err) {
|
||||
switch (err) {
|
||||
case kTlsCannotResolveHostname: return "DNS failed";
|
||||
case kTlsCannotCreateSocket: return "socket error";
|
||||
case kTlsUnsupportedProtoFamily: return "unsupported protocol family";
|
||||
case kTlsFailedConnectToHost: return "connect failed";
|
||||
case kTlsSocketSetoptFailed: return "socket setopt failed";
|
||||
case kTlsConnectionTimeout: return "connection timeout";
|
||||
case kTlsTcpClosedFin: return "server closed connection";
|
||||
case kTlsMbedtlsCertPartlyOk: return "cert chain partly parsed";
|
||||
case kTlsMbedtlsSetHostname: return "SNI hostname rejected";
|
||||
case kTlsMbedtlsX509ParseFailed: return "cert parse failed";
|
||||
case kTlsMbedtlsSslSetupFailed: return "TLS setup failed";
|
||||
case kTlsMbedtlsSslWriteFailed: return "TLS write failed";
|
||||
case kTlsMbedtlsHandshakeFailed: return "TLS handshake failed";
|
||||
default: return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
// The broker answered and refused: this is what an operator needs instead of a
|
||||
// transport error, which is why the bridge keeps the CONNACK code separately.
|
||||
static inline const char* connackReason(uint8_t code) {
|
||||
switch (code) {
|
||||
case kConnackBadProtocol: return "protocol rejected";
|
||||
case kConnackIdRejected: return "client id rejected";
|
||||
case kConnackServerUnavail: return "server unavailable";
|
||||
case kConnackBadCredentials: return "bad user/password";
|
||||
case kConnackNotAuthorized: return "not authorized";
|
||||
default: return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace MQTTErrorLabels
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <stdint.h>
|
||||
|
||||
// Ownership guard for the two AsyncWebServer users. It prevents `start ota`
|
||||
// from claiming port 80 while WebConfig is listening (and vice versa), even
|
||||
// when the requests arrive from different tasks.
|
||||
namespace HttpPort80Lease {
|
||||
|
||||
enum class Owner : uint8_t { None = 0, WebConfig, Ota };
|
||||
|
||||
inline std::atomic<Owner>& current() {
|
||||
static std::atomic<Owner> owner{Owner::None};
|
||||
return owner;
|
||||
}
|
||||
|
||||
inline bool acquire(Owner requested) {
|
||||
if (requested == Owner::None) return false;
|
||||
Owner expected = Owner::None;
|
||||
return current().compare_exchange_strong(
|
||||
expected, requested, std::memory_order_acq_rel,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
inline void release(Owner expected) {
|
||||
current().compare_exchange_strong(
|
||||
expected, Owner::None, std::memory_order_acq_rel,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
inline const char* ownerName() {
|
||||
switch (current().load(std::memory_order_acquire)) {
|
||||
case Owner::WebConfig: return "webconfig";
|
||||
case Owner::Ota: return "ota";
|
||||
default: return "none";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace HttpPort80Lease
|
||||
+1916
-1893
File diff suppressed because it is too large.
Load diff
@@ -238,6 +238,12 @@ static inline bool wcIsDeferredReboot(const char* cmd) {
|
||||
return strncmp(cmd, "reboot", 6) == 0;
|
||||
}
|
||||
|
||||
static const char* const WC_BOARD_CMDS[] = {
|
||||
"radio.fem.rxgain", "radio.fem.txgain", "fan",
|
||||
};
|
||||
static const size_t WC_BOARD_CMD_COUNT = sizeof(WC_BOARD_CMDS) / sizeof(WC_BOARD_CMDS[0]);
|
||||
static_assert(WC_BOARD_CMD_COUNT <= 8, "board command mask must fit uint8_t");
|
||||
|
||||
// Commands the CLI reaches but the portal cannot honestly serve. Rejected at
|
||||
// POST so nothing in the sequence runs, rather than failing halfway with a
|
||||
// reply that does not explain itself. Returns the reason, or NULL if fine.
|
||||
@@ -1007,9 +1013,25 @@ void WebConfigServer::finalizeTeardown() {
|
||||
_admin_pwd_set = false;
|
||||
_session_token[0] = 0;
|
||||
_stats_json[0] = 0;
|
||||
_board_cmds = 0;
|
||||
_board_cmds_probed = false;
|
||||
if (_cb) _cb->onWebConfigStopped();
|
||||
}
|
||||
|
||||
void WebConfigServer::probeBoardCommands() {
|
||||
char command[48], reply[160];
|
||||
uint8_t mask = 0;
|
||||
for (size_t i = 0; i < WC_BOARD_CMD_COUNT; ++i) {
|
||||
snprintf(command, sizeof(command), "get %s", WC_BOARD_CMDS[i]);
|
||||
reply[0] = 0;
|
||||
_cb->execCommand(command, reply);
|
||||
if (reply[0] == '>') mask |= static_cast<uint8_t>(1U << i);
|
||||
}
|
||||
WCLock lock(_mux);
|
||||
_board_cmds = mask;
|
||||
_board_cmds_probed = true;
|
||||
}
|
||||
|
||||
void WebConfigServer::tick(uint32_t now) {
|
||||
if (_stopping) {
|
||||
uint32_t refs = handlerRefCount();
|
||||
@@ -1030,6 +1052,8 @@ void WebConfigServer::tick(uint32_t now) {
|
||||
}
|
||||
if (_mode == MODE_OFF) return;
|
||||
|
||||
if (!_board_cmds_probed) probeBoardCommands();
|
||||
|
||||
serviceTerminal(now);
|
||||
|
||||
// A primary ESP-NOW radio and its WiFi station cannot remain on different
|
||||
@@ -1662,7 +1686,7 @@ void WebConfigServer::handleStatus(AsyncWebServerRequest* req) {
|
||||
}
|
||||
const bool has_mqtt = _mqtt_prefs != NULL;
|
||||
|
||||
DynamicJsonDocument doc(768);
|
||||
DynamicJsonDocument doc(896);
|
||||
doc["mode"] = (_mode == MODE_SETUP) ? "setup" : "lan";
|
||||
doc["auth"] = authed;
|
||||
doc["needs_setup"] = (_wifi_ssid[0] == 0);
|
||||
@@ -1678,6 +1702,25 @@ void WebConfigServer::handleStatus(AsyncWebServerRequest* req) {
|
||||
doc["build_date"] = _build_date;
|
||||
doc["role"] = _role;
|
||||
doc["board"] = _board_name;
|
||||
uint8_t board_mask = 0;
|
||||
bool board_probed = false;
|
||||
{
|
||||
WCLock lock(_mux);
|
||||
board_mask = _board_cmds;
|
||||
board_probed = _board_cmds_probed;
|
||||
}
|
||||
if (board_probed) {
|
||||
char board_cmds[80] = {0};
|
||||
size_t used = 0;
|
||||
for (size_t i = 0; i < WC_BOARD_CMD_COUNT; ++i) {
|
||||
if ((board_mask & (1U << i)) == 0) continue;
|
||||
const int written = snprintf(board_cmds + used, sizeof(board_cmds) - used,
|
||||
"%s%s", used ? "," : "", WC_BOARD_CMDS[i]);
|
||||
if (written < 0 || static_cast<size_t>(written) >= sizeof(board_cmds) - used) break;
|
||||
used += static_cast<size_t>(written);
|
||||
}
|
||||
doc["board_cmds"] = board_cmds;
|
||||
}
|
||||
doc["uptime_s"] = millis() / 1000;
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
doc["runtime_slots"] = has_mqtt ? RUNTIME_MQTT_SLOTS : 0;
|
||||
|
||||
@@ -333,6 +333,8 @@ private:
|
||||
volatile uint32_t _stats_wanted_until = 0;
|
||||
uint32_t _stats_built_at = 0;
|
||||
char _stats_json[1024] = {0};
|
||||
uint8_t _board_cmds = 0;
|
||||
bool _board_cmds_probed = false;
|
||||
|
||||
void createServer();
|
||||
void registerRoutes();
|
||||
@@ -342,6 +344,7 @@ private:
|
||||
void detachRoutes();
|
||||
uint32_t handlerRefCount() const;
|
||||
void drainBatch(uint32_t now);
|
||||
void probeBoardCommands();
|
||||
void serviceTerminal(uint32_t now);
|
||||
void closeTerminal();
|
||||
void serviceSetupWiFiHandoff(uint32_t now);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include <ESP32_CH390.h>
|
||||
|
||||
/**
|
||||
* Bring up the repository's CH390 lwIP interface from the board build flags.
|
||||
* Shared by the companion transport wrapper and the observer network adapter so
|
||||
* pin and static-IP behavior cannot drift between the two paths.
|
||||
*/
|
||||
static inline bool beginConfiguredCH390(const char* hostname = nullptr) {
|
||||
ch390_config_t config = CH390_DEFAULT_CONFIG();
|
||||
config.spi_miso_gpio = ETH_MISO_PIN;
|
||||
config.spi_mosi_gpio = ETH_MOSI_PIN;
|
||||
config.spi_sck_gpio = ETH_SCLK_PIN;
|
||||
config.spi_cs_gpio = ETH_CS_PIN;
|
||||
config.int_gpio = ETH_INT_PIN;
|
||||
if (hostname && hostname[0] != '\0') {
|
||||
if (!CH390.setHostname(hostname)) {
|
||||
Serial.printf("Network: invalid Ethernet hostname %s\n", hostname);
|
||||
}
|
||||
}
|
||||
if (!CH390.begin(config)) return false;
|
||||
|
||||
#if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET)
|
||||
IPAddress ip(ETHERNET_STATIC_IP);
|
||||
IPAddress gateway(ETHERNET_STATIC_GATEWAY);
|
||||
IPAddress subnet(ETHERNET_STATIC_SUBNET);
|
||||
#if defined(ETHERNET_STATIC_DNS)
|
||||
IPAddress dns(ETHERNET_STATIC_DNS);
|
||||
CH390.config(ip, gateway, subnet, dns);
|
||||
#else
|
||||
CH390.config(ip, gateway, subnet);
|
||||
#endif
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "CH390EthernetInterface.h"
|
||||
#include "CH390Config.h"
|
||||
|
||||
void onWiFiEvent(WiFiEvent_t event) {
|
||||
switch(event){
|
||||
@@ -29,26 +30,12 @@ bool CH390EthernetInterface::begin() {
|
||||
// listen to ethernet events
|
||||
WiFi.onEvent(onWiFiEvent);
|
||||
|
||||
// Init CH390
|
||||
ch390_config_t config = CH390_DEFAULT_CONFIG();
|
||||
config.spi_miso_gpio = ETH_MISO_PIN;
|
||||
config.spi_mosi_gpio = ETH_MOSI_PIN;
|
||||
config.spi_sck_gpio = ETH_SCLK_PIN;
|
||||
config.spi_cs_gpio = ETH_CS_PIN;
|
||||
config.int_gpio = ETH_INT_PIN;
|
||||
if (!CH390.begin(config)) {
|
||||
// Init CH390 using the same board configuration as the observer uplink.
|
||||
if (!beginConfiguredCH390()) {
|
||||
ETHERNET_DEBUG_PRINTLN("Failed to initialize CH390 hardware.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Setup Static IP if build flags are present
|
||||
#if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET)
|
||||
IPAddress ip(ETHERNET_STATIC_IP);
|
||||
IPAddress gw(ETHERNET_STATIC_GATEWAY);
|
||||
IPAddress sn(ETHERNET_STATIC_SUBNET);
|
||||
CH390.config(ip, gw, sn);
|
||||
#endif
|
||||
|
||||
// Start Server
|
||||
server.begin(ETHERNET_TCP_PORT);
|
||||
ETHERNET_DEBUG_PRINTLN("listening on TCP port: %d", ETHERNET_TCP_PORT);
|
||||
|
||||
@@ -24,11 +24,11 @@ RotaryInputEvent RotaryInputGPIO::poll() {
|
||||
if (!b_prec && b) { // rising edge of A
|
||||
if (a) {
|
||||
ev = RotaryInputEvent::Next;
|
||||
} else {
|
||||
} else {
|
||||
ev = RotaryInputEvent::Prev;
|
||||
}
|
||||
}
|
||||
b_prec = b;
|
||||
|
||||
return ev;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
#define BUTTON_EVENT_DOWN 6
|
||||
|
||||
class RotaryInputGPIO: public RotaryInput {
|
||||
int8_t _pin_a;
|
||||
int8_t _pin_a;
|
||||
bool _pull_a;
|
||||
int8_t _pin_b;
|
||||
bool _pull_b;
|
||||
|
||||
Reference in new issue
Block a user