Connectivity & OTA
Connectivity State Machine
stateDiagram-v2
[*] --> WiFiScan: boot
WiFiScan --> WiFiConnected: SSID found
WiFiScan --> FallbackAP: all SSIDs failed
WiFiConnected --> MQTT_TLS: PubSubClient
FallbackAP --> CaptivePortal: ap_timeout_s
FallbackAP --> WiFiScan: timeout, retry
WiFiConnected --> CellularStandby: WiFi ok
state "WiFi Path" as wp {
MQTT_TLS --> Publishing: connected
Publishing --> MQTT_TLS: reconnect
}
CellularStandby --> CellularActive: WiFi drops
CellularActive --> ModemSocket: bearer up
ModemSocket --> CellularPublishing: same MQTT and TLS over modem TCP
CellularActive --> WiFiScan: WiFi back
WiFi is always tried first. Each SSID is retried up to wifi.retries times (default 2) before moving on. If no WiFi network is in range, the fallback AP starts a captive portal for local configuration - provided its passphrase is usable, see below. Cellular activates in parallel when WiFi fails.
OTA Update (OTAUpdate)
Pull-based OTA over HTTPS. The device fetches a JSON manifest, compares semver, and streams + verifies the firmware binary.
flowchart TD
A[Trigger: periodic / cli/ota.check / cmd/ota] --> B{Transport up?}
B -->|No| R1[publish status/ota refused: no-transport]
B -->|Yes| C{manifest_url set?}
C -->|No| R2[publish status/ota refused: no-manifest-url]
C -->|Yes| D[loadCaCert]
D --> E{ca.crt on LittleFS?}
E -->|Yes| G[Use file CA]
E -->|No| F[Use PROGMEM CA bundle]
F --> H{Heap above floor?}
G --> H
H -->|No| R3[publish status/ota refused: heap-low]
H -->|Yes| I[Fetch manifest]
I --> J{Fetch ok?}
J -->|No| R4[publish status/ota refused: manifest-fetch-failed]
J -->|Yes| K{force?}
K -->|No| L{Newer version?}
L -->|No| M[publish status/ota up-to-date]
L -->|Yes| FL{Fled release, skip still running, not forced?}
K -->|Yes| FL
FL -->|Yes| R5[publish status/ota refused: fled-release]
FL -->|No| N[publish status/ota updating]
N --> O[Download .bin]
O --> P{SHA256 match?}
P -->|No| Q[publish status/ota failed]
P -->|Yes| S[Flash + reboot]
Manifest format (build/firmware.json, generated by scripts/generate_manifest.py):
{
"version": "26.11.1",
"url": "https://example.com/firmware.bin",
"sha256": "abc123..."
}
version must be three dot-separated numbers. Any other form never counts as newer, so a plain check never installs it. Only --force does.
Triggers:
- Periodic interval check (default 6 h, configurable via
ota.check_interval_s) - First check runs at boot when a network is already up
- Shell command
ota.check [--force] [url]- over serial, WebSocket, HTTP POST/api/cmd, or MQTT CLI topic<prefix>/cli/ota.check - MQTT message to
ota.cmd_topic(any payload) - defaults to<topic_prefix>/cmd/ota
Trigger over MQTT CLI (recommended - no external scripts, response on <prefix>/cli_response):
# use config manifest_url, version check
mosquitto_pub ... -t '<prefix>/cli/ota.check' -m ''
# use config manifest_url, skip version check (re-flash same or older)
mosquitto_pub ... -t '<prefix>/cli/ota.check' -m '--force'
# use override URL, version check
mosquitto_pub ... -t '<prefix>/cli/ota.check' -m 'https://example.com/firmware.json'
# use override URL, force re-flash
mosquitto_pub ... -t '<prefix>/cli/ota.check' -m '--force https://example.com/firmware.json'
Force mode bypasses isNewer() and the fled-release skip, so dev iteration does not need a FIRMWARE_VERSION bump every test cycle. Intended for development and for recovering a stuck device without version juggling.
Watchdog-safe download loop: over WiFi the body loop feeds the task watchdog on every pass and reads at most min(available, 1024) bytes, which are already buffered, so readBytes() never waits on a slow sender. A trickle keeps the loop polling and fed, and the whole body is capped at 5 minutes. The task watchdog window is 30 s. The steps before the loop are not fed while they wait: connect, TLS handshake and headers are bounded by 10 s, 10 s and 5 s of silence per header line.
TLS: loads /ca.crt from LittleFS. If the file is missing or empty, the OTA client falls back to a PROGMEM bundle of common public TLS roots baked into the firmware. The OTA path stays cert-validated even when the LittleFS data partition has been wiped.
URL scheme: an http:// manifest URL or binary url is refused unless ota.allow_insecure is set. The manifest is not signed, so over plain HTTP an on-path host can set the binary and its sha256 together. Use https:// URLs only. Over cellular every OTA fetch is TLS, so an http:// URL fails there.
The manifest URL, configured or an ota.check <url> override, and the binary url must start with https:// unless ota.allow_insecure is set. Use https:// even with it set.
| URL | Result |
|---|---|
https:// |
fetched |
http://, ota.allow_insecure set |
fetched as plain HTTP over WiFi, fails over cellular |
http://, ota.allow_insecure unset |
refused, --force or not |
| any other scheme | refused |
A refused manifest URL logs ota.check_refused reason=insecure_url url=.... A refused binary URL logs ota.phase_change from=fetch_manifest to=idle reason=insecure_url url=.... Both publish {"state":"refused","reason":"insecure-url"} on status/ota. A refused manifest URL fetches nothing. A refused binary URL comes after the manifest fetch, so no binary is fetched. The binary check runs before the fled-release skip, so it spends no try.
config.json keys:
"ota": {
"enabled": true,
"manifest_url": "https://github.com/Thesada/thesada-fw/releases/latest/download/firmware.json",
"check_interval_s": 21600,
"cmd_topic": "thesada/node/cmd/ota",
"allow_insecure": false
}
Rollback and the crash streak
A new image boots pending. It is marked valid after the first MQTT session of that boot, WiFi or cellular, or after five minutes up, whichever comes first, and logs ota.state_change from=pending to=valid reason=healthy. An image flashed over USB is never pending.
Every boot updates a crash streak, NVS namespace boot key crash_n, and the boot.reset_info line logs it as crash_streak=. At three, setup leaves the running image before the serial wait and before MQTT can confirm it. The health gate never confirms a pending image at the limit. The one exception is a pending image with no rollback target: the guard confirms it, so the bootloader cannot boot the slot just refused (At the limit).
| Reset that started this boot | Crash streak |
|---|---|
| Power-on, deep-sleep wake | cleared |
| Panic, any watchdog | +1 |
| Software restart without a marker, the heap watchdog included | +1 |
Operator restart: restart, fs.format, identity.reset, the web restart, config save, Node.restart(), the cert reboot |
held on a confirmed image, +1 on any other |
| Firmware upload, OTA apply | set to 1, whatever the installer had: they carry the operator marker into an image that boots pending, which starts its own streak (ota.crash_streak_restarted reason=install) |
MQTT budget reboot: the reboot after mqtt.reboot_after_fails failed connects, the TLS low-heap defrag reboot |
held on a confirmed image that is proven on the broker, +1 on any other |
| Brownout, external pin, SDIO, unknown | held |
A healthy confirm and a slot switch write the streak back to zero, so the image that comes up next does not start at the limit. A confirmed image that stays up one hour does too and logs ota.crash_streak_cleared reason=healthy_uptime, so restarts weeks apart never add up. A loop that crashes within the hour of every boot still reaches the limit.
An image is proven on the broker while NVS boot key proven_id names it: the slot address and the app ELF sha256. An unproven image writes the record at its first MQTT session, WiFi or cellular (ota.image_proven reason=mqtt_up). There is one record, for the last image that connected, so any other image reads unproven until it connects: a new build, the same build in the other slot, or an image that connected before another one did. A new image is confirmed at five minutes, long before its first budget reboot, so a build with broken MQTT or TLS counts its budget reboots: with the default mqtt.max_exhaust_reboots of 3, the third one reaches the limit and boots the previous slot. With a budget below 3 the reboots stop first and that image stays. A broker outage holds the streak only on the image that connected last.
At the limit
| Running image | Other slot is a target | No target |
|---|---|---|
| Pending | marked invalid, the bootloader boots the other slot: ota.state_change from=pending to=previous reason=crash_streak |
confirmed, so the bootloader cannot boot the slot just refused: ota.state_change from=pending to=valid reason=no_other_image |
| Confirmed | streak zeroed, release recorded as fled, other slot booted: ota.state_change from=valid to=other reason=crash_streak |
stays: ota.image_rollback_failed reason=no_other_image |
| Neither, or unreadable | no switch: ota.image_rollback_failed reason=state_not_valid or reason=state_unknown |
no switch |
The other slot is a target only when otadata reads it valid, the image in it verifies whole (esp_image_verify), and it is not the slot the last switch came from. An interrupted download leaves a slot valid in otadata with the new image’s descriptor already readable, so the state alone is not enough (ota.image_rollback_failed reason=image_invalid).
The image a switch boots records where it came from: NVS boot key left_id, the other slot’s address and app ELF sha256, written on arrival (ota.left_image_recorded rescue=2), so a failed switch leaves no record. Any boot of the recorded slot removes it (ota.left_image_cleared reason=slot_running): that slot was rewritten or fallen back to, so a reinstalled build is a rollback target again. Two images that both crash-loop switch once, not back and forth.
The fled-release skip
Once the boot slot is set, the fleeing image writes its own version to NVS boot key fled_ver (ota.fled_release_recorded version=...) and restarts. The update check then refuses a manifest with that version, compared as N.N.N: it logs ota.phase_change from=fetch_manifest to=idle reason=fled_release version=... age_s=... and publishes {"state":"refused","reason":"fled-release"} on status/ota. Without the skip, the older image the switch booted sees the broken build as newer and pulls it straight back at its first check, a full download and a slot rewrite per cycle.
A newer manifest version installs as usual, and a firmware upload installs without the check. ota.check --force installs the fled release and logs ota.force_reflash version=fled. A forced build that loops again is fled again. A missing or unreadable record refuses nothing.
The OTA check also records the build it installs, once the update has set the boot slot (ota.install_recorded version=...). A build that is aborted or rolled back before it confirms, by a crash, a power cut or a restart, is then refused as fled-release for 24 h by the image that comes back, instead of downloaded again at every check. A record that already names the build stays as it is, so a fled-release try keeps its age and tries. A confirmed image drops a record that names its own build (ota.install_record_cleared version=...). There is one record: an install replaces a fled record of another build, which is then no longer skipped. A firmware upload records nothing.
The refusal lasts 24 hours of skip age, and its log line ends in age_s=. Then the check installs the release again and logs ota.fled_release_retry version=... try=1. If that try does not confirm, the next check installs it once more with try=2, and the second try starts a new 24 hours. --force installs at any age and spends no try.
The skip age is uptime. RTC memory carries the unsaved seconds over a software reset or deep sleep, capped at 20 minutes, two save intervals. NVS gets the age at a boot’s first refusal and then at most every 10 minutes awake, and only while the record names another build than the running one and the 24 hours are not spent. When SNTP had synced the clock at the last save and has again, the first save of a boot also adds the time the unit was off, at most one hour per reset, and a clock behind the last save adds nothing.
A unit without a synced clock, cellular-only or with SNTP blocked, counts uptime only. A power-on loses what was not saved yet, under 10 minutes, so a boot shorter than about 10 minutes counts only the seconds before its first refusing check. With that check 15 s after power-on, a unit power-cycled every 50 minutes reaches the 24 hours about 30 hours after the switch, one power-cycled every 5 minutes about 20 days after it. Deep sleep counts the time awake, so at 30 s awake and 300 s asleep the 24 hours take about 11 days. A power-on never ends the skip.
The crash streak and the switch at the limit ship from 26.10.1. Firmware 26.10.1 and 26.10.2 count every software restart and have no one-hour clear, proven record or fled-release skip. When a switch boots an image from 26.10.2 or older, that image pulls the fled build again until the manifest changes. An image of 26.11.1 or older writes no install record, so a build it installed that did not confirm is pulled again at every check.
The left-slot record of 26.10.1 and 26.10.2 is the leaving image’s descriptor version, date and time, in NVS boot keys left_ver, left_date and left_time. Those strings come from the prebuilt IDF and match every build on the same platform, and 26.10.x never removes them, so after one switch from a confirmed image 26.10.x accepts no later rollback target. This guard never reads, writes or removes those keys.
Log events
| Event | Meaning |
|---|---|
ota.crash_streak_held reason=planned_restart or reason=broker_restart |
a restart on a confirmed image that did not count |
ota.crash_streak_counted reason=broker_restart_unproven |
a budget reboot on a confirmed image that is not the last one to connect, counted |
ota.crash_streak_cleared reason=healthy_uptime |
a confirmed image one hour up, streak written to zero |
ota.crash_streak_unread |
the streak could not be read or stored; confirm stays shut and nothing switches |
ota.image_proven reason=mqtt_up |
the proven record was written |
ota.image_proven_unrecorded reason=no_image_id, nvs or nvs_write |
the proven record was not written; the next boot tries again |
ota.left_image_recorded rescue=N |
a switch arrival recorded the slot it came from |
ota.left_image_cleared reason=slot_running |
the recorded slot booted, record removed |
ota.left_image_kept reason=nvs_write |
that record could not be removed |
ota.left_image_unrecorded reason=no_image_id, older_guard or nvs_write |
a switch arrival recorded nothing |
ota.fled_release_recorded version=... |
the fleeing image recorded its release |
ota.fled_release_unrecorded reason=nvs_write |
that write failed; the next check can pull the release once more |
ota.fled_release_unread reason=nvs |
the record could not be read; nothing is skipped |
ota.phase_change from=fetch_manifest to=idle reason=fled_release version=... age_s=... |
the check refused the fled release; age_s is the skip age |
ota.fled_release_retry version=... try=1 or try=2 |
the 24 hours ran out and the check installs the fled release again |
ota.fled_age_unsaved reason=nvs_write |
the skip age was not saved; it stays in RAM and the next save is due 10 minutes later |
ota.force_reflash version=fled |
--force installs the fled release |
ota.image_rollback_failed reason=... |
no switch: state_unknown, state_not_valid, no_other_image, image_invalid, no_description, no_image_id, nvs, nvs_write, cancel_failed. With no reason, setting the boot slot or marking the image invalid failed |
ota.rescue_left_set reason=nvs_write |
a failed switch could not clear its rescue flag |
ota.image_confirm_failed |
the IDF confirm of a pending image failed; it is retried |
MQTT Subscriptions
MQTTClient::subscribe(topic, callback) stores subscriptions and re-applies them automatically on reconnect. Callbacks are dispatched by exact topic match or trailing /# wildcard in onMessage().
MQTT CLI
The primary interface for remote management. Subscribe to <prefix>/cli/# - the topic is the command, the payload is the arguments. Response published to <prefix>/cli_response as JSON.
thesada/node/cli/sensors payload: "" -> all sensors
thesada/node/cli/sensors payload: "temp_1" -> specific sensor
thesada/node/cli/config.set payload: "mqtt.ha_discovery true"
thesada/node/cli/config.reload payload: ""
thesada/node/cli/ota.check payload: ""
thesada/node/cli/restart payload: ""
thesada/node/cli/sensors payload: "battery" -> battery only
thesada/node/cli/version payload: ""
Response format:
{"cmd": "sensors", "ok": true, "output": ["temp_1: 65.2C", "temp_2: 57.1C"]}
Any shell command works - same 30+ commands available over serial, WebSocket, HTTP, and now MQTT.
Binary write command: cli/fs.write - payload is <path>\n<content>. All three mosquitto_pub modes work (-m, -f, -s):
mosquitto_pub ... -t '<prefix>/cli/fs.write' -m '/test.txt
hello world'
The legacy cli/file.write alias still works for older clients. See Chunked File I/O for the full write contract, chunking math, and concurrency notes.
Notes:
- All CLI commands execute in
loop()via deferred processing (not inside the PubSubClient callback). This prevents keepalive timeouts on slow operations like LittleFS writes. config.setsaves to flash and reloads in place atomically.- Full config replacement: use
cli/fs.writewith path/config.json+cli/config.reload.
Dedicated triggers vs the CLI bridge
<prefix>/cmd/ota is the only legacy dedicated trigger still wired up. Set ota.cmd_topic in config.json to enable it; any payload on the configured topic triggers an OTA check. Prefer the cli/ota.check path for normal use - it calls the same code path, accepts --force, and publishes its response to <prefix>/cli_response so failures are diagnosable instead of silent.
Modules and Lua scripts can add further subscriptions via MQTTClient::subscribe() or MQTT.publish() / EventBus.subscribe().
HA MQTT Auto-Discovery
On every MQTT connect, the firmware publishes retained discovery config messages to homeassistant/sensor/<device_id>/..., keyed on the minted identity rather than device.name. Home Assistant picks these up automatically - no manual YAML sensor config needed.
<device_id> is the minted identity, and the same value fills the discovery payload’s dev.ids and each uniq_id. It is deliberately not device.name: the MQTT clientId reads that label, discovery does not, so renaming a live device no longer re-registers it in Home Assistant as a new one.
Enabled by default. Disable with mqtt.ha_discovery: false in config.json.
Each sensor publishes on its own topic with a simple value (no JSON parsing needed by HA):
<prefix>/sensor/temperature/<slug> -> "65.20"
<prefix>/sensor/current/<slug> -> "0.70"
<prefix>/sensor/power/<slug> -> "84.0"
<prefix>/sensor/battery/percent -> "100"
<prefix>/sensor/battery/voltage -> "4.19"
<prefix>/sensor/battery/charging -> "Charging"
<prefix>/sensor/wifi/rssi -> "-52"
<prefix>/sensor/wifi/ssid -> "MyNetwork"
<prefix>/sensor/wifi/ip -> "192.0.2.10"
<prefix>/status -> "online" / "offline" (LWT)
Discovery template is `` for all entities. WiFi diagnostics are entity_category: diagnostic (disabled by default in HA).
Combined JSON payloads are still published on the original topics for backwards compatibility (Lua scripts, SD logging, cellular relay).
All entities are grouped under a single HA device (device name from device.friendly_name, manufacturer “Thesada”, model “Base Node”, sw_version from firmware).
No manual YAML sensor config needed - auto-discovery handles everything.
MQTT Connection Reliability
Several mechanisms prevent connection drops after extended uptime:
Connection watchdog (10 min) - if no successful _client.loop() or publish in 10 minutes, the client force-disconnects and reconnects. Catches half-open TCP sockets that PubSubClient reports as connected.
TCP keepalive - enabled on the MQTT socket after connect via setsockopt(). Sends OS-level TCP probes after 30 s of silence, every 10 s, and declares dead after 3 failed probes. Detects NAT table timeouts and router reboots faster than MQTT-level keepalive.
Telegram HTTPS timeout - all outbound HTTPS requests (Telegram Bot API, webhooks) are capped at 10 s for the TLS handshake and 5 s for TCP connect and each write. Without this, a slow DNS lookup or TLS handshake can block loop() long enough for the MQTT keepalive (60 s) to expire.
Persistent WiFiClientSecure - the Telegram HTTPS client uses a static WiFiClientSecure instance instead of allocating a new one per request. Repeated new+delete of the ~30 KB TLS buffer fragments the heap beyond recovery on ESP32. The persistent instance avoids that and keeps Telegram reliable after extended uptime.
Boot clock floor - before the first TLS handshake, a clock that reads earlier than the floor is set forward to it. The floor is the newer of a value saved in NVS (at most once a day) and the firmware build date minus one day. The clock never moves backwards, and NTP corrects it forward later.
Verified TLS from the first connect - every MQTT connect, cold boot included, checks the broker certificate chain against /ca.crt, or the baked bundle when the file is missing. There is no insecure connect while waiting for NTP and no low-heap fallback to an unchecked session. The one unchecked case is mqtt.allow_insecure set with no CA at all, see TLS exceptions.
Certificate dates are not checked - the TLS stack on this build never checks notBefore or notAfter, at any clock value. An expired or not-yet-valid certificate is accepted on MQTT and OTA. What is checked is the chain to the CA. The clock floor is not what makes a cold-boot connect pass.
TLS low-heap reboot - mbedtls needs about 30 KB of contiguous heap for a handshake. After three failed connects in a row that resolved the broker but got no answer (rc -2), with the largest free block under 40 KB, the client reboots to defragment the heap. It logs mqtt.defrag_reboot reason=tls_low_heap and spends the same mqtt.max_exhaust_reboots budget as the exhaustion reboot below. The connection never drops to unchecked TLS.
Bounded exhaustion reboots - after mqtt.reboot_after_fails consecutive failed reconnects (default 30) the client used to call ESP.restart() indefinitely, so a misconfigured broker turned into a perpetual ~30 min reboot loop with no remote recovery path. The reboot still happens, but an NVS counter (thesada-boot namespace, keys mqtt_reboots + mqtt_rb_at) tracks consecutive exhaustion reboots and stops them once mqtt.max_exhaust_reboots (default 3) is reached. The device stays up and keeps retrying at the capped backoff so local serial/HTTP/shell remain usable. The counter clears on the first successful connect; a streak older than 6 h (RB_STALE_WINDOW_S) ages out so a one-off outage does not accumulate toward a halt.
These reboots count toward the OTA crash streak unless the running image is confirmed and proven on the broker, that is, the last image that had an MQTT session. So a long outage on that image cannot switch slots, while a new image that never connects still escapes. See Rollback and the crash streak.
Connection uptime is logged on disconnect to help diagnose patterns (consistent ~3600s = NAT timeout, random = WiFi instability).
WiFi Path (normal)
- Multi-SSID: configure a list of networks; ranked by RSSI at scan time
- Configurable retries per SSID before fallback:
wifi.retries(default 2) - NTP synced on connect (
pool.ntp.orgby default, configurable) - PubSubClient MQTT over TLS (port 8883)
- Optional minimum send interval:
mqtt.send_interval_s - Optional static IP:
wifi.static_ip/gateway/subnet/dns
"wifi": {
"retries": 2
}
Fallback AP (captive portal)
When no configured WiFi network is in range (or none are configured), the node starts a SoftAP for local configuration, in parallel with the cellular fallback.
- SSID:
<device_id>-setup(e.g.thesada-0123456789ab-setup). Built from the per-device identity, not fromdevice.name: the config label ships as a fixed string, so every unit off the line would broadcast the same SSID and a per-device join QR would be ambiguous the moment two units are in range. - Password: from
wifi.ap_password, resolved NVS-first thenconfig.json. - Captive portal: all DNS queries redirect to
192.168.4.1, and unknown HTTP requests redirect to the dashboard. Phones and laptops auto-open the config page on connect. - Timeout: after
wifi.ap_timeout_s(default 300s) the AP stops and WiFi scan retries. This cycles until WiFi connects.
The web interface is fully functional in AP mode - you can view sensors, edit config, and upload firmware.
The AP refuses to start without a usable passphrase
The AP is not a first-boot-only feature: it is raised on any WiFi failure for the device’s whole service life, and the portal behind it writes WiFi credentials. An open or publicly-keyed AP is therefore an unauthenticated console, so the firmware fails closed rather than degrading.
| Passphrase state | Result |
|---|---|
| absent or empty | refused, wifi.ap_refused reason=no_password |
| shorter than 8 characters | refused, wifi.ap_refused reason=default_or_short_password |
the shipped changeme placeholder |
refused, wifi.ap_refused reason=default_or_short_password |
| 8 or more characters, not the placeholder | AP starts |
The placeholder case is the one a length check alone would miss: changeme is exactly 8 characters. The refusal log carries the hint seed via secret.set wifi.ap_password.
A unit whose passphrase was never seeded has no local recovery path short of a serial cable, so seeding is a flash-time step - see Provisioning.
"wifi": {
"ap_password": "my-setup-pass",
"ap_timeout_s": 300
}
Cellular Fallback (LTE-M/NB-IoT)
- Activates when WiFi has been down for 60 s (in parallel with fallback AP)
- The modem only carries TCP. The MQTT session and HTTPS (OTA,
net.http) run TLS on the ESP32 over a modem socket, with the same CA (/ca.crt, else the PROGMEM bundle), host name check and client cert as WiFi - The session moves back to WiFi as soon as WiFi is up; after 60 s of stable WiFi the data context is torn down (unless
cellular.link_modeisstandby)
Incremental activation
Cellular activation runs as a phase-per-call state machine (tickActivation()), polled by CellularModule each loop, so other modules keep ticking between phases. The earlier path ran power-on through bring-up in one synchronous Cellular::begin() call - up to 30-120 s of frozen loop() during a WiFi-to-cellular failover (no MQTT keepalive, no sensor publish, no shell).
Phases: POWER_ON -> SIM -> RADIO_CFG -> REGISTER -> BEARER -> ACTIVE. MQTT then dials the modem socket on its own, with the same backoff as on WiFi. networkConnect() is split into radioConfigure, pollRegistration, and activateBearer; the synchronous version stays for the steady-state recovery path inside loop().
cellular.activation_timeout_ms (default 30 min) bounds the whole cycle. On expiry the modem is hard-reset and activation fails back to STANDBY instead of looping a wedged modem forever.
CA Certificate
The firmware looks for /ca.crt on LittleFS first and uses the contents directly for both WiFi MQTT and OTA. Place a CA cert PEM bundle as data/ca.crt and upload (pio run --target uploadfs). Multiple certs can be concatenated in one file.
If /ca.crt is missing or empty, a PROGMEM bundle baked into the firmware takes over. It covers the common public TLS roots (Let’s Encrypt + GitHub Releases) so the device stays cert-validated through a wiped data partition or a firmware-only reflash that did not include uploadfs. The flash-resident /ca.crt always wins when present, so rotation stays a filesystem operation.
Use self-signed root certificates only. Cross-signed intermediates will not work - the ESP32 TLS stack needs the actual trust anchor. The “Sectigo Root E46 signed by USERTrust ECC” cert is a cross-signed intermediate, for example; using it instead of the USERTrust ECC root causes silent OTA and TLS failures. Verify the bundle is self-signed (issuer == subject) before uploading.
The PROGMEM fallback bundle contains these public roots:
| Root | Covers |
|---|---|
| ISRG Root X1, ISRG Root X2 | Let’s Encrypt chains: the MQTT broker and the GitHub release asset host |
| DigiCert Global Root CA, G2, G3 | DigiCert chains |
| USERTrust ECC Certification Authority | Sectigo ECC chains: github.com itself, where the OTA manifest URL starts |
A host can change its issuer. Check the chain with openssl s_client -connect <host>:443 -showcerts when a backend moves.
You can also upload ca.crt at runtime via POST /api/file?path=/ca.crt&source=littlefs, or push it over MQTT with the chunked-write contract (cli/fs.write to /ca.crt), then restart. No reflash required.
AsyncTCP
AsyncTCP is not vendored - it is pulled in transitively by ESP32Async/ESPAsyncWebServer via PlatformIO’s lib deps (see platformio.ini). The pinned upstream version is whatever ESPAsyncWebServer resolves at build time. There are no local source patches applied.