Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
290445e3ad | ||
|
|
b121560b1f | ||
|
|
71ced6bf0e | ||
|
|
9d69733257 | ||
|
|
009cefcb90 | ||
|
|
c43d9ae11c | ||
|
|
cec4db4894 | ||
|
|
09f562cf1d | ||
|
|
bf4a04d6f4 | ||
|
|
83b2b2547f |
+9
-1
@@ -82,7 +82,15 @@ Before writing any new code, surface any dirty working tree and deal with it fir
|
||||
- Log message tweaks
|
||||
- Doc-only commits
|
||||
|
||||
**6. Console API Reference is mandatory.**
|
||||
**6. Every change bumps the firmware version.**
|
||||
`FW_VERSION` in `src/Version.hpp` is `MAJOR.MINOR.PATCH` and is what devices report and what OTA compares, so two different builds must never share a number.
|
||||
- **PATCH** (`2.4.0 → 2.4.1`) — bug fixes, internal changes, log/latency tweaks with no new API or behaviour contract.
|
||||
- **MINOR** (`2.4.x → 2.5.0`) — new commands, fields, topics or features, or a change to observable behaviour (timings, QoS, defaults).
|
||||
- **MAJOR** (`2.x → 3.0.0`) — breaking changes for apps/backend. **Discuss with the owner before bumping major.**
|
||||
|
||||
The bump goes in the same commit as the change (or one commit covering a batch that ships together): update `FW_VERSION`, add a line to the `VERSION HISTORY` comment above it, and set the feature catalog's "Since" column to the new version. Doc-only commits don't bump.
|
||||
|
||||
**7. Console API Reference is mandatory.**
|
||||
Any new command/API endpoint, or a change to an existing one's contents/response/errors, must be reflected in the console's live API Reference page — not just in `docs/reference/api-reference.md`. The two are separate files in separate repos and neither auto-syncs from the other; both must be updated by hand in the same change.
|
||||
|
||||
### Console API Reference location
|
||||
|
||||
@@ -81,6 +81,13 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
|
||||
| F-066 | Fix: stale retained `status/playback` — republished with the Player's real state on every MQTT (re)connect | v2.3.0 | Stable |
|
||||
| F-067 | Specific `playback.play` / `playback.stop` ACK messages (busy, invalid params, not found, load failed, bells disabled, overload…) instead of a generic "Playback command failed"; `url` no longer sticky | v2.3.0 | Stable |
|
||||
| F-068 | `loading` playback state while a melody downloads (MQTT `status/playback`), cancellable by `playback.stop`; `playback_failed` event on `control/reports` when an ACKed play never starts | v2.3.0 | Stable |
|
||||
| F-069 | RF remote disabled on Vesper Standard builds (`HAS_RF=0`) — no fielded unit has a receiver; `rf.*` now only on agnus | v2.3.0 | Stable |
|
||||
| F-070 | Richer crash reports — coredump backtrace + ELF SHA, abort() reason string, and last pre-crash heap/uptime snapshot in `boot_report` and the SD boot log | v2.3.0 | Stable |
|
||||
| F-071 | MQTT self-recovery — single supervisor task replaces timer/task chain, wedge detection (stuck connect, missing heartbeat PUBACK), LWT payload fix, `mqtt.status` diagnostics | v2.4.0 | Stable |
|
||||
| F-072 | Lower status/reply latency — QoS 0 for non-critical MQTT topics; WiFi modem sleep disabled | v2.4.0 | Stable |
|
||||
| F-073 | Confirmed delivery for `status/playback` + `control/reports` (QoS 1, PUBACK tracked, reset + republish/resend); AsyncMqttClient vendored + patched; all dependencies pinned | v2.4.0 | Stable |
|
||||
| F-074 | Fix: `mode: "infinite"` no longer flips status playing/paused every ~0.5 s | v2.4.0 | Stable |
|
||||
| F-075 | Play/stop command replies no longer wait for telemetry SD writes (deferred to TelemetryTask) | v2.4.1 | Stable |
|
||||
|
||||
---
|
||||
|
||||
@@ -1340,3 +1347,222 @@ one download can be pending.
|
||||
Verified: `pio run -e vesper-std-v1`, `-e agnus-v1` and `-e bespoke-rs485-v1` build clean.
|
||||
|
||||
Subsystem: `src/Player/Player.hpp`, `src/Player/Player.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.cpp`, `src/Communication/CommandBus/LegacyResponseAdapter.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-069 — RF remote disabled on Vesper Standard
|
||||
|
||||
`variants/vesper-std.hpp` had `HAS_RF 1`, so every Vesper Standard build started the RF task on
|
||||
GPIO 22 and registered `rf.set_slot` / `rf.clear_slot` / `rf.get_slots` / `rf.enable` — but no Vesper
|
||||
Standard unit in the field has an RF receiver fitted (confirmed with the owner, 2026-09-29). Nothing
|
||||
could ever trigger, so the code only cost an idle task and flash.
|
||||
|
||||
Now `HAS_RF 0` for `vesper-std-v1` (same as `bespoke-rs485-v1`); `RF_RX_PIN` is left defined for a future
|
||||
RF-equipped revision. Effect: no RF task, and `rf.*` commands return `Unknown command: rf.…` on this
|
||||
build. Agnus keeps RF. `status/playback` `source: "rf"` can therefore only appear on agnus.
|
||||
|
||||
Verified: `pio run -e vesper-std-v1` builds clean.
|
||||
|
||||
Subsystem: `variants/vesper-std.hpp`
|
||||
|
||||
---
|
||||
|
||||
### F-070 — Richer crash reports: backtrace, abort reason, pre-crash snapshot
|
||||
|
||||
**Why.** Crashes kept arriving on the console as `task async_tcp, PC 0x40083ed5, cause 29, vaddr 0x0`.
|
||||
That PC is `panic_abort()` (IDF `panic.c:408`), which *deliberately* writes to address 0 to halt the
|
||||
chip, so every `abort()` looks identical no matter what caused it (see F-055's note on this). The
|
||||
actual reason, and the call chain that led to it, were only ever on the serial port.
|
||||
|
||||
**What's added.**
|
||||
|
||||
1. **Backtrace + ELF SHA from the coredump** (`Telemetry::captureCrashReport()`). The coredump summary
|
||||
already carried `exc_bt_info` (up to 16 PCs) and the crashing app's ELF SHA-256 prefix; they're now
|
||||
read and reported. For an `abort()` the first 2–4 frames are the abort machinery (`panic_abort`,
|
||||
`esp_system_abort`, `abort`, `std::terminate`…); the frames after that are the real call site.
|
||||
Also logged at boot in the same `0x… 0x…` format as the serial panic output, ready for `addr2line`.
|
||||
2. **Abort reason string** (`src/Telemetry/CrashBreadcrumbs.cpp`). `platformio.ini` links with
|
||||
`-Wl,--wrap=esp_system_abort`, so every abort path in this SDK (`abort()`, `assert`, `configASSERT`,
|
||||
the FreeRTOS stack-overflow hook, stack-smashing protection) passes through
|
||||
`__wrap_esp_system_abort()` first. It copies the message (≤159 chars) into `RTC_NOINIT` memory and
|
||||
hands off to the real function. Typical values: `abort() was called at PC 0x400d1234 on core 0`
|
||||
(that PC is `abort()`'s caller; decode it), `assert failed: tcp_update_rcv_ann_wnd tcp.c:951 (...)`,
|
||||
`***ERROR*** A stack overflow in task async_tcp has been detected.` The wrapper is IRAM-only, copies
|
||||
bytes by hand, and takes no locks, since it can run with the heap lock held or the cache disabled.
|
||||
3. **Pre-crash snapshot.** TelemetryTask writes `millis()`, free heap, largest free block and the
|
||||
boot's minimum-ever free heap into the same RTC block every second, regardless of the OTA pause
|
||||
flag. Enough to tell "heap exhaustion again" (F-055) apart from a genuine bug.
|
||||
|
||||
RTC memory survives panic/watchdog/software resets but not power-on or brownout; magic words guard
|
||||
against garbage. `CrashBreadcrumbs::consume()` runs once in `Telemetry::begin()` and clears the block;
|
||||
the result is kept only when `isFaultReset()`, so a clean reboot/OTA never reports the previous boot's
|
||||
snapshot.
|
||||
|
||||
**Where it shows up.** MQTT `boot_report` (`system/info`) and each SD boot-log entry
|
||||
(`telemetry.get_boot_history`), same shape in both, built by `Telemetry::writeCrashJson()` /
|
||||
`writePreCrashJson()`:
|
||||
|
||||
```json
|
||||
"crash": {
|
||||
"task": "async_tcp", "pc": 1074282197, "exc_cause": 29, "exc_vaddr": 0,
|
||||
"backtrace": [1074282194, 1074340312, 1074348122, 1074606712],
|
||||
"backtrace_corrupted": false,
|
||||
"elf_sha256": "3f9a1c0be7d2a441"
|
||||
},
|
||||
"pre_crash": {
|
||||
"uptime_ms": 5412000, "free_heap": 21480, "largest_block": 9716, "min_free_heap": 18112,
|
||||
"abort_msg": "abort() was called at PC 0x400d8a3f on core 0"
|
||||
}
|
||||
```
|
||||
|
||||
All new `crash` keys are additive. `pre_crash` is independent of `crash`: it can appear without a
|
||||
coredump (e.g. a task-watchdog reset whose dump failed), and `abort_msg` is omitted when the reset
|
||||
wasn't an abort (a real hardware exception, a watchdog).
|
||||
|
||||
**Decoding.** `elf_sha256` is the first 16 hex chars of the SHA-256 of the crashing build's
|
||||
`firmware.elf`. Keep each release's `.elf`: `xtensa-esp32-elf-addr2line -pfiaC -e firmware.elf <pc> <backtrace...> <PC from abort_msg>`.
|
||||
|
||||
Verified: `pio run -e vesper-std-v1`, `-e agnus-v1` and `-e bespoke-rs485-v1` build clean; `objdump`
|
||||
confirms `abort()` now calls `__wrap_esp_system_abort` (IRAM) and the breadcrumb block lives in RTC slow
|
||||
memory (`0x5000xxxx`). Not yet exercised with a deliberate crash on hardware.
|
||||
|
||||
Subsystem: `src/Telemetry/CrashBreadcrumbs.hpp`, `src/Telemetry/CrashBreadcrumbs.cpp`, `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `platformio.ini`
|
||||
|
||||
---
|
||||
|
||||
### F-071 — MQTT self-recovery and `mqtt.status`
|
||||
|
||||
**Incident.** A device that had been up for days stopped talking MQTT mid-session: the cloud console
|
||||
saw it offline, pings and commands went unanswered, but the local WebSocket app kept working, and full
|
||||
logs showed no errors. The last thing on `status/heartbeat` was a garbage payload.
|
||||
|
||||
**Root causes found in `MQTTDriver`:**
|
||||
|
||||
1. **The LWT payload was a dangling pointer.** `AsyncMqttClient::setWill()` stores the raw `const char*`;
|
||||
`begin()` passed `.c_str()` of a local `String`. Every later CONNECT carried whatever was in that freed
|
||||
heap block as the Will, so on an unclean drop the broker published garbage to `status/heartbeat` (retained).
|
||||
The garbage seen in the incident was the broker announcing that the connection had died. Now kept in the
|
||||
`_willPayload` member.
|
||||
2. **The reconnect chain could die silently.** Reconnect, network stabilisation and heartbeat were
|
||||
FreeRTOS timers whose callbacks each `xTaskCreate()`d a short-lived 4 KB task, with the return value
|
||||
ignored. The reconnect timer is one-shot, so a single failed allocation (fragmented heap after days of
|
||||
uptime) ended reconnection until reboot, and nothing was logged afterwards. A reconnect that fired while
|
||||
WiFi was briefly down also gave up without rescheduling and waited for a network callback that might never come.
|
||||
3. **AsyncMqttClient can wedge without telling anyone.** It ignores `AsyncClient::connect()`'s return value
|
||||
(lwIP out of PCBs leaves it in CONNECTING forever), and a failed `tcp_close` never fires onDisconnect.
|
||||
In both cases every later `connect()` is a silent no-op.
|
||||
|
||||
**What changed.** One persistent supervisor task (`mqttSup`, allocated at boot, never freed) owns
|
||||
connect/reconnect with backoff (5 s ×3, then doubling, **now capped at 60 s instead of 5 min**), the 2 s
|
||||
network stabilisation (it polls `WiFi.status()` itself, so it doesn't depend on Networking callbacks), the
|
||||
30 s heartbeat, and wedge detection. It forces a reset (`disconnect(true)` + normal reconnect) when:
|
||||
|
||||
- a connect attempt gets neither CONNACK nor a disconnect callback within 30 s (`"connect attempt stuck"`), or
|
||||
- the heartbeat's PUBACK is still missing 20 s after it was sent (`"heartbeat PUBACK timeout"`): a half-open
|
||||
socket or stalled send queue while the library still says CONNECTED. The heartbeat stays QoS 1 for this
|
||||
reason. With the `heartbeat` topic switch off, this probe is off too. (F-073 adds the same check, 8 s,
|
||||
for playback and reports.)
|
||||
|
||||
**`mqtt.status`** (new command, all transports) returns connect/disconnect counters, last disconnect reason
|
||||
and age, forced-reset count/reason/age, WiFi state and free heap. If a device goes cloud-silent again, send
|
||||
it over WebSocket: `forced_resets > 0` means self-recovery is firing, `connected:true` while the cloud sees
|
||||
it offline points at the broker/backend side.
|
||||
|
||||
Not covered: if the broker is reachable but rejects the device (auth), the device keeps retrying at the
|
||||
60 s cap, which is visible in `mqtt.status` as climbing `reconnect_attempts`.
|
||||
|
||||
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp/.cpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp/.cpp`
|
||||
|
||||
### F-072 — Lower status/reply latency (QoS 0, WiFi sleep off)
|
||||
|
||||
**Symptom.** Playback status and command replies usually took 1–2 s to reach the apps, and MQTT sometimes 3–5 s+.
|
||||
|
||||
**Why MQTT was slow.** This AsyncMqttClient build sends its outbound queue strictly in order and holds every
|
||||
later packet until a QoS 1 PUBACK arrives. `_onPubAck()` releases the packet but doesn't restart the queue,
|
||||
so the next packet waits for the next lwIP poll (~500 ms). Everything the board published was QoS 1
|
||||
(acks, playback, alerts, info, reports, and log lines), so a play command queued playback + ack + several
|
||||
log lines, each costing a round trip plus up to 500 ms. The PUBACK the board owes the broker for the incoming
|
||||
command waited in the same queue. With `cleanSession=true` on both the device and the backend
|
||||
(`backend/mqtt/client.py`), QoS 1 never bought redelivery: unacked packets are dropped on reconnect either way.
|
||||
|
||||
**Change.** Everything is published at QoS 0 except the heartbeat (QoS 1, see F-071). *Amended by F-073:
|
||||
`status/playback` and `control/reports` went back to QoS 1, with PUBACK tracking.* Topics, retain flags
|
||||
and payloads are unchanged. Subscribers receive at min(publish QoS, subscription QoS), so they now get QoS 0
|
||||
delivery, which changes nothing with clean sessions.
|
||||
|
||||
**WiFi modem sleep off.** Arduino-ESP32 defaults to `WIFI_PS_MIN_MODEM`: the radio dozes between AP beacons
|
||||
and inbound packets wait for the next DTIM (100 ms to 1 s+ depending on the AP). This affects WebSocket and
|
||||
MQTT equally. `Networking::onWiFiConnected()` now calls `WiFi.setSleep(false)` on every connect. The device is
|
||||
mains powered, so the extra ~80 mA doesn't matter.
|
||||
|
||||
Subsystem: `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Logging/Logging.cpp`, `src/Networking/Networking.cpp`
|
||||
|
||||
### F-073 — Confirmed delivery for playback and reports; pinned dependencies
|
||||
|
||||
**Why.** F-072 moved everything except the heartbeat to QoS 0 for speed. Playback state is what the apps act
|
||||
on, so it must not get lost. QoS 0 can only lose a message in one situation: the connection has silently died
|
||||
but the device hasn't noticed yet. Plain QoS 1 doesn't save that message either — with `cleanSession=true` on
|
||||
both ends, AsyncMqttClient drops unacked packets on reconnect. Before this change, recovery depended on the
|
||||
20 s heartbeat probe plus the reconnect republish, so the app could show stale state for up to ~50 s.
|
||||
|
||||
**What changed.**
|
||||
|
||||
1. **`MQTTDriver::publishConfirmed()`** publishes at QoS 1 and records the packet ID with an 8 s deadline
|
||||
(heartbeat: 20 s). `onMqttPublish()` clears it on PUBACK. Publish and registration happen under one
|
||||
recursive mutex, because the PUBACK can arrive on the async_tcp task before `publish()` returns. A missed
|
||||
deadline makes the supervisor force-reset the connection. Up to 8 entries are tracked.
|
||||
2. **`status/playback`** uses it with no resend: on every connect `CommunicationRouter` already republishes
|
||||
the Player's *current* snapshot, and resending the old message would overwrite fresh retained state.
|
||||
Worst case for a lost transition is now ~8 s + reconnect, then the app gets the correct state.
|
||||
3. **`control/reports`** (`playback_failed`, `bell_overload`) uses it with resend: unconfirmed reports
|
||||
(newest 4) are republished right after the next CONNACK. Counted in `mqtt.status` as `resent_messages`.
|
||||
Reports raised while already disconnected are still dropped.
|
||||
4. **AsyncMqttClient vendored into `lib/AsyncMqttClient`** (upstream commit `3d93fc7`) and patched:
|
||||
`_onPubAck()`/`_onPubComp()` now call `_handleQueue()`. Upstream released the packet but waited for the
|
||||
next lwIP poll (~500 ms) to send the next one, so every QoS 1 message used to delay what was behind it by
|
||||
RTT + up to 500 ms; now it's just the RTT. Patches are marked `[vesper patch]`; see `VENDORED.md`.
|
||||
5. **Every dependency pinned to an exact version** in `platformio.ini`, including the platform
|
||||
(`espressif32 @ 6.12.0` = Arduino core 2.0.17). Git libraries (`ESPAsyncWebServer`, `AsyncTCP`) are pinned
|
||||
to the commits that were already being built. Nothing changes on a clean build unless a pin is edited in a
|
||||
commit. Verified by deleting `.pio/libdeps` and rebuilding: the same AsyncTCP (`3.3.2+sha.ef448a8`) and the
|
||||
vendored AsyncMqttClient are used.
|
||||
6. **Removed `board_build.cmake_extra_args`** (timer stack 4096). It only affects ESP-IDF framework builds;
|
||||
the Arduino SDK is precompiled with `CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048`, so it never did
|
||||
anything. Replaced by a comment: timer callbacks must only set flags or notify tasks.
|
||||
7. **WiFi and NTP timer callbacks retry** if `xTaskCreate()` fails (re-arm their one-shot timer), instead
|
||||
of silently ending the WiFi reconnect chain / skipping the NTP sync. Same failure mode as F-071.
|
||||
|
||||
Subsystem: `lib/AsyncMqttClient/`, `platformio.ini`, `src/Communication/Drivers/MQTTDriver/`,
|
||||
`src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Networking/Networking.cpp`, `src/main.cpp`
|
||||
|
||||
### F-074 — Fix status flicker in `mode: "infinite"`
|
||||
|
||||
**Symptom.** Found while measuring latency on hardware (2026-10-15): during a `playback.play` with
|
||||
`mode: "infinite"`, the device broadcast `paused` → `playing` → `paused` … about twice a second for the whole
|
||||
melody, on WebSocket and as retained MQTT `status/playback` messages. The bells kept ringing.
|
||||
|
||||
**Cause.** `"infinite"` maps to `continuous_loop=true, segment_duration=0`. `Player::timeToPause()` only
|
||||
checked `continuous_loop`, so with a 0 ms segment every duration-timer tick paused, and since
|
||||
`pause_duration` was also 0, the next tick resumed. The same happened for a v1 request with
|
||||
`continuous_loop: true` and no `segment_duration`.
|
||||
|
||||
**Fix.** `timeToPause()` also requires `segment_duration > 0`: zero means "no segments". `"interval"` already
|
||||
rejects `duration: 0`, so no valid segmented mode is affected.
|
||||
|
||||
Subsystem: `src/Player/Player.cpp`
|
||||
|
||||
### F-075 — Telemetry SD writes deferred off the command path
|
||||
|
||||
**Symptom.** Measured on hardware (2026-10-15): the `playback.play`/`playback.stop` reply arrived 50–100 ms
|
||||
after the status broadcast even with serial logging off. Between the two, the command handler wrote to the SD
|
||||
card: `Telemetry::recordPlayback()` (play → `/telemetry_runtime.json`) and `saveStrikeCounters()` (stop →
|
||||
`/telemetry_data.json`), both inline in the async_tcp task that also has to send the reply.
|
||||
|
||||
**Change.** Both now set a pending flag and notify `TelemetryTask`, which does the write within milliseconds
|
||||
(`processPendingSaves()`). The task waits on a notification instead of a plain 1 s delay, but the periodic
|
||||
work keeps its 1 s cadence, since `checkBellLoads()` decays bell loads once per call. Pending writes are
|
||||
held while telemetry is paused for OTA and done right after `resume()`. Before the task exists (early boot)
|
||||
`saveStrikeCounters()` still writes synchronously. Repeated requests before the write happens collapse into
|
||||
one write of the latest values.
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`
|
||||
|
||||
@@ -65,7 +65,7 @@ Handlers are only registered when their dependencies exist on the build:
|
||||
|---|---|---|
|
||||
| `SystemHandler` (`ping`, `identify`, `system.*`) | RTC-less builds (`HAS_RTC=0`: agnus, agnus-mini) | `Unknown command` (HTTP `GET /api/ping` still works) |
|
||||
| `ClockHandler` (`clock.*`) | RTC-less builds | `Unknown command` |
|
||||
| `RFRemoteHandler` (`rf.*`) | builds without RF (`HAS_RF=0`: bespoke-rs485) | `Unknown command` |
|
||||
| `RFRemoteHandler` (`rf.*`) | builds without RF (`HAS_RF=0`: vesper-std, bespoke-rs485 — only agnus has it) | `Unknown command` |
|
||||
| `FileHandler` (`files.*`) | builds with no FileManager | `Unknown command` |
|
||||
|
||||
---
|
||||
@@ -80,9 +80,9 @@ MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_to
|
||||
| MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited |
|
||||
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | `bell_overload`, `playback_failed` — not retained |
|
||||
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT |
|
||||
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions |
|
||||
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events |
|
||||
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device events (boot report) |
|
||||
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 (confirmed) | Playback transitions |
|
||||
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 0 | Subsystem state-change events |
|
||||
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 0 | Discrete device events (boot report) |
|
||||
| MQTT | `vesper/{device_id}/system/logs` | Outbound, QoS 0 | Mirrors serial log stream |
|
||||
| MQTT | `vesper/{device_id}/system/metrics` | Outbound, QoS 0 | Structured telemetry every 5 min |
|
||||
| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Send `identify` on connect |
|
||||
@@ -731,7 +731,7 @@ Returns `data: { "deleted": 4 }`. Error: `SD card not available on this device`.
|
||||
|
||||
---
|
||||
|
||||
## RF Remote Namespace — `RFRemoteHandler` (HAS_RF builds only)
|
||||
## RF Remote Namespace — `RFRemoteHandler` (HAS_RF builds only — agnus)
|
||||
|
||||
Up to 16 slots, each binding one 433 MHz code to a playback action. Slots are blank by default. Stored in NVS namespace `rf`.
|
||||
|
||||
@@ -821,6 +821,12 @@ Returns `message: "MQTT enabled and saved"` / `"MQTT disabled and saved"`. Error
|
||||
|
||||
Returns `data: { "enabled", "host", "port", "user", "use_ssl" }` (never the password).
|
||||
|
||||
### `mqtt.status`
|
||||
|
||||
Connection health since boot — works on every transport, so it's the command to send over WebSocket when the cloud shows a device offline but the local app still works.
|
||||
Returns `data: { "enabled", "connected", "connected_for_ms", "connects", "disconnects", "reconnect_attempts", "last_disconnect_reason", "last_disconnect_ago_ms", "forced_resets", "last_forced_reset_reason", "last_forced_reset_ago_ms", "resent_messages", "wifi_connected", "free_heap" }`.
|
||||
`*_ago_ms` and `connected_for_ms` are `0` when the event never happened / not connected. `last_forced_reset_reason` is `"connect attempt stuck"`, `"heartbeat PUBACK timeout"`, `"playback PUBACK timeout"` or `"report PUBACK timeout"` (empty if self-recovery never fired). `resent_messages` counts `control/reports` messages republished after a reconnect because their PUBACK never came. No errors.
|
||||
|
||||
### `mqtt.get_topics`
|
||||
|
||||
Returns `data: { "command", "heartbeat", "playback", "reports", "alerts", "info", "logs", "metrics" }` (bools).
|
||||
@@ -875,12 +881,14 @@ Published without a request, on the v2 topic set. Full field-level reference: [m
|
||||
| `vesper/{id}/status/heartbeat` | Every 30s (+ LWT on unclean disconnect) | 1 | yes | `heartbeat` |
|
||||
| `vesper/{id}/status/playback` | On playback transition | 1 | yes | `playback` |
|
||||
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 1 | no | `reports` |
|
||||
| `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` |
|
||||
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 1 | yes | `info` |
|
||||
| `vesper/{id}/system/alerts` | On subsystem state change only | 0 | yes, until cleared | `alerts` |
|
||||
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 0 | yes | `info` |
|
||||
| `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` |
|
||||
| `vesper/{id}/system/metrics` | Every 5 min | 0 | no | `metrics` |
|
||||
|
||||
`control/ack` carries only replies (it is not an event topic).
|
||||
`control/ack` carries only replies (it is not an event topic). Replies are published at QoS 0.
|
||||
|
||||
QoS 1 is used only for the heartbeat, `status/playback` and `control/reports`, and the firmware tracks their PUBACKs: a missing one makes the device reset the connection, republish the current playback state, and resend unconfirmed reports. Everything else is QoS 0 — see F-071/F-073 in the feature catalog.
|
||||
|
||||
---
|
||||
|
||||
@@ -957,4 +965,4 @@ When `v` is `1` (or omitted on MQTT/WebSocket/UART), `LegacyAdapter` rewrites `c
|
||||
| `mqtt` | `enable`, `disable`, `get_config`, `get_topics`, `set_topics` |
|
||||
| `telemetry` | `get_strikes`, `reset_strikes`, `get_loads`, `set_max_loads`, `set_guard_enabled`, `get_metrics`, `reset_metrics`, `get_boot_history`, `get_diagnostics`, `reset_boot_data` |
|
||||
| `bells` | `enable`, `disable`, `get_config` |
|
||||
| `rf` | `set_slot`, `clear_slot`, `get_slots`, `enable` *(HAS_RF builds only)* |
|
||||
| `rf` | `set_slot`, `clear_slot`, `get_slots`, `enable` *(HAS_RF builds only — agnus)* |
|
||||
|
||||
@@ -14,12 +14,12 @@ Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but no
|
||||
| Topic | Direction | QoS | Retained | Switch | Purpose |
|
||||
|-------|-----------|-----|----------|--------|---------|
|
||||
| `vesper/{id}/control/command` | Inbound | 1 | no | `command` | Commands from server/app — board only ever receives here |
|
||||
| `vesper/{id}/control/ack` | Outbound | 1 | no | `command` | Replies to commands **only** — strictly request/response |
|
||||
| `vesper/{id}/control/ack` | Outbound | 0 | no | `command` | Replies to commands **only** — strictly request/response |
|
||||
| `vesper/{id}/control/reports` | Outbound | 1 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
|
||||
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | `heartbeat` | Periodic liveness + state signal. Also carries LWT. |
|
||||
| `vesper/{id}/status/playback` | Outbound | 1 | yes | `playback` | Playback transitions only |
|
||||
| `vesper/{id}/system/alerts` | Outbound | 1 | yes, until cleared | `alerts` | Subsystem state-change events |
|
||||
| `vesper/{id}/system/info` | Outbound | 1 | yes | `info` | Discrete device state events (boot report, etc.) |
|
||||
| `vesper/{id}/system/alerts` | Outbound | 0 | yes, until cleared | `alerts` | Subsystem state-change events |
|
||||
| `vesper/{id}/system/info` | Outbound | 0 | yes | `info` | Discrete device state events (boot report, etc.) |
|
||||
| `vesper/{id}/system/logs` | Outbound | 0 | no | `logs` | Full log stream, mirrors serial log output |
|
||||
| `vesper/{id}/system/metrics` | Outbound | 0 | no | `metrics` | Structured telemetry — fleet-health graphing |
|
||||
|
||||
@@ -85,7 +85,7 @@ to `status/heartbeat` (QoS 1, retained), overwriting the last "online" heartbeat
|
||||
|
||||
## `vesper/{id}/status/playback`
|
||||
|
||||
**QoS:** 1 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
|
||||
**QoS:** 1 (PUBACK tracked; current state republished on every reconnect) — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
|
||||
|
||||
Published by `Player::setStatus()` on every transition (not polled), **and on every MQTT connect/reconnect** with the Player's current real state — so a retained `playing` left behind by a power loss mid-melody is overwritten (normally with `idle`) as soon as the board is back. This topic — not the `control/ack` reply — is the source of truth for what the board is actually doing. Skipped (not queued) while free heap is below the publish guard.
|
||||
|
||||
@@ -151,7 +151,7 @@ On a SUCCESS play ACK the board publishes `status/playback` **before** the ACK:
|
||||
|
||||
## `vesper/{id}/control/reports`
|
||||
|
||||
**QoS:** 1 — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
|
||||
**QoS:** 1 (PUBACK tracked; resent after a reconnect if unconfirmed) — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
|
||||
|
||||
The opposite of `control/command`: unsolicited data the board sends because it needs to be read *now*. Not a reply to anything — never carries `req_id`. Not retained, since it's an event stream, not a status snapshot.
|
||||
|
||||
@@ -201,7 +201,7 @@ Like every `control/reports` event it carries no `req_id` — correlate with the
|
||||
|
||||
## `vesper/{id}/system/alerts`
|
||||
|
||||
**QoS:** 1 — **Retained:** yes, until cleared — **Switch:** `alerts` — **Trigger:** subsystem state change only
|
||||
**QoS:** 0 — **Retained:** yes, until cleared — **Switch:** `alerts` — **Trigger:** subsystem state change only
|
||||
|
||||
Published by `HealthMonitor` (via `CommunicationRouter::publishAlert()`) whenever a subsystem transitions between health states. Published once on change; not repeated until the state changes again. Silent if MQTT is not connected, or the `alerts` switch is off, at the moment of the transition. Retained so a late-connecting console (fleet webserver) immediately sees the last unresolved alert per subsystem.
|
||||
|
||||
@@ -262,7 +262,7 @@ A fault-class boot reset also publishes here — `subsystem: "System"`, e.g.:
|
||||
|
||||
## `vesper/{id}/system/info`
|
||||
|
||||
**QoS:** 1 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
|
||||
**QoS:** 0 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
|
||||
|
||||
Published for general device state changes that are not health failures and not quantitative telemetry (see `system/metrics` for that). Use this topic to update the device detail panel (e.g. boot reason) without polling.
|
||||
|
||||
@@ -284,12 +284,23 @@ Published once, the first time MQTT connects after boot (guarded, not repeated o
|
||||
"reset_reason": "PANIC",
|
||||
"is_fault": true,
|
||||
"free_heap": 187234,
|
||||
"crash": { "task": "TelemetryTask", "pc": 1074111832, "exc_cause": 1, "exc_vaddr": 0 }
|
||||
"crash": {
|
||||
"task": "async_tcp", "pc": 1074282197, "exc_cause": 29, "exc_vaddr": 0,
|
||||
"backtrace": [1074282194, 1074340312, 1074348122, 1074606712],
|
||||
"backtrace_corrupted": false,
|
||||
"elf_sha256": "3f9a1c0be7d2a441"
|
||||
},
|
||||
"pre_crash": {
|
||||
"uptime_ms": 5412000, "free_heap": 21480, "largest_block": 9716, "min_free_heap": 18112,
|
||||
"abort_msg": "abort() was called at PC 0x400d8a3f on core 0"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`crash` is present only when a coredump was found for the crash that caused this boot — omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout). A fault-class reset additionally publishes a `system/alerts` WARNING (see above) — `system/info`'s `boot_report` is published unconditionally, fault or not.
|
||||
`crash` is present only when a coredump was found for the crash that caused this boot — omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout). `backtrace` (up to 16 PCs, decimal) and `elf_sha256` (first 16 hex chars of the crashing build's ELF SHA-256) identify the call chain; decode with `addr2line` against that exact `.elf`.
|
||||
|
||||
`pre_crash` (F-070) is present only on a fault reset where RTC memory survived (not power-on/brownout): the last once-per-second heap/uptime snapshot before the reset, plus `abort_msg` when the reset came from `abort()`/`assert`/a stack-overflow check. For those resets `pc`/`exc_cause 29`/`exc_vaddr 0` are the abort mechanism itself; `abort_msg` and the later `backtrace` frames are the real cause. A fault-class reset additionally publishes a `system/alerts` WARNING (see above) — `system/info`'s `boot_report` is published unconditionally, fault or not.
|
||||
|
||||
---
|
||||
|
||||
@@ -339,7 +350,7 @@ Structured telemetry for fleet-health graphing — not consumed by the phone app
|
||||
|
||||
## `vesper/{id}/control/command` and `vesper/{id}/control/ack`
|
||||
|
||||
**QoS:** 1 — **Retained:** no — **Switch:** `command`
|
||||
**QoS:** 1 inbound (`control/command`), 0 outbound (`control/ack`) — **Retained:** no — **Switch:** `command`
|
||||
|
||||
`control/command` is read-only from the board's perspective — the board only ever receives here. `control/ack` is strictly reply-only: every message on it answers a specific request (including `pong`), and no unsolicited event is ever published there. Both support an optional `req_id` field for correlation — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#req_id-correlation).
|
||||
|
||||
|
||||
@@ -48,6 +48,8 @@ This lets a device "breathe" — a fleet-monitoring-only install with no phone a
|
||||
|
||||
- **Always optional.** A request without `req_id` gets a reply without `req_id` — this is deliberate so v1 clients and any caller not fanning requests out over a shared channel keep working unchanged.
|
||||
- **Bus-wide plumbing, MQTT-only today.** `req_id` lives on `CommandEnvelope`/`CommandResult` in the shared `CommandBus` core (see [CommandBus](../../src/Communication/CommandBus/README.md)), not bolted onto MQTT alone — the intent is that any transport where multiple logical senders share one channel (multiple devices on one broker; a future multiplexed transport) can use the same mechanism to route replies. Only `MQTTTransport` currently reads it from the request; WebSocket, HTTP and UART ignore it and their replies never carry it.
|
||||
- **Replies are never deferred.** `CommandBus::dispatch()` sends the reply synchronously, on the transport's own task, right after the handler returns — no command replies from another task/context, so `req_id` can't be lost. This includes `playback.play` when a download is needed: the ACK (`Melody download started — …`, with `req_id`) goes out immediately, and the later outcome is reported on `status/playback` (`loading` → `playing`/`idle`) and, on failure, `control/reports` `playback_failed` — neither of which carries `req_id` (match by `pid`).
|
||||
- **When no reply arrives at all:** the MQTT heap guard drops incoming commands silently under critical heap pressure, and a reply is dropped if the `command` switch is off or the broker link is down at reply time. A client should still time out.
|
||||
- **No access control yet.** Any caller can set any `req_id` today. If needed later, safeguards (e.g. restricting who may set one, or validating format) can be added without a wire-format change.
|
||||
|
||||
## Malformed Input
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2021 Marvin Roger
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,33 @@
|
||||
# AsyncMqttClient (vendored, patched)
|
||||
|
||||
This is a copy of the library kept in the repo, not downloaded at build time.
|
||||
PlatformIO builds it from `lib/` automatically. Do not add it back to `lib_deps`.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Upstream | https://github.com/marvinroger/async-mqtt-client |
|
||||
| Commit | `3d93fc7f662e65366f8e2b0d88b108f874f035b9` (2024-09-25, "Merge pull request #310") |
|
||||
| Copied | `src/`, `LICENSE`, `library.json` (dependencies removed — AsyncTCP comes from `lib_deps`) |
|
||||
| Version | `0.9.0+vesper.1` |
|
||||
|
||||
## Why vendored
|
||||
|
||||
1. We patch it (below).
|
||||
2. It used to come from the repo's default branch with no pin, so any upstream push could change the
|
||||
firmware on the next clean build. Upstream is unmaintained, so updates are unlikely, but a copy here
|
||||
means nothing changes unless someone changes it in a commit.
|
||||
|
||||
## Patches
|
||||
|
||||
Every patched line is marked `[vesper patch]` — `grep -rn "vesper patch" lib/AsyncMqttClient`.
|
||||
|
||||
1. **`_onPubAck()` / `_onPubComp()` call `_handleQueue()`.** The outbound queue is sent strictly in order
|
||||
and stops after each QoS 1/2 PUBLISH until its acknowledgement arrives. Upstream releases the packet
|
||||
on the ack but doesn't restart sending, so the next queued packet waited for the next lwIP poll
|
||||
(~500 ms). Every QoS 1 message therefore delayed whatever was behind it by a round trip plus up to
|
||||
half a second. Now it's just the round trip. See feature catalog F-072/F-073.
|
||||
|
||||
## Updating
|
||||
|
||||
Don't just copy a newer upstream over this folder. Diff upstream against the commit above, re-apply the
|
||||
patches, bump the `+vesper.N` suffix in `library.json`, update this file, and test MQTT on hardware.
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "AsyncMqttClient",
|
||||
"keywords": "iot, home, automation, async, mqtt, client, esp8266",
|
||||
"description": "An Arduino for ESP8266 / ESP32 asynchronous MQTT client implementation",
|
||||
"authors": {
|
||||
"name": "Marvin ROGER",
|
||||
"url": "https://www.marvinroger.fr"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/marvinroger/async-mqtt-client.git"
|
||||
},
|
||||
"version": "0.9.0+vesper.1",
|
||||
"frameworks": "arduino",
|
||||
"platforms": [
|
||||
"espressif8266",
|
||||
"espressif32"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,757 @@
|
||||
#include "AsyncMqttClient.hpp"
|
||||
|
||||
AsyncMqttClient::AsyncMqttClient()
|
||||
: _client()
|
||||
, _head(nullptr)
|
||||
, _tail(nullptr)
|
||||
, _sent(0)
|
||||
, _state(DISCONNECTED)
|
||||
, _disconnectReason(AsyncMqttClientDisconnectReason::TCP_DISCONNECTED)
|
||||
, _lastClientActivity(0)
|
||||
, _lastServerActivity(0)
|
||||
, _lastPingRequestTime(0)
|
||||
, _generatedClientId{0}
|
||||
, _ip()
|
||||
, _host(nullptr)
|
||||
, _useIp(false)
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
, _secure(false)
|
||||
#endif
|
||||
, _port(0)
|
||||
, _keepAlive(15)
|
||||
, _cleanSession(true)
|
||||
, _clientId(nullptr)
|
||||
, _username(nullptr)
|
||||
, _password(nullptr)
|
||||
, _willTopic(nullptr)
|
||||
, _willPayload(nullptr)
|
||||
, _willPayloadLength(0)
|
||||
, _willQos(0)
|
||||
, _willRetain(false)
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
, _secureServerFingerprints()
|
||||
#endif
|
||||
, _onConnectUserCallbacks()
|
||||
, _onDisconnectUserCallbacks()
|
||||
, _onSubscribeUserCallbacks()
|
||||
, _onUnsubscribeUserCallbacks()
|
||||
, _onMessageUserCallbacks()
|
||||
, _onPublishUserCallbacks()
|
||||
, _parsingInformation { .bufferState = AsyncMqttClientInternals::BufferState::NONE }
|
||||
, _currentParsedPacket(nullptr)
|
||||
, _remainingLengthBufferPosition(0)
|
||||
, _remainingLengthBuffer{0}
|
||||
, _pendingPubRels() {
|
||||
_client.onConnect([](void* obj, AsyncClient* c) { (static_cast<AsyncMqttClient*>(obj))->_onConnect(); }, this);
|
||||
_client.onDisconnect([](void* obj, AsyncClient* c) { (static_cast<AsyncMqttClient*>(obj))->_onDisconnect(); }, this);
|
||||
// _client.onError([](void* obj, AsyncClient* c, int8_t error) { (static_cast<AsyncMqttClient*>(obj))->_onError(error); }, this);
|
||||
// _client.onTimeout([](void* obj, AsyncClient* c, uint32_t time) { (static_cast<AsyncMqttClient*>(obj))->_onTimeout(); }, this);
|
||||
_client.onAck([](void* obj, AsyncClient* c, size_t len, uint32_t time) { (static_cast<AsyncMqttClient*>(obj))->_onAck(len); }, this);
|
||||
_client.onData([](void* obj, AsyncClient* c, void* data, size_t len) { (static_cast<AsyncMqttClient*>(obj))->_onData(static_cast<char*>(data), len); }, this);
|
||||
_client.onPoll([](void* obj, AsyncClient* c) { (static_cast<AsyncMqttClient*>(obj))->_onPoll(); }, this);
|
||||
_client.setNoDelay(true); // send small packets immediately (PINGREQ/DISCONN are only 2 bytes)
|
||||
#ifdef ESP32
|
||||
sprintf(_generatedClientId, "esp32-%06llx", ESP.getEfuseMac());
|
||||
_xSemaphore = xSemaphoreCreateMutex();
|
||||
#elif defined(ESP8266)
|
||||
sprintf(_generatedClientId, "esp8266-%06x", ESP.getChipId());
|
||||
#endif
|
||||
_clientId = _generatedClientId;
|
||||
|
||||
setMaxTopicLength(128);
|
||||
}
|
||||
|
||||
AsyncMqttClient::~AsyncMqttClient() {
|
||||
delete _currentParsedPacket;
|
||||
delete[] _parsingInformation.topicBuffer;
|
||||
_clear();
|
||||
_pendingPubRels.clear();
|
||||
_pendingPubRels.shrink_to_fit();
|
||||
_clearQueue(false); // _clear() doesn't clear session data
|
||||
#ifdef ESP32
|
||||
vSemaphoreDelete(_xSemaphore);
|
||||
#endif
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setKeepAlive(uint16_t keepAlive) {
|
||||
_keepAlive = keepAlive;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setClientId(const char* clientId) {
|
||||
_clientId = clientId;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setCleanSession(bool cleanSession) {
|
||||
_cleanSession = cleanSession;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setMaxTopicLength(uint16_t maxTopicLength) {
|
||||
_parsingInformation.maxTopicLength = maxTopicLength;
|
||||
delete[] _parsingInformation.topicBuffer;
|
||||
_parsingInformation.topicBuffer = new char[maxTopicLength + 1];
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setCredentials(const char* username, const char* password) {
|
||||
_username = username;
|
||||
_password = password;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setWill(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length) {
|
||||
_willTopic = topic;
|
||||
_willQos = qos;
|
||||
_willRetain = retain;
|
||||
_willPayload = payload;
|
||||
_willPayloadLength = length;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setServer(IPAddress ip, uint16_t port) {
|
||||
_useIp = true;
|
||||
_ip = ip;
|
||||
_port = port;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setServer(const char* host, uint16_t port) {
|
||||
_useIp = false;
|
||||
_host = host;
|
||||
_port = port;
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
AsyncMqttClient& AsyncMqttClient::setSecure(bool secure) {
|
||||
_secure = secure;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::addServerFingerprint(const uint8_t* fingerprint) {
|
||||
std::array<uint8_t, SHA1_SIZE> newFingerprint;
|
||||
memcpy(newFingerprint.data(), fingerprint, SHA1_SIZE);
|
||||
_secureServerFingerprints.push_back(newFingerprint);
|
||||
return *this;
|
||||
}
|
||||
#endif
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onConnect(AsyncMqttClientInternals::OnConnectUserCallback callback) {
|
||||
_onConnectUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onDisconnect(AsyncMqttClientInternals::OnDisconnectUserCallback callback) {
|
||||
_onDisconnectUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onSubscribe(AsyncMqttClientInternals::OnSubscribeUserCallback callback) {
|
||||
_onSubscribeUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onUnsubscribe(AsyncMqttClientInternals::OnUnsubscribeUserCallback callback) {
|
||||
_onUnsubscribeUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onMessage(AsyncMqttClientInternals::OnMessageUserCallback callback) {
|
||||
_onMessageUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onPublish(AsyncMqttClientInternals::OnPublishUserCallback callback) {
|
||||
_onPublishUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_freeCurrentParsedPacket() {
|
||||
delete _currentParsedPacket;
|
||||
_currentParsedPacket = nullptr;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_clear() {
|
||||
_lastPingRequestTime = 0;
|
||||
_freeCurrentParsedPacket();
|
||||
_clearQueue(true); // keep session data for now
|
||||
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::NONE;
|
||||
|
||||
_client.setRxTimeout(0);
|
||||
}
|
||||
|
||||
/* TCP */
|
||||
void AsyncMqttClient::_onConnect() {
|
||||
log_i("TCP conn, MQTT CONNECT");
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
if (_secure && _secureServerFingerprints.size() > 0) {
|
||||
SSL* clientSsl = _client.getSSL();
|
||||
|
||||
bool sslFoundFingerprint = false;
|
||||
for (std::array<uint8_t, SHA1_SIZE> fingerprint : _secureServerFingerprints) {
|
||||
if (ssl_match_fingerprint(clientSsl, fingerprint.data()) == SSL_OK) {
|
||||
sslFoundFingerprint = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sslFoundFingerprint) {
|
||||
_disconnectReason = AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT;
|
||||
_client.close(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
AsyncMqttClientInternals::OutPacket* msg =
|
||||
new AsyncMqttClientInternals::ConnectOutPacket(_cleanSession,
|
||||
_username,
|
||||
_password,
|
||||
_willTopic,
|
||||
_willRetain,
|
||||
_willQos,
|
||||
_willPayload,
|
||||
_willPayloadLength,
|
||||
_keepAlive,
|
||||
_clientId);
|
||||
_addFront(msg);
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onDisconnect() {
|
||||
log_i("TCP disconn");
|
||||
_state = DISCONNECTED;
|
||||
|
||||
_clear();
|
||||
|
||||
for (auto callback : _onDisconnectUserCallbacks) callback(_disconnectReason);
|
||||
}
|
||||
|
||||
/*
|
||||
void AsyncMqttClient::_onError(int8_t error) {
|
||||
(void)error;
|
||||
// _onDisconnect called anyway
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onTimeout() {
|
||||
// disconnection will be handled by ping/pong management
|
||||
}
|
||||
*/
|
||||
|
||||
void AsyncMqttClient::_onAck(size_t len) {
|
||||
log_i("ack %u", len);
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onData(char* data, size_t len) {
|
||||
log_i("data rcv (%u)", len);
|
||||
size_t currentBytePosition = 0;
|
||||
char currentByte;
|
||||
_lastServerActivity = millis();
|
||||
do {
|
||||
switch (_parsingInformation.bufferState) {
|
||||
case AsyncMqttClientInternals::BufferState::NONE:
|
||||
currentByte = data[currentBytePosition++];
|
||||
_parsingInformation.packetType = currentByte >> 4;
|
||||
_parsingInformation.packetFlags = (currentByte << 4) >> 4;
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::REMAINING_LENGTH;
|
||||
switch (_parsingInformation.packetType) {
|
||||
case AsyncMqttClientInternals::PacketType.CONNACK:
|
||||
log_i("rcv CONNACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::ConnAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onConnAck, this, std::placeholders::_1, std::placeholders::_2));
|
||||
_client.setRxTimeout(0);
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PINGRESP:
|
||||
log_i("rcv PINGRESP");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PingRespPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPingResp, this));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.SUBACK:
|
||||
log_i("rcv SUBACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::SubAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onSubAck, this, std::placeholders::_1, std::placeholders::_2));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.UNSUBACK:
|
||||
log_i("rcv UNSUBACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::UnsubAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onUnsubAck, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBLISH:
|
||||
log_i("rcv PUBLISH");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PublishPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6, std::placeholders::_7, std::placeholders::_8, std::placeholders::_9), std::bind(&AsyncMqttClient::_onPublish, this, std::placeholders::_1, std::placeholders::_2));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBREL:
|
||||
log_i("rcv PUBREL");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubRelPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubRel, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBACK:
|
||||
log_i("rcv PUBACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubAck, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBREC:
|
||||
log_i("rcv PUBREC");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubRecPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubRec, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBCOMP:
|
||||
log_i("rcv PUBCOMP");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubCompPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubComp, this, std::placeholders::_1));
|
||||
break;
|
||||
default:
|
||||
log_i("rcv PROTOCOL VIOLATION");
|
||||
disconnect(true);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case AsyncMqttClientInternals::BufferState::REMAINING_LENGTH:
|
||||
currentByte = data[currentBytePosition++];
|
||||
_remainingLengthBuffer[_remainingLengthBufferPosition++] = currentByte;
|
||||
if (currentByte >> 7 == 0) {
|
||||
_parsingInformation.remainingLength = AsyncMqttClientInternals::Helpers::decodeRemainingLength(_remainingLengthBuffer);
|
||||
_remainingLengthBufferPosition = 0;
|
||||
if (_parsingInformation.remainingLength > 0) {
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::VARIABLE_HEADER;
|
||||
} else {
|
||||
// PINGRESP is a special case where it has no variable header, so the packet ends right here
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::NONE;
|
||||
_onPingResp();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case AsyncMqttClientInternals::BufferState::VARIABLE_HEADER:
|
||||
_currentParsedPacket->parseVariableHeader(data, len, ¤tBytePosition);
|
||||
break;
|
||||
case AsyncMqttClientInternals::BufferState::PAYLOAD:
|
||||
_currentParsedPacket->parsePayload(data, len, ¤tBytePosition);
|
||||
break;
|
||||
default:
|
||||
currentBytePosition = len;
|
||||
}
|
||||
} while (currentBytePosition != len);
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPoll() {
|
||||
// if there is too much time the client has sent a ping request without a response, disconnect client to avoid half open connections
|
||||
if (_lastPingRequestTime != 0 && (millis() - _lastPingRequestTime) >= (_keepAlive * 1000 * 2)) {
|
||||
log_w("PING t/o, disconnecting");
|
||||
disconnect(true);
|
||||
return;
|
||||
}
|
||||
// send ping to ensure the server will receive at least one message inside keepalive window
|
||||
if (_state == CONNECTED && _lastPingRequestTime == 0 && (millis() - _lastClientActivity) >= (_keepAlive * 1000 * 0.7)) {
|
||||
_sendPing();
|
||||
// send ping to verify if the server is still there (ensure this is not a half connection)
|
||||
} else if (_state == CONNECTED && _lastPingRequestTime == 0 && (millis() - _lastServerActivity) >= (_keepAlive * 1000 * 0.7)) {
|
||||
_sendPing();
|
||||
}
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
/* QUEUE */
|
||||
|
||||
void AsyncMqttClient::_insert(AsyncMqttClientInternals::OutPacket* packet) {
|
||||
// We only use this for QoS2 PUBREL so there must be a PUBLISH packet present.
|
||||
// The queue therefore cannot be empty and _head points to this PUBLISH packet.
|
||||
SEMAPHORE_TAKE();
|
||||
log_i("new insert #%u", packet->packetType());
|
||||
packet->next = _head->next;
|
||||
_head->next = packet;
|
||||
if (_head == _tail) { // PUB packet is the only one in the queue
|
||||
_tail = packet;
|
||||
}
|
||||
SEMAPHORE_GIVE();
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_addFront(AsyncMqttClientInternals::OutPacket* packet) {
|
||||
// This is only used for the CONNECT packet, to be able to establish a connection
|
||||
// before anything else. The queue can be empty or has packets from the continued session.
|
||||
// In both cases, _head should always point to the CONNECT packet afterwards.
|
||||
SEMAPHORE_TAKE();
|
||||
log_i("new front #%u", packet->packetType());
|
||||
if (_head == nullptr) {
|
||||
_tail = packet;
|
||||
} else {
|
||||
packet->next = _head;
|
||||
}
|
||||
_head = packet;
|
||||
SEMAPHORE_GIVE();
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_addBack(AsyncMqttClientInternals::OutPacket* packet) {
|
||||
SEMAPHORE_TAKE();
|
||||
log_i("new back #%u", packet->packetType());
|
||||
if (!_tail) {
|
||||
_head = packet;
|
||||
} else {
|
||||
_tail->next = packet;
|
||||
}
|
||||
_tail = packet;
|
||||
_tail->next = nullptr;
|
||||
SEMAPHORE_GIVE();
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_handleQueue() {
|
||||
SEMAPHORE_TAKE();
|
||||
// On ESP32, onDisconnect is called within the close()-call. So we need to make sure we don't lock
|
||||
bool disconnect = false;
|
||||
|
||||
while (_head && _client.space() > 10) { // safe but arbitrary value, send at least 10 bytes
|
||||
// 1. try to send
|
||||
if (_head->size() > _sent) {
|
||||
// On SSL the TCP library returns the total amount of bytes, not just the unencrypted payload length.
|
||||
// So we calculate the amount to be written ourselves.
|
||||
size_t willSend = std::min(_head->size() - _sent, _client.space());
|
||||
size_t realSent = _client.add(reinterpret_cast<const char*>(_head->data(_sent)), willSend, ASYNC_WRITE_FLAG_COPY); // flag is set by LWIP anyway, added for clarity
|
||||
_sent += willSend;
|
||||
(void)realSent;
|
||||
_client.send();
|
||||
_lastClientActivity = millis();
|
||||
_lastPingRequestTime = 0;
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
log_i("snd #%u: (tls: %u) %u/%u", _head->packetType(), realSent, _sent, _head->size());
|
||||
#else
|
||||
log_i("snd #%u: %u/%u", _head->packetType(), _sent, _head->size());
|
||||
#endif
|
||||
if (_head->packetType() == AsyncMqttClientInternals::PacketType.DISCONNECT) {
|
||||
disconnect = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. stop processing when we have to wait for an MQTT acknowledgment
|
||||
if (_head->size() == _sent) {
|
||||
if (_head->released()) {
|
||||
log_i("p #%d rel", _head->packetType());
|
||||
AsyncMqttClientInternals::OutPacket* tmp = _head;
|
||||
_head = _head->next;
|
||||
if (!_head) _tail = nullptr;
|
||||
delete tmp;
|
||||
_sent = 0;
|
||||
} else {
|
||||
break; // sending is complete however send next only after mqtt confirmation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SEMAPHORE_GIVE();
|
||||
if (disconnect) {
|
||||
log_i("snd DISCONN, disconnecting");
|
||||
_client.close();
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_clearQueue(bool keepSessionData) {
|
||||
SEMAPHORE_TAKE();
|
||||
AsyncMqttClientInternals::OutPacket* packet = _head;
|
||||
_head = nullptr;
|
||||
_tail = nullptr;
|
||||
|
||||
while (packet) {
|
||||
/* MQTT spec 3.1.2.4 Clean Session:
|
||||
* - QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
|
||||
* - QoS 2 messages which have been received from the Server, but have not been completely acknowledged.
|
||||
* + (unsent PUB messages with QoS > 0)
|
||||
*
|
||||
* To be kept:
|
||||
* - possibly first message (sent to server but not acked)
|
||||
* - PUBREC messages (QoS 2 PUB received but not acked)
|
||||
* - PUBCOMP messages (QoS 2 PUBREL received but not acked)
|
||||
*/
|
||||
if (keepSessionData) {
|
||||
if (packet->qos() > 0 && packet->size() <= _sent) { // check for qos includes check for PUB-packet type
|
||||
reinterpret_cast<AsyncMqttClientInternals::PublishOutPacket*>(packet)->setDup();
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
log_i("keep #%u", packet->packetType());
|
||||
SEMAPHORE_GIVE();
|
||||
_addBack(packet);
|
||||
SEMAPHORE_TAKE();
|
||||
packet = next;
|
||||
} else if (packet->qos() > 0 ||
|
||||
packet->packetType() == AsyncMqttClientInternals::PacketType.PUBREC ||
|
||||
packet->packetType() == AsyncMqttClientInternals::PacketType.PUBCOMP) {
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
log_i("keep #%u", packet->packetType());
|
||||
SEMAPHORE_GIVE();
|
||||
_addBack(packet);
|
||||
SEMAPHORE_TAKE();
|
||||
packet = next;
|
||||
} else {
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
delete packet;
|
||||
packet = next;
|
||||
}
|
||||
/* Delete everything when not keeping session data
|
||||
*/
|
||||
} else {
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
delete packet;
|
||||
packet = next;
|
||||
}
|
||||
}
|
||||
_sent = 0;
|
||||
SEMAPHORE_GIVE();
|
||||
}
|
||||
|
||||
/* MQTT */
|
||||
void AsyncMqttClient::_onPingResp() {
|
||||
log_i("PINGRESP");
|
||||
_freeCurrentParsedPacket();
|
||||
_lastPingRequestTime = 0;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onConnAck(bool sessionPresent, uint8_t connectReturnCode) {
|
||||
log_i("CONNACK");
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
if (!sessionPresent) {
|
||||
_pendingPubRels.clear();
|
||||
_pendingPubRels.shrink_to_fit();
|
||||
_clearQueue(false); // remove session data
|
||||
}
|
||||
|
||||
if (connectReturnCode == 0) {
|
||||
_state = CONNECTED;
|
||||
for (auto callback : _onConnectUserCallbacks) callback(sessionPresent);
|
||||
} else {
|
||||
// Callbacks are handled by the onDisconnect function which is called from the AsyncTcp lib
|
||||
_disconnectReason = static_cast<AsyncMqttClientDisconnectReason>(connectReturnCode);
|
||||
return;
|
||||
}
|
||||
_handleQueue(); // send any remaining data from continued session
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onSubAck(uint16_t packetId, char status) {
|
||||
log_i("SUBACK");
|
||||
_freeCurrentParsedPacket();
|
||||
SEMAPHORE_TAKE();
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("SUB released");
|
||||
}
|
||||
SEMAPHORE_GIVE();
|
||||
|
||||
for (auto callback : _onSubscribeUserCallbacks) callback(packetId, status);
|
||||
|
||||
_handleQueue(); // subscribe confirmed, ready to send next queued item
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onUnsubAck(uint16_t packetId) {
|
||||
log_i("UNSUBACK");
|
||||
_freeCurrentParsedPacket();
|
||||
SEMAPHORE_TAKE();
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("UNSUB released");
|
||||
}
|
||||
SEMAPHORE_GIVE();
|
||||
|
||||
for (auto callback : _onUnsubscribeUserCallbacks) callback(packetId);
|
||||
|
||||
_handleQueue(); // unsubscribe confirmed, ready to send next queued item
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onMessage(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId) {
|
||||
bool notifyPublish = true;
|
||||
|
||||
if (qos == 2) {
|
||||
for (AsyncMqttClientInternals::PendingPubRel pendingPubRel : _pendingPubRels) {
|
||||
if (pendingPubRel.packetId == packetId) {
|
||||
notifyPublish = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notifyPublish) {
|
||||
AsyncMqttClientMessageProperties properties;
|
||||
properties.qos = qos;
|
||||
properties.dup = dup;
|
||||
properties.retain = retain;
|
||||
|
||||
for (auto callback : _onMessageUserCallbacks) callback(topic, payload, properties, len, index, total);
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPublish(uint16_t packetId, uint8_t qos) {
|
||||
AsyncMqttClientInternals::PendingAck pendingAck;
|
||||
|
||||
if (qos == 1) {
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBACK;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBACK_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
_addBack(msg);
|
||||
} else if (qos == 2) {
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBREC;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBREC_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
_addBack(msg);
|
||||
|
||||
bool pubRelAwaiting = false;
|
||||
for (AsyncMqttClientInternals::PendingPubRel pendingPubRel : _pendingPubRels) {
|
||||
if (pendingPubRel.packetId == packetId) {
|
||||
pubRelAwaiting = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pubRelAwaiting) {
|
||||
AsyncMqttClientInternals::PendingPubRel pendingPubRel;
|
||||
pendingPubRel.packetId = packetId;
|
||||
_pendingPubRels.push_back(pendingPubRel);
|
||||
}
|
||||
}
|
||||
|
||||
_freeCurrentParsedPacket();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubRel(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
AsyncMqttClientInternals::PendingAck pendingAck;
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBCOMP;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBCOMP_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
_head->release();
|
||||
_insert(msg);
|
||||
log_i("PUBREC released");
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < _pendingPubRels.size(); i++) {
|
||||
if (_pendingPubRels[i].packetId == packetId) {
|
||||
_pendingPubRels.erase(_pendingPubRels.begin() + i);
|
||||
_pendingPubRels.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubAck(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("PUB released");
|
||||
}
|
||||
|
||||
for (auto callback : _onPublishUserCallbacks) callback(packetId);
|
||||
_handleQueue(); // [vesper patch] send the next queued packet now, not on the next ~500ms poll
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubRec(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
// We will only be sending 1 QoS>0 PUB message at a time (to honor message
|
||||
// ordering). So no need to store ACKS in a separate container as it will
|
||||
// be stored in the outgoing queue until a PUBCOMP comes in.
|
||||
AsyncMqttClientInternals::PendingAck pendingAck;
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBREL;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBREL_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
log_i("snd PUBREL");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("PUB released");
|
||||
}
|
||||
_insert(msg);
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubComp(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
// _head points to the PUBREL package
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("PUBREL released");
|
||||
}
|
||||
|
||||
for (auto callback : _onPublishUserCallbacks) callback(packetId);
|
||||
_handleQueue(); // [vesper patch] send the next queued packet now, not on the next ~500ms poll
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_sendPing() {
|
||||
log_i("PING");
|
||||
_lastPingRequestTime = millis();
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PingReqOutPacket;
|
||||
_addBack(msg);
|
||||
}
|
||||
|
||||
bool AsyncMqttClient::connected() const {
|
||||
return _state == CONNECTED;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::connect() {
|
||||
if (_state != DISCONNECTED) return;
|
||||
log_i("CONNECTING");
|
||||
_state = CONNECTING;
|
||||
_disconnectReason = AsyncMqttClientDisconnectReason::TCP_DISCONNECTED; // reset any previous
|
||||
|
||||
_client.setRxTimeout(_keepAlive);
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
if (_useIp) {
|
||||
_client.connect(_ip, _port, _secure);
|
||||
} else {
|
||||
_client.connect(_host, _port, _secure);
|
||||
}
|
||||
#else
|
||||
if (_useIp) {
|
||||
_client.connect(_ip, _port);
|
||||
} else {
|
||||
_client.connect(_host, _port);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void AsyncMqttClient::disconnect(bool force) {
|
||||
if (_state == DISCONNECTED) return;
|
||||
log_i("DISCONNECT (f:%d)", force);
|
||||
if (force) {
|
||||
_state = DISCONNECTED;
|
||||
_client.close(true);
|
||||
} else if (_state != DISCONNECTING) {
|
||||
_state = DISCONNECTING;
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::DisconnOutPacket;
|
||||
_addBack(msg);
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t AsyncMqttClient::subscribe(const char* topic, uint8_t qos) {
|
||||
if (_state != CONNECTED) return 0;
|
||||
log_i("SUBSCRIBE");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::SubscribeOutPacket(topic, qos);
|
||||
_addBack(msg);
|
||||
return msg->packetId();
|
||||
}
|
||||
|
||||
uint16_t AsyncMqttClient::unsubscribe(const char* topic) {
|
||||
if (_state != CONNECTED) return 0;
|
||||
log_i("UNSUBSCRIBE");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::UnsubscribeOutPacket(topic);
|
||||
_addBack(msg);
|
||||
return msg->packetId();
|
||||
}
|
||||
|
||||
uint16_t AsyncMqttClient::publish(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length, bool dup, uint16_t message_id) {
|
||||
if (_state != CONNECTED || GET_FREE_MEMORY() < MQTT_MIN_FREE_MEMORY) return 0;
|
||||
log_i("PUBLISH");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PublishOutPacket(topic, qos, retain, payload, length);
|
||||
_addBack(msg);
|
||||
return msg->packetId();
|
||||
}
|
||||
|
||||
bool AsyncMqttClient::clearQueue() {
|
||||
if (_state != DISCONNECTED) return false;
|
||||
_clearQueue(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
const char* AsyncMqttClient::getClientId() const {
|
||||
return _clientId;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#ifndef SRC_ASYNCMQTTCLIENT_H_
|
||||
#define SRC_ASYNCMQTTCLIENT_H_
|
||||
|
||||
#include "AsyncMqttClient.hpp"
|
||||
|
||||
#endif // SRC_ASYNCMQTTCLIENT_H_
|
||||
@@ -0,0 +1,179 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
#ifndef MQTT_MIN_FREE_MEMORY
|
||||
#define MQTT_MIN_FREE_MEMORY 4096
|
||||
#endif
|
||||
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#include <freertos/semphr.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESPAsyncTCP.h>
|
||||
#else
|
||||
#error Platform not supported
|
||||
#endif
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
#include <tcp_axtls.h>
|
||||
#define SHA1_SIZE 20
|
||||
#endif
|
||||
|
||||
#include "AsyncMqttClient/Flags.hpp"
|
||||
#include "AsyncMqttClient/ParsingInformation.hpp"
|
||||
#include "AsyncMqttClient/MessageProperties.hpp"
|
||||
#include "AsyncMqttClient/Helpers.hpp"
|
||||
#include "AsyncMqttClient/Callbacks.hpp"
|
||||
#include "AsyncMqttClient/DisconnectReasons.hpp"
|
||||
#include "AsyncMqttClient/Storage.hpp"
|
||||
|
||||
#include "AsyncMqttClient/Packets/Packet.hpp"
|
||||
#include "AsyncMqttClient/Packets/ConnAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PingRespPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/SubAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/UnsubAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PublishPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubRelPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubRecPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubCompPacket.hpp"
|
||||
|
||||
#include "AsyncMqttClient/Packets/Out/Connect.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/PingReq.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/PubAck.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Disconn.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Subscribe.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Unsubscribe.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Publish.hpp"
|
||||
|
||||
class AsyncMqttClient {
|
||||
public:
|
||||
AsyncMqttClient();
|
||||
~AsyncMqttClient();
|
||||
|
||||
AsyncMqttClient& setKeepAlive(uint16_t keepAlive);
|
||||
AsyncMqttClient& setClientId(const char* clientId);
|
||||
AsyncMqttClient& setCleanSession(bool cleanSession);
|
||||
AsyncMqttClient& setMaxTopicLength(uint16_t maxTopicLength);
|
||||
AsyncMqttClient& setCredentials(const char* username, const char* password = nullptr);
|
||||
AsyncMqttClient& setWill(const char* topic, uint8_t qos, bool retain, const char* payload = nullptr, size_t length = 0);
|
||||
AsyncMqttClient& setServer(IPAddress ip, uint16_t port);
|
||||
AsyncMqttClient& setServer(const char* host, uint16_t port);
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
AsyncMqttClient& setSecure(bool secure);
|
||||
AsyncMqttClient& addServerFingerprint(const uint8_t* fingerprint);
|
||||
#endif
|
||||
|
||||
AsyncMqttClient& onConnect(AsyncMqttClientInternals::OnConnectUserCallback callback);
|
||||
AsyncMqttClient& onDisconnect(AsyncMqttClientInternals::OnDisconnectUserCallback callback);
|
||||
AsyncMqttClient& onSubscribe(AsyncMqttClientInternals::OnSubscribeUserCallback callback);
|
||||
AsyncMqttClient& onUnsubscribe(AsyncMqttClientInternals::OnUnsubscribeUserCallback callback);
|
||||
AsyncMqttClient& onMessage(AsyncMqttClientInternals::OnMessageUserCallback callback);
|
||||
AsyncMqttClient& onPublish(AsyncMqttClientInternals::OnPublishUserCallback callback);
|
||||
|
||||
bool connected() const;
|
||||
void connect();
|
||||
void disconnect(bool force = false);
|
||||
uint16_t subscribe(const char* topic, uint8_t qos);
|
||||
uint16_t unsubscribe(const char* topic);
|
||||
uint16_t publish(const char* topic, uint8_t qos, bool retain, const char* payload = nullptr, size_t length = 0, bool dup = false, uint16_t message_id = 0);
|
||||
bool clearQueue(); // Not MQTT compliant!
|
||||
|
||||
const char* getClientId() const;
|
||||
|
||||
private:
|
||||
AsyncClient _client;
|
||||
AsyncMqttClientInternals::OutPacket* _head;
|
||||
AsyncMqttClientInternals::OutPacket* _tail;
|
||||
size_t _sent;
|
||||
enum {
|
||||
CONNECTING,
|
||||
CONNECTED,
|
||||
DISCONNECTING,
|
||||
DISCONNECTED
|
||||
} _state;
|
||||
AsyncMqttClientDisconnectReason _disconnectReason;
|
||||
uint32_t _lastClientActivity;
|
||||
uint32_t _lastServerActivity;
|
||||
uint32_t _lastPingRequestTime;
|
||||
|
||||
char _generatedClientId[18 + 1]; // esp8266-abc123 and esp32-abcdef123456
|
||||
IPAddress _ip;
|
||||
const char* _host;
|
||||
bool _useIp;
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
bool _secure;
|
||||
#endif
|
||||
uint16_t _port;
|
||||
uint16_t _keepAlive;
|
||||
bool _cleanSession;
|
||||
const char* _clientId;
|
||||
const char* _username;
|
||||
const char* _password;
|
||||
const char* _willTopic;
|
||||
const char* _willPayload;
|
||||
uint16_t _willPayloadLength;
|
||||
uint8_t _willQos;
|
||||
bool _willRetain;
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
std::vector<std::array<uint8_t, SHA1_SIZE>> _secureServerFingerprints;
|
||||
#endif
|
||||
|
||||
std::vector<AsyncMqttClientInternals::OnConnectUserCallback> _onConnectUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnDisconnectUserCallback> _onDisconnectUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnSubscribeUserCallback> _onSubscribeUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnUnsubscribeUserCallback> _onUnsubscribeUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnMessageUserCallback> _onMessageUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnPublishUserCallback> _onPublishUserCallbacks;
|
||||
|
||||
AsyncMqttClientInternals::ParsingInformation _parsingInformation;
|
||||
AsyncMqttClientInternals::Packet* _currentParsedPacket;
|
||||
uint8_t _remainingLengthBufferPosition;
|
||||
char _remainingLengthBuffer[4];
|
||||
|
||||
std::vector<AsyncMqttClientInternals::PendingPubRel> _pendingPubRels;
|
||||
|
||||
#if defined(ESP32)
|
||||
SemaphoreHandle_t _xSemaphore = nullptr;
|
||||
#elif defined(ESP8266)
|
||||
bool _xSemaphore = false;
|
||||
#endif
|
||||
|
||||
void _clear();
|
||||
void _freeCurrentParsedPacket();
|
||||
|
||||
// TCP
|
||||
void _onConnect();
|
||||
void _onDisconnect();
|
||||
// void _onError(int8_t error);
|
||||
// void _onTimeout();
|
||||
void _onAck(size_t len);
|
||||
void _onData(char* data, size_t len);
|
||||
void _onPoll();
|
||||
|
||||
// QUEUE
|
||||
void _insert(AsyncMqttClientInternals::OutPacket* packet); // for PUBREL
|
||||
void _addFront(AsyncMqttClientInternals::OutPacket* packet); // for CONNECT
|
||||
void _addBack(AsyncMqttClientInternals::OutPacket* packet); // all the rest
|
||||
void _handleQueue();
|
||||
void _clearQueue(bool keepSessionData);
|
||||
|
||||
// MQTT
|
||||
void _onPingResp();
|
||||
void _onConnAck(bool sessionPresent, uint8_t connectReturnCode);
|
||||
void _onSubAck(uint16_t packetId, char status);
|
||||
void _onUnsubAck(uint16_t packetId);
|
||||
void _onMessage(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId);
|
||||
void _onPublish(uint16_t packetId, uint8_t qos);
|
||||
void _onPubRel(uint16_t packetId);
|
||||
void _onPubAck(uint16_t packetId);
|
||||
void _onPubRec(uint16_t packetId);
|
||||
void _onPubComp(uint16_t packetId);
|
||||
|
||||
void _sendPing();
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "DisconnectReasons.hpp"
|
||||
#include "MessageProperties.hpp"
|
||||
#include "Errors.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
// user callbacks
|
||||
typedef std::function<void(bool sessionPresent)> OnConnectUserCallback;
|
||||
typedef std::function<void(AsyncMqttClientDisconnectReason reason)> OnDisconnectUserCallback;
|
||||
typedef std::function<void(uint16_t packetId, uint8_t qos)> OnSubscribeUserCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnUnsubscribeUserCallback;
|
||||
typedef std::function<void(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total)> OnMessageUserCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPublishUserCallback;
|
||||
typedef std::function<void(uint16_t packetId, AsyncMqttClientError error)> OnErrorUserCallback;
|
||||
|
||||
// internal callbacks
|
||||
typedef std::function<void(bool sessionPresent, uint8_t connectReturnCode)> OnConnAckInternalCallback;
|
||||
typedef std::function<void()> OnPingRespInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId, char status)> OnSubAckInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnUnsubAckInternalCallback;
|
||||
typedef std::function<void(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId)> OnMessageInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId, uint8_t qos)> OnPublishInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubRelInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubAckInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubRecInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubCompInternalCallback;
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
enum class AsyncMqttClientDisconnectReason : uint8_t {
|
||||
TCP_DISCONNECTED = 0,
|
||||
|
||||
MQTT_UNACCEPTABLE_PROTOCOL_VERSION = 1,
|
||||
MQTT_IDENTIFIER_REJECTED = 2,
|
||||
MQTT_SERVER_UNAVAILABLE = 3,
|
||||
MQTT_MALFORMED_CREDENTIALS = 4,
|
||||
MQTT_NOT_AUTHORIZED = 5,
|
||||
|
||||
ESP8266_NOT_ENOUGH_SPACE = 6,
|
||||
|
||||
TLS_BAD_FINGERPRINT = 7
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
enum class AsyncMqttClientError : uint8_t {
|
||||
MAX_RETRIES = 0,
|
||||
OUT_OF_MEMORY = 1
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
constexpr struct {
|
||||
const uint8_t RESERVED = 0;
|
||||
const uint8_t CONNECT = 1;
|
||||
const uint8_t CONNACK = 2;
|
||||
const uint8_t PUBLISH = 3;
|
||||
const uint8_t PUBACK = 4;
|
||||
const uint8_t PUBREC = 5;
|
||||
const uint8_t PUBREL = 6;
|
||||
const uint8_t PUBCOMP = 7;
|
||||
const uint8_t SUBSCRIBE = 8;
|
||||
const uint8_t SUBACK = 9;
|
||||
const uint8_t UNSUBSCRIBE = 10;
|
||||
const uint8_t UNSUBACK = 11;
|
||||
const uint8_t PINGREQ = 12;
|
||||
const uint8_t PINGRESP = 13;
|
||||
const uint8_t DISCONNECT = 14;
|
||||
const uint8_t RESERVED2 = 1;
|
||||
} PacketType;
|
||||
|
||||
constexpr struct {
|
||||
const uint8_t CONNECT_RESERVED = 0x00;
|
||||
const uint8_t CONNACK_RESERVED = 0x00;
|
||||
const uint8_t PUBLISH_DUP = 0x08;
|
||||
const uint8_t PUBLISH_QOS0 = 0x00;
|
||||
const uint8_t PUBLISH_QOS1 = 0x02;
|
||||
const uint8_t PUBLISH_QOS2 = 0x04;
|
||||
const uint8_t PUBLISH_QOSRESERVED = 0x06;
|
||||
const uint8_t PUBLISH_RETAIN = 0x01;
|
||||
const uint8_t PUBACK_RESERVED = 0x00;
|
||||
const uint8_t PUBREC_RESERVED = 0x00;
|
||||
const uint8_t PUBREL_RESERVED = 0x02;
|
||||
const uint8_t PUBCOMP_RESERVED = 0x00;
|
||||
const uint8_t SUBSCRIBE_RESERVED = 0x02;
|
||||
const uint8_t SUBACK_RESERVED = 0x00;
|
||||
const uint8_t UNSUBSCRIBE_RESERVED = 0x02;
|
||||
const uint8_t UNSUBACK_RESERVED = 0x00;
|
||||
const uint8_t PINGREQ_RESERVED = 0x00;
|
||||
const uint8_t PINGRESP_RESERVED = 0x00;
|
||||
const uint8_t DISCONNECT_RESERVED = 0x00;
|
||||
const uint8_t RESERVED2_RESERVED = 0x00;
|
||||
} HeaderFlag;
|
||||
|
||||
constexpr struct {
|
||||
const uint8_t USERNAME = 0x80;
|
||||
const uint8_t PASSWORD = 0x40;
|
||||
const uint8_t WILL_RETAIN = 0x20;
|
||||
const uint8_t WILL_QOS0 = 0x00;
|
||||
const uint8_t WILL_QOS1 = 0x08;
|
||||
const uint8_t WILL_QOS2 = 0x10;
|
||||
const uint8_t WILL = 0x04;
|
||||
const uint8_t CLEAN_SESSION = 0x02;
|
||||
const uint8_t RESERVED = 0x00;
|
||||
} ConnectFlag;
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class Helpers {
|
||||
public:
|
||||
static uint32_t decodeRemainingLength(char* bytes) {
|
||||
uint32_t multiplier = 1;
|
||||
uint32_t value = 0;
|
||||
uint8_t currentByte = 0;
|
||||
uint8_t encodedByte;
|
||||
do {
|
||||
encodedByte = bytes[currentByte++];
|
||||
value += (encodedByte & 127) * multiplier;
|
||||
multiplier *= 128;
|
||||
} while ((encodedByte & 128) != 0);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
static uint8_t encodeRemainingLength(uint32_t remainingLength, char* destination) {
|
||||
uint8_t currentByte = 0;
|
||||
uint8_t bytesNeeded = 0;
|
||||
|
||||
do {
|
||||
uint8_t encodedByte = remainingLength % 128;
|
||||
remainingLength /= 128;
|
||||
if (remainingLength > 0) {
|
||||
encodedByte = encodedByte | 128;
|
||||
}
|
||||
|
||||
destination[currentByte++] = encodedByte;
|
||||
bytesNeeded++;
|
||||
} while (remainingLength > 0);
|
||||
|
||||
return bytesNeeded;
|
||||
}
|
||||
};
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP32)
|
||||
#define SEMAPHORE_TAKE() xSemaphoreTake(_xSemaphore, portMAX_DELAY)
|
||||
#define SEMAPHORE_GIVE() xSemaphoreGive(_xSemaphore)
|
||||
#define GET_FREE_MEMORY() ESP.getMaxAllocHeap()
|
||||
#include <esp32-hal-log.h>
|
||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
||||
#define SEMAPHORE_TAKE(X) while (_xSemaphore) { /*ESP.wdtFeed();*/ } _xSemaphore = true
|
||||
#define SEMAPHORE_GIVE() _xSemaphore = false
|
||||
#define GET_FREE_MEMORY() ESP.getMaxFreeBlockSize()
|
||||
#if defined(DEBUG_ESP_PORT) && defined(DEBUG_ASYNC_MQTT_CLIENT)
|
||||
#define log_i(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n")
|
||||
#define log_e(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n")
|
||||
#define log_w(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n")
|
||||
#else
|
||||
#define log_i(...)
|
||||
#define log_e(...)
|
||||
#define log_w(...)
|
||||
#endif
|
||||
#else
|
||||
#pragma error "No valid architecture"
|
||||
#endif
|
||||
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
struct AsyncMqttClientMessageProperties {
|
||||
uint8_t qos;
|
||||
bool dup;
|
||||
bool retain;
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "ConnAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::ConnAckPacket;
|
||||
|
||||
ConnAckPacket::ConnAckPacket(ParsingInformation* parsingInformation, OnConnAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _sessionPresent(false)
|
||||
, _connectReturnCode(0) {
|
||||
}
|
||||
|
||||
ConnAckPacket::~ConnAckPacket() {
|
||||
}
|
||||
|
||||
void ConnAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_sessionPresent = (currentByte << 7) >> 7;
|
||||
} else {
|
||||
_connectReturnCode = currentByte;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_sessionPresent, _connectReturnCode);
|
||||
}
|
||||
}
|
||||
|
||||
void ConnAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class ConnAckPacket : public Packet {
|
||||
public:
|
||||
explicit ConnAckPacket(ParsingInformation* parsingInformation, OnConnAckInternalCallback callback);
|
||||
~ConnAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnConnAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
bool _sessionPresent;
|
||||
uint8_t _connectReturnCode;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "Connect.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::ConnectOutPacket;
|
||||
|
||||
ConnectOutPacket::ConnectOutPacket(bool cleanSession,
|
||||
const char* username,
|
||||
const char* password,
|
||||
const char* willTopic,
|
||||
bool willRetain,
|
||||
uint8_t willQos,
|
||||
const char* willPayload,
|
||||
uint16_t willPayloadLength,
|
||||
uint16_t keepAlive,
|
||||
const char* clientId) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.CONNECT;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.CONNECT_RESERVED;
|
||||
|
||||
uint16_t protocolNameLength = 4;
|
||||
char protocolNameLengthBytes[2];
|
||||
protocolNameLengthBytes[0] = protocolNameLength >> 8;
|
||||
protocolNameLengthBytes[1] = protocolNameLength & 0xFF;
|
||||
|
||||
char protocolLevel[1];
|
||||
protocolLevel[0] = 0x04;
|
||||
|
||||
char connectFlags[1];
|
||||
connectFlags[0] = 0;
|
||||
if (cleanSession) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.CLEAN_SESSION;
|
||||
if (username != nullptr) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.USERNAME;
|
||||
if (password != nullptr) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.PASSWORD;
|
||||
if (willTopic != nullptr) {
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL;
|
||||
if (willRetain) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_RETAIN;
|
||||
switch (willQos) {
|
||||
case 0:
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS0;
|
||||
break;
|
||||
case 1:
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS1;
|
||||
break;
|
||||
case 2:
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
char keepAliveBytes[2];
|
||||
keepAliveBytes[0] = keepAlive >> 8;
|
||||
keepAliveBytes[1] = keepAlive & 0xFF;
|
||||
|
||||
uint16_t clientIdLength = strlen(clientId);
|
||||
char clientIdLengthBytes[2];
|
||||
clientIdLengthBytes[0] = clientIdLength >> 8;
|
||||
clientIdLengthBytes[1] = clientIdLength & 0xFF;
|
||||
|
||||
// Optional fields
|
||||
uint16_t willTopicLength = 0;
|
||||
char willTopicLengthBytes[2];
|
||||
char willPayloadLengthBytes[2];
|
||||
if (willTopic != nullptr) {
|
||||
willTopicLength = strlen(willTopic);
|
||||
willTopicLengthBytes[0] = willTopicLength >> 8;
|
||||
willTopicLengthBytes[1] = willTopicLength & 0xFF;
|
||||
|
||||
if (willPayload != nullptr && willPayloadLength == 0) willPayloadLength = strlen(willPayload);
|
||||
|
||||
willPayloadLengthBytes[0] = willPayloadLength >> 8;
|
||||
willPayloadLengthBytes[1] = willPayloadLength & 0xFF;
|
||||
}
|
||||
|
||||
uint16_t usernameLength = 0;
|
||||
char usernameLengthBytes[2];
|
||||
if (username != nullptr) {
|
||||
usernameLength = strlen(username);
|
||||
usernameLengthBytes[0] = usernameLength >> 8;
|
||||
usernameLengthBytes[1] = usernameLength & 0xFF;
|
||||
}
|
||||
|
||||
uint16_t passwordLength = 0;
|
||||
char passwordLengthBytes[2];
|
||||
if (password != nullptr) {
|
||||
passwordLength = strlen(password);
|
||||
passwordLengthBytes[0] = passwordLength >> 8;
|
||||
passwordLengthBytes[1] = passwordLength & 0xFF;
|
||||
}
|
||||
|
||||
uint32_t remainingLength = 2 + protocolNameLength + 1 + 1 + 2 + 2 + clientIdLength; // always present
|
||||
if (willTopic != nullptr) remainingLength += 2 + willTopicLength + 2 + willPayloadLength;
|
||||
if (username != nullptr) remainingLength += 2 + usernameLength;
|
||||
if (password != nullptr) remainingLength += 2 + passwordLength;
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(remainingLength, fixedHeader + 1);
|
||||
|
||||
uint32_t neededSpace = 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += protocolNameLength;
|
||||
neededSpace += 1;
|
||||
neededSpace += 1;
|
||||
neededSpace += 2;
|
||||
neededSpace += 2;
|
||||
neededSpace += clientIdLength;
|
||||
if (willTopic != nullptr) {
|
||||
neededSpace += 2;
|
||||
neededSpace += willTopicLength;
|
||||
|
||||
neededSpace += 2;
|
||||
if (willPayload != nullptr) neededSpace += willPayloadLength;
|
||||
}
|
||||
if (username != nullptr) {
|
||||
neededSpace += 2;
|
||||
neededSpace += usernameLength;
|
||||
}
|
||||
if (password != nullptr) {
|
||||
neededSpace += 2;
|
||||
neededSpace += passwordLength;
|
||||
}
|
||||
|
||||
_data.reserve(neededSpace);
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
|
||||
_data.push_back(protocolNameLengthBytes[0]);
|
||||
_data.push_back(protocolNameLengthBytes[1]);
|
||||
|
||||
_data.push_back('M');
|
||||
_data.push_back('Q');
|
||||
_data.push_back('T');
|
||||
_data.push_back('T');
|
||||
|
||||
_data.push_back(protocolLevel[0]);
|
||||
_data.push_back(connectFlags[0]);
|
||||
_data.push_back(keepAliveBytes[0]);
|
||||
_data.push_back(keepAliveBytes[1]);
|
||||
_data.push_back(clientIdLengthBytes[0]);
|
||||
_data.push_back(clientIdLengthBytes[1]);
|
||||
|
||||
_data.insert(_data.end(), clientId, clientId + clientIdLength);
|
||||
if (willTopic != nullptr) {
|
||||
_data.insert(_data.end(), willTopicLengthBytes, willTopicLengthBytes + 2);
|
||||
_data.insert(_data.end(), willTopic, willTopic + willTopicLength);
|
||||
|
||||
_data.insert(_data.end(), willPayloadLengthBytes, willPayloadLengthBytes + 2);
|
||||
if (willPayload != nullptr) _data.insert(_data.end(), willPayload, willPayload + willPayloadLength);
|
||||
}
|
||||
if (username != nullptr) {
|
||||
_data.insert(_data.end(), usernameLengthBytes, usernameLengthBytes + 2);
|
||||
_data.insert(_data.end(), username, username + usernameLength);
|
||||
}
|
||||
if (password != nullptr) {
|
||||
_data.insert(_data.end(), passwordLengthBytes, passwordLengthBytes + 2);
|
||||
_data.insert(_data.end(), password, password + passwordLength);
|
||||
}
|
||||
}
|
||||
|
||||
const uint8_t* ConnectOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t ConnectOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <cstring> // strlen
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class ConnectOutPacket : public OutPacket {
|
||||
public:
|
||||
ConnectOutPacket(bool cleanSession,
|
||||
const char* username,
|
||||
const char* password,
|
||||
const char* willTopic,
|
||||
bool willRetain,
|
||||
uint8_t willQos,
|
||||
const char* willPayload,
|
||||
uint16_t willPayloadLength,
|
||||
uint16_t keepAlive,
|
||||
const char* clientId);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "Disconn.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::DisconnOutPacket;
|
||||
|
||||
DisconnOutPacket::DisconnOutPacket() {
|
||||
_data[0] = AsyncMqttClientInternals::PacketType.DISCONNECT;
|
||||
_data[0] = _data[0] << 4;
|
||||
_data[0] = _data[0] | AsyncMqttClientInternals::HeaderFlag.DISCONNECT_RESERVED;
|
||||
_data[1] = 0;
|
||||
}
|
||||
|
||||
const uint8_t* DisconnOutPacket::data(size_t index) const {
|
||||
return &_data[index];
|
||||
}
|
||||
|
||||
size_t DisconnOutPacket::size() const {
|
||||
return 2;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class DisconnOutPacket : public OutPacket {
|
||||
public:
|
||||
DisconnOutPacket();
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
uint8_t _data[2];
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "OutPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::OutPacket;
|
||||
|
||||
OutPacket::OutPacket()
|
||||
: next(nullptr)
|
||||
, timeout(0)
|
||||
, noTries(0)
|
||||
, _released(true)
|
||||
, _packetId(0) {}
|
||||
|
||||
OutPacket::~OutPacket() {}
|
||||
|
||||
bool OutPacket::released() const {
|
||||
return _released;
|
||||
}
|
||||
|
||||
uint8_t OutPacket::packetType() const {
|
||||
return data(0)[0] >> 4;
|
||||
}
|
||||
|
||||
uint16_t OutPacket::packetId() const {
|
||||
return _packetId;
|
||||
}
|
||||
|
||||
uint8_t OutPacket::qos() const {
|
||||
if (packetType() == AsyncMqttClientInternals::PacketType.PUBLISH) {
|
||||
return (data()[1] & 0x06) >> 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void OutPacket::release() {
|
||||
_released = true;
|
||||
}
|
||||
|
||||
uint16_t OutPacket::_nextPacketId = 0;
|
||||
|
||||
uint16_t OutPacket::_getNextPacketId() {
|
||||
if (++_nextPacketId == 0) {
|
||||
++_nextPacketId;
|
||||
}
|
||||
return _nextPacketId;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h> // uint*_t
|
||||
#include <stddef.h> // size_t
|
||||
#include <algorithm> // std::min
|
||||
|
||||
#include "../../Flags.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class OutPacket {
|
||||
public:
|
||||
OutPacket();
|
||||
virtual ~OutPacket();
|
||||
virtual const uint8_t* data(size_t index = 0) const = 0;
|
||||
virtual size_t size() const = 0;
|
||||
bool released() const;
|
||||
uint8_t packetType() const;
|
||||
uint16_t packetId() const;
|
||||
uint8_t qos() const;
|
||||
void release();
|
||||
|
||||
public:
|
||||
OutPacket* next;
|
||||
uint32_t timeout;
|
||||
uint8_t noTries;
|
||||
|
||||
protected:
|
||||
static uint16_t _getNextPacketId();
|
||||
bool _released;
|
||||
uint16_t _packetId;
|
||||
|
||||
private:
|
||||
static uint16_t _nextPacketId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "PingReq.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PingReqOutPacket;
|
||||
|
||||
PingReqOutPacket::PingReqOutPacket() {
|
||||
_data[0] = AsyncMqttClientInternals::PacketType.PINGREQ;
|
||||
_data[0] = _data[0] << 4;
|
||||
_data[0] = _data[0] | AsyncMqttClientInternals::HeaderFlag.PINGREQ_RESERVED;
|
||||
_data[1] = 0;
|
||||
}
|
||||
|
||||
const uint8_t* PingReqOutPacket::data(size_t index) const {
|
||||
return &_data[index];;
|
||||
}
|
||||
|
||||
size_t PingReqOutPacket::size() const {
|
||||
return 2;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PingReqOutPacket : public OutPacket {
|
||||
public:
|
||||
PingReqOutPacket();
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
uint8_t _data[2];
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "PubAck.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubAckOutPacket;
|
||||
|
||||
PubAckOutPacket::PubAckOutPacket(PendingAck pendingAck) {
|
||||
_data[0] = pendingAck.packetType;
|
||||
_data[0] = _data[0] << 4;
|
||||
_data[0] = _data[0] | pendingAck.headerFlag;
|
||||
_data[1] = 2;
|
||||
_packetId = pendingAck.packetId;
|
||||
_data[2] = pendingAck.packetId >> 8;
|
||||
_data[3] = pendingAck.packetId & 0xFF;
|
||||
if (packetType() == AsyncMqttClientInternals::PacketType.PUBREL ||
|
||||
packetType() == AsyncMqttClientInternals::PacketType.PUBREC) {
|
||||
_released = false;
|
||||
}
|
||||
}
|
||||
|
||||
const uint8_t* PubAckOutPacket::data(size_t index) const {
|
||||
return &_data[index];
|
||||
}
|
||||
|
||||
size_t PubAckOutPacket::size() const {
|
||||
return 4;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubAckOutPacket : public OutPacket {
|
||||
public:
|
||||
explicit PubAckOutPacket(PendingAck pendingAck);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
uint8_t _data[4];
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,69 @@
|
||||
#include "Publish.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PublishOutPacket;
|
||||
|
||||
PublishOutPacket::PublishOutPacket(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.PUBLISH;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
// if (dup) fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_DUP;
|
||||
if (retain) fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_RETAIN;
|
||||
switch (qos) {
|
||||
case 0:
|
||||
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS0;
|
||||
break;
|
||||
case 1:
|
||||
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS1;
|
||||
break;
|
||||
case 2:
|
||||
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS2;
|
||||
break;
|
||||
}
|
||||
|
||||
uint16_t topicLength = strlen(topic);
|
||||
char topicLengthBytes[2];
|
||||
topicLengthBytes[0] = topicLength >> 8;
|
||||
topicLengthBytes[1] = topicLength & 0xFF;
|
||||
|
||||
uint32_t payloadLength = length;
|
||||
if (payload != nullptr && payloadLength == 0) payloadLength = strlen(payload);
|
||||
|
||||
uint32_t remainingLength = 2 + topicLength + payloadLength;
|
||||
if (qos != 0) remainingLength += 2;
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(remainingLength, fixedHeader + 1);
|
||||
|
||||
size_t neededSpace = 0;
|
||||
neededSpace += 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += topicLength;
|
||||
if (qos != 0) neededSpace += 2;
|
||||
if (payload != nullptr) neededSpace += payloadLength;
|
||||
|
||||
_data.reserve(neededSpace);
|
||||
|
||||
_packetId = (qos !=0) ? _getNextPacketId() : 1;
|
||||
char packetIdBytes[2];
|
||||
packetIdBytes[0] = _packetId >> 8;
|
||||
packetIdBytes[1] = _packetId & 0xFF;
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
|
||||
_data.insert(_data.end(), topic, topic + topicLength);
|
||||
if (qos != 0) {
|
||||
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
|
||||
_released = false;
|
||||
}
|
||||
if (payload != nullptr) _data.insert(_data.end(), payload, payload + payloadLength);
|
||||
}
|
||||
|
||||
const uint8_t* PublishOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t PublishOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
|
||||
void PublishOutPacket::setDup() {
|
||||
_data[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_DUP;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring> // strlen
|
||||
#include <vector>
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PublishOutPacket : public OutPacket {
|
||||
public:
|
||||
PublishOutPacket(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
void setDup(); // you cannot unset dup
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "Subscribe.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::SubscribeOutPacket;
|
||||
|
||||
SubscribeOutPacket::SubscribeOutPacket(const char* topic, uint8_t qos) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.SUBSCRIBE;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.SUBSCRIBE_RESERVED;
|
||||
|
||||
uint16_t topicLength = strlen(topic);
|
||||
char topicLengthBytes[2];
|
||||
topicLengthBytes[0] = topicLength >> 8;
|
||||
topicLengthBytes[1] = topicLength & 0xFF;
|
||||
|
||||
char qosByte[1];
|
||||
qosByte[0] = qos;
|
||||
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(2 + 2 + topicLength + 1, fixedHeader + 1);
|
||||
|
||||
size_t neededSpace = 0;
|
||||
neededSpace += 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += 2;
|
||||
neededSpace += topicLength;
|
||||
neededSpace += 1;
|
||||
|
||||
_data.reserve(neededSpace);
|
||||
|
||||
_packetId = _getNextPacketId();
|
||||
char packetIdBytes[2];
|
||||
packetIdBytes[0] = _packetId >> 8;
|
||||
packetIdBytes[1] = _packetId & 0xFF;
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
|
||||
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
|
||||
_data.insert(_data.end(), topic, topic + topicLength);
|
||||
_data.push_back(qosByte[0]);
|
||||
_released = false;
|
||||
}
|
||||
|
||||
const uint8_t* SubscribeOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t SubscribeOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring> // strlen
|
||||
#include <vector>
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class SubscribeOutPacket : public OutPacket {
|
||||
public:
|
||||
SubscribeOutPacket(const char* topic, uint8_t qos);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "Unsubscribe.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::UnsubscribeOutPacket;
|
||||
|
||||
UnsubscribeOutPacket::UnsubscribeOutPacket(const char* topic) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.UNSUBSCRIBE;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.UNSUBSCRIBE_RESERVED;
|
||||
|
||||
uint16_t topicLength = strlen(topic);
|
||||
char topicLengthBytes[2];
|
||||
topicLengthBytes[0] = topicLength >> 8;
|
||||
topicLengthBytes[1] = topicLength & 0xFF;
|
||||
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(2 + 2 + topicLength, fixedHeader + 1);
|
||||
|
||||
size_t neededSpace = 0;
|
||||
neededSpace += 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += 2;
|
||||
neededSpace += topicLength;
|
||||
|
||||
_packetId = _getNextPacketId();
|
||||
char packetIdBytes[2];
|
||||
packetIdBytes[0] = _packetId >> 8;
|
||||
packetIdBytes[1] = _packetId & 0xFF;
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
|
||||
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
|
||||
_data.insert(_data.end(), topic, topic + topicLength);
|
||||
_released = false;
|
||||
}
|
||||
|
||||
const uint8_t* UnsubscribeOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t UnsubscribeOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring> // strlen
|
||||
#include <vector>
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class UnsubscribeOutPacket : public OutPacket {
|
||||
public:
|
||||
explicit UnsubscribeOutPacket(const char* topic);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class Packet {
|
||||
public:
|
||||
virtual ~Packet() {}
|
||||
|
||||
virtual void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) = 0;
|
||||
virtual void parsePayload(char* data, size_t len, size_t* currentBytePosition) = 0;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,21 @@
|
||||
#include "PingRespPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PingRespPacket;
|
||||
|
||||
PingRespPacket::PingRespPacket(ParsingInformation* parsingInformation, OnPingRespInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback) {
|
||||
}
|
||||
|
||||
PingRespPacket::~PingRespPacket() {
|
||||
}
|
||||
|
||||
void PingRespPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
|
||||
void PingRespPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PingRespPacket : public Packet {
|
||||
public:
|
||||
explicit PingRespPacket(ParsingInformation* parsingInformation, OnPingRespInternalCallback callback);
|
||||
~PingRespPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPingRespInternalCallback _callback;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubAckPacket;
|
||||
|
||||
PubAckPacket::PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubAckPacket::~PubAckPacket() {
|
||||
}
|
||||
|
||||
void PubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubAckPacket : public Packet {
|
||||
public:
|
||||
explicit PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback);
|
||||
~PubAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubCompPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubCompPacket;
|
||||
|
||||
PubCompPacket::PubCompPacket(ParsingInformation* parsingInformation, OnPubCompInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubCompPacket::~PubCompPacket() {
|
||||
}
|
||||
|
||||
void PubCompPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubCompPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubCompPacket : public Packet {
|
||||
public:
|
||||
explicit PubCompPacket(ParsingInformation* parsingInformation, OnPubCompInternalCallback callback);
|
||||
~PubCompPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubCompInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubRecPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubRecPacket;
|
||||
|
||||
PubRecPacket::PubRecPacket(ParsingInformation* parsingInformation, OnPubRecInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubRecPacket::~PubRecPacket() {
|
||||
}
|
||||
|
||||
void PubRecPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubRecPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubRecPacket : public Packet {
|
||||
public:
|
||||
explicit PubRecPacket(ParsingInformation* parsingInformation, OnPubRecInternalCallback callback);
|
||||
~PubRecPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubRecInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubRelPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubRelPacket;
|
||||
|
||||
PubRelPacket::PubRelPacket(ParsingInformation* parsingInformation, OnPubRelInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubRelPacket::~PubRelPacket() {
|
||||
}
|
||||
|
||||
void PubRelPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubRelPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubRelPacket : public Packet {
|
||||
public:
|
||||
explicit PubRelPacket(ParsingInformation* parsingInformation, OnPubRelInternalCallback callback);
|
||||
~PubRelPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubRelInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "PublishPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PublishPacket;
|
||||
|
||||
PublishPacket::PublishPacket(ParsingInformation* parsingInformation, OnMessageInternalCallback dataCallback, OnPublishInternalCallback completeCallback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _dataCallback(dataCallback)
|
||||
, _completeCallback(completeCallback)
|
||||
, _dup(false)
|
||||
, _qos(0)
|
||||
, _retain(0)
|
||||
, _bytePosition(0)
|
||||
, _topicLengthMsb(0)
|
||||
, _topicLength(0)
|
||||
, _ignore(false)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0)
|
||||
, _payloadLength(0)
|
||||
, _payloadBytesRead(0) {
|
||||
_dup = _parsingInformation->packetFlags & HeaderFlag.PUBLISH_DUP;
|
||||
_retain = _parsingInformation->packetFlags & HeaderFlag.PUBLISH_RETAIN;
|
||||
char qosMasked = _parsingInformation->packetFlags & 0x06;
|
||||
switch (qosMasked) {
|
||||
case HeaderFlag.PUBLISH_QOS0:
|
||||
_qos = 0;
|
||||
break;
|
||||
case HeaderFlag.PUBLISH_QOS1:
|
||||
_qos = 1;
|
||||
break;
|
||||
case HeaderFlag.PUBLISH_QOS2:
|
||||
_qos = 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
PublishPacket::~PublishPacket() {
|
||||
}
|
||||
|
||||
void PublishPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition == 0) {
|
||||
_topicLengthMsb = currentByte;
|
||||
} else if (_bytePosition == 1) {
|
||||
_topicLength = currentByte | _topicLengthMsb << 8;
|
||||
if (_topicLength > _parsingInformation->maxTopicLength) {
|
||||
_ignore = true;
|
||||
} else {
|
||||
_parsingInformation->topicBuffer[_topicLength] = '\0';
|
||||
}
|
||||
} else if (_bytePosition >= 2 && _bytePosition < 2 + _topicLength) {
|
||||
// Starting from here, _ignore might be true
|
||||
if (!_ignore) _parsingInformation->topicBuffer[_bytePosition - 2] = currentByte;
|
||||
if (_bytePosition == 2 + _topicLength - 1 && _qos == 0) {
|
||||
_preparePayloadHandling(_parsingInformation->remainingLength - (_bytePosition + 1));
|
||||
return;
|
||||
}
|
||||
} else if (_bytePosition == 2 + _topicLength) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_preparePayloadHandling(_parsingInformation->remainingLength - (_bytePosition + 1));
|
||||
}
|
||||
_bytePosition++;
|
||||
}
|
||||
|
||||
void PublishPacket::_preparePayloadHandling(uint32_t payloadLength) {
|
||||
_payloadLength = payloadLength;
|
||||
if (payloadLength == 0) {
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
if (!_ignore) {
|
||||
_dataCallback(_parsingInformation->topicBuffer, nullptr, _qos, _dup, _retain, 0, 0, 0, _packetId);
|
||||
_completeCallback(_packetId, _qos);
|
||||
}
|
||||
} else {
|
||||
_parsingInformation->bufferState = BufferState::PAYLOAD;
|
||||
}
|
||||
}
|
||||
|
||||
void PublishPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
size_t remainToRead = len - (*currentBytePosition);
|
||||
if (_payloadBytesRead + remainToRead > _payloadLength) remainToRead = _payloadLength - _payloadBytesRead;
|
||||
|
||||
if (!_ignore) _dataCallback(_parsingInformation->topicBuffer, data + (*currentBytePosition), _qos, _dup, _retain, remainToRead, _payloadBytesRead, _payloadLength, _packetId);
|
||||
_payloadBytesRead += remainToRead;
|
||||
(*currentBytePosition) += remainToRead;
|
||||
|
||||
if (_payloadBytesRead == _payloadLength) {
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
if (!_ignore) _completeCallback(_packetId, _qos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../Flags.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PublishPacket : public Packet {
|
||||
public:
|
||||
explicit PublishPacket(ParsingInformation* parsingInformation, OnMessageInternalCallback dataCallback, OnPublishInternalCallback completeCallback);
|
||||
~PublishPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnMessageInternalCallback _dataCallback;
|
||||
OnPublishInternalCallback _completeCallback;
|
||||
|
||||
void _preparePayloadHandling(uint32_t payloadLength);
|
||||
|
||||
bool _dup;
|
||||
uint8_t _qos;
|
||||
bool _retain;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _topicLengthMsb;
|
||||
uint16_t _topicLength;
|
||||
bool _ignore;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
uint32_t _payloadLength;
|
||||
uint32_t _payloadBytesRead;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,46 @@
|
||||
#include "SubAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::SubAckPacket;
|
||||
|
||||
SubAckPacket::SubAckPacket(ParsingInformation* parsingInformation, OnSubAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
SubAckPacket::~SubAckPacket() {
|
||||
}
|
||||
|
||||
void SubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::PAYLOAD;
|
||||
}
|
||||
}
|
||||
|
||||
void SubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char status = data[(*currentBytePosition)++];
|
||||
|
||||
/* switch (status) {
|
||||
case 0:
|
||||
Serial.println("Success QoS 0");
|
||||
break;
|
||||
case 1:
|
||||
Serial.println("Success QoS 1");
|
||||
break;
|
||||
case 2:
|
||||
Serial.println("Success QoS 2");
|
||||
break;
|
||||
case 0x80:
|
||||
Serial.println("Failure");
|
||||
break;
|
||||
} */
|
||||
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId, status);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class SubAckPacket : public Packet {
|
||||
public:
|
||||
explicit SubAckPacket(ParsingInformation* parsingInformation, OnSubAckInternalCallback callback);
|
||||
~SubAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnSubAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "UnsubAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::UnsubAckPacket;
|
||||
|
||||
UnsubAckPacket::UnsubAckPacket(ParsingInformation* parsingInformation, OnUnsubAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
UnsubAckPacket::~UnsubAckPacket() {
|
||||
}
|
||||
|
||||
void UnsubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void UnsubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class UnsubAckPacket : public Packet {
|
||||
public:
|
||||
explicit UnsubAckPacket(ParsingInformation* parsingInformation, OnUnsubAckInternalCallback callback);
|
||||
~UnsubAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnUnsubAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
enum class BufferState : uint8_t {
|
||||
NONE = 0,
|
||||
REMAINING_LENGTH = 2,
|
||||
VARIABLE_HEADER = 3,
|
||||
PAYLOAD = 4
|
||||
};
|
||||
|
||||
struct ParsingInformation {
|
||||
BufferState bufferState;
|
||||
|
||||
uint16_t maxTopicLength;
|
||||
char* topicBuffer;
|
||||
|
||||
uint8_t packetType;
|
||||
uint16_t packetFlags;
|
||||
uint32_t remainingLength;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
struct PendingPubRel {
|
||||
uint16_t packetId;
|
||||
};
|
||||
|
||||
struct PendingAck {
|
||||
uint8_t packetType;
|
||||
uint8_t headerFlag;
|
||||
uint16_t packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
+30
-22
@@ -24,43 +24,52 @@
|
||||
; SHARED SETTINGS — inherited by all environments
|
||||
; ───────────────────────────────────────────────────────────────────────────────
|
||||
[common]
|
||||
platform = espressif32
|
||||
; Everything below is pinned to an exact version on purpose — like the Arduino
|
||||
; IDE asking before it updates a library. Nothing changes on a clean build
|
||||
; unless someone edits a version here in a commit. To update one: change the
|
||||
; pin, rebuild all envs, test on hardware, note it in the commit message.
|
||||
; Platform 6.12.0 = Arduino-ESP32 core 2.0.17 (ESP-IDF 4.4).
|
||||
platform = espressif32 @ 6.12.0
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
|
||||
; All external library dependencies
|
||||
; All external library dependencies.
|
||||
; Not listed here: AsyncMqttClient — vendored and patched in lib/AsyncMqttClient
|
||||
; (see lib/AsyncMqttClient/VENDORED.md). PlatformIO picks it up from lib/.
|
||||
lib_deps =
|
||||
; WiFi provisioning portal
|
||||
tzapu/WiFiManager @ ^2.0.17
|
||||
tzapu/WiFiManager @ 2.0.17
|
||||
|
||||
; Async web server + WebSocket support
|
||||
; NOTE: Use the ESP32-compatible fork, not the original
|
||||
https://github.com/me-no-dev/ESPAsyncWebServer.git
|
||||
https://github.com/me-no-dev/AsyncTCP.git
|
||||
; Async web server + WebSocket support, and its TCP layer (also used by
|
||||
; AsyncMqttClient). Git sources are pinned to the exact commit after '#'.
|
||||
; me-no-dev/* now redirects to the ESP32Async forks (v3.6.0 / v3.3.2).
|
||||
https://github.com/me-no-dev/ESPAsyncWebServer.git#ad3741d159f9cfd50c567e81b67f3bef1dc6d89f
|
||||
https://github.com/me-no-dev/AsyncTCP.git#ef448a8a1dffe4ec1b72326dd5a26211ff227b49
|
||||
|
||||
; JSON parsing
|
||||
bblanchon/ArduinoJson @ ^7.0.0
|
||||
bblanchon/ArduinoJson @ 7.4.3
|
||||
|
||||
; I2C GPIO expanders (relay control) — PCF8575 header is bundled in same library
|
||||
adafruit/Adafruit PCF8574 @ ^1.1.0
|
||||
adafruit/Adafruit PCF8574 @ 1.1.2
|
||||
; Pulled in by the Adafruit libraries; pinned so it can't float either
|
||||
adafruit/Adafruit BusIO @ 1.17.4
|
||||
|
||||
; Real-time clock
|
||||
adafruit/RTClib @ ^2.1.4
|
||||
|
||||
; Async MQTT client
|
||||
; NOTE: Requires AsyncTCP (already listed above)
|
||||
https://github.com/marvinroger/async-mqtt-client.git
|
||||
adafruit/RTClib @ 2.1.4
|
||||
|
||||
; RF remote receiver (433MHz, RCSwitch protocol)
|
||||
sui77/rc-switch @ ^2.6.4
|
||||
sui77/rc-switch @ 2.6.4
|
||||
|
||||
; Modbus RTU master (used by Rs485OutputManager for bespoke-rs485 build)
|
||||
4-20ma/ModbusMaster @ ^2.0.1
|
||||
4-20ma/ModbusMaster @ 2.0.1
|
||||
|
||||
build_flags_common =
|
||||
-std=gnu++14
|
||||
-DCORE_DEBUG_LEVEL=0
|
||||
-DCONFIG_ASYNC_TCP_RUNNING_CORE=0
|
||||
; F-070: route every abort()/assert/stack-overflow through our wrapper so the
|
||||
; reason string survives the reboot (src/Telemetry/CrashBreadcrumbs.cpp)
|
||||
-Wl,--wrap=esp_system_abort
|
||||
|
||||
; ───────────────────────────────────────────────────────────────────────────────
|
||||
; VESPER Standard v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB Flash)
|
||||
@@ -92,9 +101,11 @@ board_build.partitions = no_fs.csv
|
||||
; Upgrade to C++14 so std::make_unique is available
|
||||
build_unflags = -std=gnu++11
|
||||
|
||||
; FreeRTOS timer service task stack — default 2048 is too small when timer callbacks
|
||||
; do LOG formatting, MQTT connect(), NTP sync, etc. Increase to 4096.
|
||||
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||
; NOTE: the FreeRTOS timer service task (Tmr Svc) stack is fixed at 2048 bytes in
|
||||
; Arduino builds — the SDK is precompiled, so it can't be raised from here (a
|
||||
; `board_build.cmake_extra_args` line used to claim 4096; it only works for
|
||||
; ESP-IDF framework builds and never had any effect). Timer callbacks must stay
|
||||
; tiny: set a flag or notify a task, never LOG / JSON / network / xTaskCreate.
|
||||
|
||||
; Build flags for this variant
|
||||
; IMPORTANT: MQTT_SECRET must match the MQTT_SECRET in the backend .env file exactly.
|
||||
@@ -129,7 +140,6 @@ upload_protocol = esptool
|
||||
; for the full rationale). No spiffs partition; SD-card only, no SPIFFS usage.
|
||||
board_build.partitions = no_fs.csv
|
||||
build_unflags = -std=gnu++11
|
||||
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||
|
||||
build_flags =
|
||||
${common.build_flags_common}
|
||||
@@ -158,7 +168,6 @@ upload_protocol = esptool
|
||||
; for the full rationale). No spiffs partition; SD-card only, no SPIFFS usage.
|
||||
board_build.partitions = no_fs.csv
|
||||
build_unflags = -std=gnu++11
|
||||
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||
|
||||
build_flags =
|
||||
${common.build_flags_common}
|
||||
@@ -193,7 +202,6 @@ upload_protocol = esptool
|
||||
; for the full rationale). No spiffs partition; SD-card only, no SPIFFS usage.
|
||||
board_build.partitions = no_fs.csv
|
||||
build_unflags = -std=gnu++11
|
||||
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||
|
||||
build_flags =
|
||||
${common.build_flags_common}
|
||||
|
||||
@@ -53,6 +53,10 @@ void CommandBus::dispatch(CommandEnvelope& envelope) {
|
||||
|
||||
LOG_DEBUG(TAG, "Dispatching: %s", envelope.command.c_str());
|
||||
CommandResult result = it->second->execute(envelope);
|
||||
// The reply always goes out here, synchronously, on the transport's own task —
|
||||
// which is what guarantees req_id is echoed. Work that finishes later (e.g. a
|
||||
// playback.play that must download first, F-068) must NOT defer the reply;
|
||||
// its outcome is published on its own topic (status/playback, control/reports).
|
||||
result.reqId = envelope.reqId;
|
||||
envelope.reply(result);
|
||||
}
|
||||
|
||||
@@ -554,7 +554,7 @@ void CommunicationRouter::publishAlert(const String& subsystem, const String& ne
|
||||
// immediately sees the last unresolved alert per subsystem. A CLEARED
|
||||
// publish (empty message, state="CLEARED") overwrites the retained
|
||||
// message with the resolved state, same retain semantics.
|
||||
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, true);
|
||||
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 0, true);
|
||||
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
|
||||
}
|
||||
|
||||
@@ -583,12 +583,9 @@ void CommunicationRouter::reportBootOnce() {
|
||||
payload["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||
|
||||
const CrashReport& crash = _telemetry->getCrashReport();
|
||||
if (crash.available) {
|
||||
JsonObject crashObj = payload["crash"].to<JsonObject>();
|
||||
crashObj["task"] = crash.taskName;
|
||||
crashObj["pc"] = crash.pc;
|
||||
crashObj["exc_cause"] = crash.excCause;
|
||||
crashObj["exc_vaddr"] = crash.excVaddr;
|
||||
if (crash.available) _telemetry->writeCrashJson(payload["crash"].to<JsonObject>());
|
||||
if (_telemetry->getPreCrashSnapshot().available) {
|
||||
_telemetry->writePreCrashJson(payload["pre_crash"].to<JsonObject>());
|
||||
}
|
||||
|
||||
publishInfo("boot_report", payload);
|
||||
@@ -670,7 +667,7 @@ void CommunicationRouter::publishInfo(const String& type, const JsonDocument& pa
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 1, true);
|
||||
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, true);
|
||||
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
||||
}
|
||||
|
||||
@@ -684,7 +681,9 @@ void CommunicationRouter::publishPlayback(const PlaybackSnapshot& snapshot) {
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 1, true);
|
||||
// QoS 1 + PUBACK tracking: playback is what the apps act on. Not resent on
|
||||
// reconnect — onConnect republishes the *current* snapshot instead (F-073).
|
||||
_mqttClient.publishConfirmed(_mqttClient.getPlaybackTopic(), out, true, false);
|
||||
LOG_DEBUG(TAG, "Playback published: %s", snapshot.action);
|
||||
}
|
||||
|
||||
@@ -702,7 +701,8 @@ void CommunicationRouter::publishReport(const String& type, const JsonDocument&
|
||||
serializeJson(doc, out);
|
||||
// Not retained — an event stream of critical-but-transient reports, not a
|
||||
// status snapshot. A late subscriber doesn't need old reports replayed.
|
||||
_mqttClient.publishDirect(_mqttClient.getReportsTopic(), out, 1, false);
|
||||
// QoS 1 + PUBACK tracking, resent after a reconnect if unconfirmed (F-073).
|
||||
_mqttClient.publishConfirmed(_mqttClient.getReportsTopic(), out, false, true);
|
||||
LOG_DEBUG(TAG, "Report published: %s", type.c_str());
|
||||
}
|
||||
|
||||
|
||||
@@ -48,10 +48,10 @@
|
||||
| `void broadcastToAllWebSocketClients(const String& msg)` | All WebSocket clients. |
|
||||
| `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. |
|
||||
| `void sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity)` | WS clients get the existing `bell_overload` INFO event via `broadcastStatus()`. MQTT clients get the same data via `publishReport("bell_overload", ...)` on `control/reports` instead. |
|
||||
| `void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs)` | Publishes a playback transition to `vesper/{uid}/status/playback` (QoS 1, retained). Called by `Player::setStatus()` on every transition, alongside the existing WS `broadcastStatus()` call. Gated by the `playback` topic switch. |
|
||||
| `void publishReport(const String& type, const JsonDocument& payload)` | Publishes a critical, unsolicited, time-sensitive event to `vesper/{uid}/control/reports` (QoS 1, not retained). Gated by the `reports` topic switch. |
|
||||
| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/system/alerts` (QoS 1, retained until cleared). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootOnce()` for fault reset reasons. No-op if MQTT is not connected or the `alerts` topic switch is off. |
|
||||
| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/system/info` (QoS 1, retained). No-op if MQTT is not connected or the `info` topic switch is off. Used for e.g. the `"boot_report"` event published once per boot — see below. |
|
||||
| `void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs)` | Publishes a playback transition to `vesper/{uid}/status/playback` (QoS 1 via `publishConfirmed()`, retained). Called by `Player::setStatus()` on every transition, alongside the existing WS `broadcastStatus()` call. Gated by the `playback` topic switch. |
|
||||
| `void publishReport(const String& type, const JsonDocument& payload)` | Publishes a critical, unsolicited, time-sensitive event to `vesper/{uid}/control/reports` (QoS 1 via `publishConfirmed()`, resent after reconnect if unconfirmed, not retained). Gated by the `reports` topic switch. |
|
||||
| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/system/alerts` (QoS 0, retained until cleared). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootOnce()` for fault reset reasons. No-op if MQTT is not connected or the `alerts` topic switch is off. |
|
||||
| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/system/info` (QoS 0, retained). No-op if MQTT is not connected or the `info` topic switch is off. Used for e.g. the `"boot_report"` event published once per boot — see below. |
|
||||
| `void publishMetrics(const JsonDocument& payload)` | Publishes structured telemetry to `vesper/{uid}/system/metrics` (QoS 0, not retained). Used by the 5-minute diagnostics report — see below. Gated by the `metrics` topic switch. |
|
||||
|
||||
### Network callbacks (called by Networking)
|
||||
|
||||
@@ -15,55 +15,23 @@ MQTTDriver::MQTTDriver(ConfigManager& configManager, Networking& networking)
|
||||
: _configManager(configManager)
|
||||
, _networking(networking)
|
||||
, _messageCallback(nullptr)
|
||||
, _mqttReconnectTimer(nullptr)
|
||||
, _networkStabilizationTimer(nullptr)
|
||||
, _heartbeatTimer(nullptr)
|
||||
, _heartbeatTaskHandle(nullptr)
|
||||
, _supervisorTask(nullptr)
|
||||
, _reconnectAttempts(0)
|
||||
, _lastConnectionAttempt(0) {
|
||||
, _nextConnectAtMs(0)
|
||||
, _connectAttemptMs(0)
|
||||
, _netUpSinceMs(0)
|
||||
, _heartbeatDue(false)
|
||||
, _lastHeartbeatMs(0)
|
||||
, _pendingMutex(xSemaphoreCreateRecursiveMutex())
|
||||
, _resendDue(false) {
|
||||
|
||||
_instance = this; // Set static instance pointer
|
||||
|
||||
// Create reconnection timer (initial delay will be calculated dynamically)
|
||||
_mqttReconnectTimer = xTimerCreate(
|
||||
"mqttReconnect", // Timer name (for debugging)
|
||||
pdMS_TO_TICKS(MQTT_RECONNECT_BASE_DELAY), // Initial period: 5000ms = 5 seconds
|
||||
pdFALSE, // One-shot (false) or Auto-reload (true)
|
||||
(void*)0, // Timer ID (can store data)
|
||||
mqttReconnectTimerCallback // Callback function when timer expires
|
||||
);
|
||||
|
||||
// Create network stabilization timer (one-shot, 2 seconds)
|
||||
_networkStabilizationTimer = xTimerCreate(
|
||||
"mqttNetStable", // Timer name
|
||||
pdMS_TO_TICKS(NETWORK_STABILIZATION_DELAY), // Period: 2000ms = 2 seconds
|
||||
pdFALSE, // One-shot timer
|
||||
(void*)0, // Timer ID
|
||||
networkStabilizationTimerCallback // Callback function
|
||||
);
|
||||
|
||||
// Create heartbeat timer (auto-reload every 30 seconds)
|
||||
_heartbeatTimer = xTimerCreate(
|
||||
"mqttHeartbeat", // Timer name
|
||||
pdMS_TO_TICKS(HEARTBEAT_INTERVAL), // Period: 30000ms = 30 seconds
|
||||
pdTRUE, // Auto-reload (true) - repeating timer
|
||||
(void*)0, // Timer ID
|
||||
heartbeatTimerCallback // Callback function
|
||||
);
|
||||
|
||||
_pending.reserve(MAX_PENDING_ACKS);
|
||||
}
|
||||
|
||||
MQTTDriver::~MQTTDriver() {
|
||||
if (_mqttReconnectTimer) {
|
||||
xTimerDelete(_mqttReconnectTimer, portMAX_DELAY);
|
||||
}
|
||||
if (_networkStabilizationTimer) {
|
||||
xTimerStop(_networkStabilizationTimer, 0);
|
||||
xTimerDelete(_networkStabilizationTimer, portMAX_DELAY);
|
||||
}
|
||||
if (_heartbeatTimer) {
|
||||
xTimerStop(_heartbeatTimer, 0);
|
||||
xTimerDelete(_heartbeatTimer, portMAX_DELAY);
|
||||
if (_supervisorTask) {
|
||||
vTaskDelete(_supervisorTask);
|
||||
}
|
||||
_mqttClient.disconnect();
|
||||
}
|
||||
@@ -127,8 +95,14 @@ void MQTTDriver::begin() {
|
||||
// crash, power loss). Must be re-registered on every reconnect, which is
|
||||
// automatic here since setWill() is applied on every begin()/connect() —
|
||||
// AsyncMqttClient resends CONNECT (with Will) on every reconnection attempt.
|
||||
String willPayload = buildOfflinePayload();
|
||||
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, willPayload.c_str());
|
||||
_willPayload = buildOfflinePayload();
|
||||
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, _willPayload.c_str());
|
||||
|
||||
// Created once at boot, while the heap is still unfragmented, and never
|
||||
// deleted — nothing in the reconnect/heartbeat path allocates a task again.
|
||||
if (!_supervisorTask) {
|
||||
xTaskCreate(supervisorTaskFn, "mqttSup", 4096, this, 3, &_supervisorTask);
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
|
||||
}
|
||||
@@ -144,27 +118,22 @@ String MQTTDriver::buildOfflinePayload() const {
|
||||
}
|
||||
|
||||
void MQTTDriver::connect() {
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
_reconnectAttempts = 0;
|
||||
_nextConnectAtMs = millis();
|
||||
wakeSupervisor();
|
||||
}
|
||||
|
||||
// 🔥 Check if MQTT is enabled
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_DEBUG(TAG, "MQTT is disabled in configuration - skipping connection");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
LOG_DEBUG(TAG, "Already connected to MQTT");
|
||||
return;
|
||||
}
|
||||
|
||||
// Track connection attempt
|
||||
_lastConnectionAttempt = millis();
|
||||
|
||||
LOG_INFO(TAG, "Free heap BEFORE MQTT connect: %d bytes", ESP.getFreeHeap());
|
||||
// Supervisor-task only. AsyncMqttClient::connect() is a no-op unless the
|
||||
// library is DISCONNECTED; if it's stuck in CONNECTING/DISCONNECTING the
|
||||
// supervisor notices via _connectAttemptMs and forces a reset.
|
||||
void MQTTDriver::doConnect() {
|
||||
if (_mqttClient.connected()) return;
|
||||
|
||||
unsigned long now = millis();
|
||||
_connectAttemptMs = now ? now : 1;
|
||||
LOG_INFO(TAG, "Connecting to MQTT broker (attempt #%d, free heap %u bytes)...",
|
||||
_reconnectAttempts + 1, (unsigned)ESP.getFreeHeap());
|
||||
_mqttClient.connect();
|
||||
|
||||
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
|
||||
}
|
||||
|
||||
void MQTTDriver::disconnect(bool graceful) {
|
||||
@@ -227,6 +196,91 @@ uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payloa
|
||||
return packetId;
|
||||
}
|
||||
|
||||
uint16_t MQTTDriver::publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect) {
|
||||
if (!_mqttClient.connected()) return 0;
|
||||
if (!hasHeapForPublish()) return 0;
|
||||
|
||||
uint16_t packetId = publishTracked(fullTopic, payload, retain, CONFIRMED_ACK_TIMEOUT,
|
||||
resendOnReconnect ? "report PUBACK timeout" : "playback PUBACK timeout",
|
||||
resendOnReconnect);
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published (confirmed) to %s (packetId=%d)", fullTopic.c_str(), packetId);
|
||||
}
|
||||
return packetId;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PUBACK TRACKING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
uint16_t MQTTDriver::publishTracked(const String& topic, const String& payload, bool retain,
|
||||
unsigned long timeoutMs, const char* label, bool resend) {
|
||||
PendingAck p;
|
||||
p.label = label;
|
||||
p.resend = resend;
|
||||
if (resend) {
|
||||
p.topic = topic;
|
||||
p.payload = payload;
|
||||
}
|
||||
p.retain = retain;
|
||||
|
||||
// Publish and register under the same lock: the PUBACK can come back on
|
||||
// the async_tcp task before publish() even returns here, and onMqttPublish
|
||||
// must find the entry or it would time out and force a needless reset.
|
||||
// Recursive: publish() can synchronously end in onMqttDisconnect →
|
||||
// abandonPending() on this same task.
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
uint16_t packetId = _mqttClient.publish(topic.c_str(), 1, retain, payload.c_str());
|
||||
if (packetId > 0) {
|
||||
p.id = packetId;
|
||||
p.deadlineMs = millis() + timeoutMs;
|
||||
if (_pending.size() >= MAX_PENDING_ACKS) {
|
||||
// Eight unacked QoS 1 messages means the connection is already
|
||||
// stalled; keep the oldest — its deadline triggers the reset anyway.
|
||||
_pending.erase(_pending.begin() + 1);
|
||||
}
|
||||
_pending.push_back(std::move(p));
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
return packetId;
|
||||
}
|
||||
|
||||
const char* MQTTDriver::expiredPendingLabel(unsigned long now) {
|
||||
const char* label = nullptr;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (const auto& p : _pending) {
|
||||
if ((long)(now - p.deadlineMs) >= 0) { label = p.label; break; }
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
return label;
|
||||
}
|
||||
|
||||
void MQTTDriver::abandonPending() {
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (auto& p : _pending) {
|
||||
if (p.resend) _resendQueue.push_back(std::move(p));
|
||||
}
|
||||
_pending.clear();
|
||||
while (_resendQueue.size() > MAX_RESEND) {
|
||||
_resendQueue.erase(_resendQueue.begin()); // keep the newest
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
}
|
||||
|
||||
void MQTTDriver::flushResendQueue() {
|
||||
std::vector<PendingAck> toSend;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
toSend.swap(_resendQueue);
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
|
||||
for (const auto& p : toSend) {
|
||||
if (publishConfirmed(p.topic, p.payload, p.retain, true) > 0) {
|
||||
_diag.resentMessages++;
|
||||
LOG_INFO(TAG, "Resent unconfirmed message to %s after reconnect", p.topic.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
@@ -236,32 +290,16 @@ bool MQTTDriver::isConnected() const {
|
||||
}
|
||||
|
||||
void MQTTDriver::onNetworkConnected() {
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
// 🔥 Only attempt connection if MQTT is enabled
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_DEBUG(TAG, "Network connected but MQTT is disabled - skipping MQTT connection");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Network connected - scheduling MQTT connection after 2s stabilization (non-blocking)");
|
||||
|
||||
// Reset reconnect attempts on fresh network connection
|
||||
// The supervisor tracks WiFi itself (it doesn't depend on this callback
|
||||
// ever arriving) — this just resets backoff and wakes it up promptly.
|
||||
LOG_DEBUG(TAG, "Network connected - MQTT connect after %lums stabilization", NETWORK_STABILIZATION_DELAY);
|
||||
_reconnectAttempts = 0;
|
||||
|
||||
// 🔥 CRITICAL FIX: Use non-blocking timer instead of delay()
|
||||
// This prevents blocking UDP discovery, WebSocket connections, and async operations
|
||||
if (_networkStabilizationTimer) {
|
||||
xTimerStart(_networkStabilizationTimer, 0);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Network stabilization timer not initialized!");
|
||||
// Fallback to immediate connection (better than blocking)
|
||||
connect();
|
||||
}
|
||||
_nextConnectAtMs = millis();
|
||||
wakeSupervisor();
|
||||
}
|
||||
|
||||
void MQTTDriver::onNetworkDisconnected() {
|
||||
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
|
||||
LOG_DEBUG(TAG, "Network disconnected - MQTT will reconnect when network returns");
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
_mqttClient.disconnect(true);
|
||||
@@ -286,12 +324,23 @@ void MQTTDriver::onMqttConnect(bool sessionPresent) {
|
||||
|
||||
// Reset reconnection attempts on successful connection
|
||||
_reconnectAttempts = 0;
|
||||
_connectAttemptMs = 0;
|
||||
_diag.connects++;
|
||||
|
||||
// Anything still tracked belongs to the previous connection (e.g. registered
|
||||
// after a disconnect that fired inside publish()) and would time out here.
|
||||
// Before the onConnect callback below republishes playback.
|
||||
abandonPending();
|
||||
_diag.connectedSinceMs = millis();
|
||||
|
||||
// Subscribe to control topic
|
||||
subscribe();
|
||||
|
||||
// 🔥 Start heartbeat timer
|
||||
startHeartbeat();
|
||||
// First heartbeat (and any resends) go out from the supervisor right away,
|
||||
// not from here — this callback runs on the async_tcp task.
|
||||
_heartbeatDue = true;
|
||||
_resendDue = true;
|
||||
wakeSupervisor();
|
||||
|
||||
if (_onConnectCallback) {
|
||||
_onConnectCallback(sessionPresent);
|
||||
@@ -326,34 +375,26 @@ void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
||||
break;
|
||||
}
|
||||
|
||||
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d)", reasonStr, static_cast<int>(reason));
|
||||
_diag.disconnects++;
|
||||
_diag.lastDisconnectReason = reasonStr;
|
||||
_diag.lastDisconnectMs = millis();
|
||||
_diag.connectedSinceMs = 0;
|
||||
_connectAttemptMs = 0;
|
||||
abandonPending();
|
||||
|
||||
// Stop heartbeat timer when disconnected
|
||||
stopHeartbeat();
|
||||
|
||||
// 🔥 Don't attempt reconnection if MQTT is disabled
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_INFO(TAG, "MQTT is disabled - not attempting reconnection");
|
||||
LOG_INFO(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - MQTT disabled, not reconnecting",
|
||||
reasonStr, static_cast<int>(reason));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_networking.isConnected()) {
|
||||
// Increment reconnection attempts
|
||||
_reconnectAttempts++;
|
||||
|
||||
// Calculate backoff delay
|
||||
unsigned long reconnectDelay = getReconnectDelay();
|
||||
_nextConnectAtMs = millis() + reconnectDelay;
|
||||
|
||||
LOG_INFO(TAG, "Network still connected - scheduling MQTT reconnection #%d in %lu seconds (backoff active)",
|
||||
_reconnectAttempts, reconnectDelay / 1000);
|
||||
|
||||
// Update timer period with new delay
|
||||
xTimerChangePeriod(_mqttReconnectTimer, pdMS_TO_TICKS(reconnectDelay), 0);
|
||||
xTimerStart(_mqttReconnectTimer, 0);
|
||||
} else {
|
||||
LOG_INFO(TAG, "Network is down - waiting for network to reconnect");
|
||||
}
|
||||
|
||||
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - reconnect #%d in %lus",
|
||||
reasonStr, static_cast<int>(reason), _reconnectAttempts, reconnectDelay / 1000);
|
||||
wakeSupervisor();
|
||||
}
|
||||
|
||||
void MQTTDriver::applyCommandTopicSwitch(bool enabled) {
|
||||
@@ -390,60 +431,119 @@ void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessag
|
||||
}
|
||||
|
||||
void MQTTDriver::onMqttPublish(uint16_t packetId) {
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (auto it = _pending.begin(); it != _pending.end(); ++it) {
|
||||
if (it->id == packetId) { _pending.erase(it); break; }
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
|
||||
}
|
||||
|
||||
void MQTTDriver::attemptReconnection() {
|
||||
// Double-check network is still up
|
||||
if (_networking.isConnected()) {
|
||||
LOG_INFO(TAG, "Attempting MQTT reconnection...");
|
||||
connect();
|
||||
} else {
|
||||
LOG_WARNING(TAG, "Network down during reconnect attempt - aborting");
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// SUPERVISOR TASK
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTDriver::supervisorTaskFn(void* param) {
|
||||
MQTTDriver* self = static_cast<MQTTDriver*>(param);
|
||||
for (;;) {
|
||||
// Woken early by connect/disconnect/network events; otherwise ticks.
|
||||
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(SUPERVISOR_TICK_MS));
|
||||
self->supervise();
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::mqttReconnectTaskFn(void* param) {
|
||||
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
||||
client->attemptReconnection();
|
||||
vTaskDelete(NULL);
|
||||
void MQTTDriver::wakeSupervisor() {
|
||||
if (_supervisorTask) xTaskNotifyGive(_supervisorTask);
|
||||
}
|
||||
|
||||
void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTDriver::_instance) {
|
||||
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 4096, MQTTDriver::_instance, 5, NULL);
|
||||
void MQTTDriver::supervise() {
|
||||
if (!_configManager.getMqttConfig().enabled) {
|
||||
_connectAttemptMs = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned long now = millis();
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
if (_heartbeatDue || now - _lastHeartbeatMs >= HEARTBEAT_INTERVAL) {
|
||||
_heartbeatDue = false;
|
||||
_lastHeartbeatMs = now;
|
||||
publishHeartbeat();
|
||||
}
|
||||
if (_resendDue) {
|
||||
_resendDue = false;
|
||||
flushResendQueue();
|
||||
}
|
||||
if (const char* expired = expiredPendingLabel(now)) {
|
||||
forceReset(expired);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// WiFi status straight from the driver rather than Networking's state
|
||||
// machine, so a missed network callback can't strand MQTT offline.
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
_netUpSinceMs = 0;
|
||||
return;
|
||||
}
|
||||
if (_netUpSinceMs == 0) _netUpSinceMs = now ? now : 1;
|
||||
if (now - _netUpSinceMs < NETWORK_STABILIZATION_DELAY) return;
|
||||
|
||||
unsigned long attemptStart = _connectAttemptMs;
|
||||
if (attemptStart != 0) {
|
||||
if (now - attemptStart > CONNECT_STUCK_TIMEOUT) {
|
||||
forceReset("connect attempt stuck");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ((long)(now - _nextConnectAtMs) >= 0) {
|
||||
doConnect();
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::forceReset(const char* reason) {
|
||||
_diag.forcedResets++;
|
||||
_diag.lastForcedResetReason = reason;
|
||||
_diag.lastForcedResetMs = millis();
|
||||
LOG_WARNING(TAG, "⚠️ MQTT connection wedged (%s) - forcing reset #%lu",
|
||||
reason, (unsigned long)_diag.forcedResets);
|
||||
|
||||
// Forced close: drops the socket and resets the library to DISCONNECTED
|
||||
// even when it's stuck mid-connect, so the next connect() isn't a no-op.
|
||||
// onMqttDisconnect may or may not fire from inside this call.
|
||||
_mqttClient.disconnect(true);
|
||||
|
||||
abandonPending();
|
||||
_connectAttemptMs = 0;
|
||||
unsigned long earliest = millis() + MQTT_RECONNECT_BASE_DELAY;
|
||||
if ((long)(_nextConnectAtMs - earliest) < 0) _nextConnectAtMs = earliest;
|
||||
}
|
||||
|
||||
void MQTTDriver::writeStatus(JsonObject out) const {
|
||||
unsigned long now = millis();
|
||||
out["enabled"] = _configManager.getMqttConfig().enabled;
|
||||
out["connected"] = _mqttClient.connected();
|
||||
out["connected_for_ms"] = _diag.connectedSinceMs ? now - _diag.connectedSinceMs : 0;
|
||||
out["connects"] = _diag.connects;
|
||||
out["disconnects"] = _diag.disconnects;
|
||||
out["reconnect_attempts"] = _reconnectAttempts;
|
||||
out["last_disconnect_reason"] = _diag.lastDisconnectReason;
|
||||
out["last_disconnect_ago_ms"] = _diag.lastDisconnectMs ? now - _diag.lastDisconnectMs : 0;
|
||||
out["forced_resets"] = _diag.forcedResets;
|
||||
out["last_forced_reset_reason"] = _diag.lastForcedResetReason;
|
||||
out["last_forced_reset_ago_ms"] = _diag.lastForcedResetMs ? now - _diag.lastForcedResetMs : 0;
|
||||
out["resent_messages"] = _diag.resentMessages;
|
||||
out["wifi_connected"] = WiFi.status() == WL_CONNECTED;
|
||||
out["free_heap"] = ESP.getFreeHeap();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// HEARTBEAT FUNCTIONALITY
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTDriver::startHeartbeat() {
|
||||
if (_heartbeatTimer) {
|
||||
LOG_INFO(TAG, "💓 Starting MQTT heartbeat (every %d seconds)", HEARTBEAT_INTERVAL / 1000);
|
||||
|
||||
// Publish first heartbeat immediately
|
||||
publishHeartbeat();
|
||||
|
||||
// Start periodic timer
|
||||
xTimerStart(_heartbeatTimer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::stopHeartbeat() {
|
||||
if (_heartbeatTimer) {
|
||||
xTimerStop(_heartbeatTimer, 0);
|
||||
_heartbeatTaskHandle = nullptr;
|
||||
LOG_INFO(TAG, "❤️ Stopped MQTT heartbeat");
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::publishHeartbeat() {
|
||||
if (!_mqttClient.connected()) {
|
||||
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
|
||||
return;
|
||||
}
|
||||
if (!_mqttClient.connected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().heartbeat) return;
|
||||
if (!hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
||||
|
||||
@@ -481,7 +581,9 @@ void MQTTDriver::publishHeartbeat() {
|
||||
serializeJson(doc, heartbeatMessage);
|
||||
|
||||
// Publish to heartbeat topic with RETAIN flag
|
||||
uint16_t packetId = _mqttClient.publish(_heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
|
||||
// QoS 1 on purpose — its PUBACK is the liveness probe (HEARTBEAT_ACK_TIMEOUT).
|
||||
uint16_t packetId = publishTracked(_heartbeatTopic, heartbeatMessage, true,
|
||||
HEARTBEAT_ACK_TIMEOUT, "heartbeat PUBACK timeout", false);
|
||||
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - state: %s, IP: %s, Uptime: %lums",
|
||||
@@ -491,47 +593,6 @@ void MQTTDriver::publishHeartbeat() {
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::mqttHeartbeatTaskFn(void* param) {
|
||||
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
||||
client->publishHeartbeat();
|
||||
client->_heartbeatTaskHandle = nullptr;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTDriver::heartbeatTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTDriver::_instance) {
|
||||
// Guard: skip if previous heartbeat task is still running
|
||||
if (MQTTDriver::_instance->_heartbeatTaskHandle != nullptr) {
|
||||
return;
|
||||
}
|
||||
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 4096, MQTTDriver::_instance, 3,
|
||||
&MQTTDriver::_instance->_heartbeatTaskHandle);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTDriver::connectAfterStabilization() {
|
||||
LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT");
|
||||
connect();
|
||||
}
|
||||
|
||||
void MQTTDriver::mqttConnectTaskFn(void* param) {
|
||||
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack
|
||||
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
||||
client->connectAfterStabilization();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTDriver::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTDriver::_instance) {
|
||||
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
|
||||
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 4096, MQTTDriver::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// EXPONENTIAL BACKOFF CALCULATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
@@ -544,11 +605,12 @@ unsigned long MQTTDriver::getReconnectDelay() {
|
||||
|
||||
// After quick retries: Exponential backoff
|
||||
// Formula: base_delay * 2^(attempts - quick_retries)
|
||||
// Examples: 10s, 20s, 40s, 80s, 160s, 300s (capped at 5 minutes)
|
||||
// Examples: 10s, 20s, 40s, 60s (capped at 1 minute)
|
||||
uint8_t backoffPower = _reconnectAttempts - MQTT_MAX_QUICK_RETRIES;
|
||||
if (backoffPower > 8) backoffPower = 8; // already past the cap; avoids shift overflow
|
||||
unsigned long delay = MQTT_RECONNECT_BASE_DELAY * (1 << backoffPower); // 2^backoffPower
|
||||
|
||||
// Cap at maximum delay (5 minutes)
|
||||
// Cap at maximum delay (1 minute)
|
||||
if (delay > MQTT_RECONNECT_MAX_DELAY) {
|
||||
delay = MQTT_RECONNECT_MAX_DELAY;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,17 @@
|
||||
* Handles broker connection, auth, publish/subscribe, reconnect with exponential
|
||||
* backoff, and heartbeat. Wrapped by MQTTTransport for CommandBus integration.
|
||||
*
|
||||
* QoS policy (F-072/F-073): QoS 1 only where losing a message matters —
|
||||
* the heartbeat, status/playback and control/reports — and those go through
|
||||
* publishConfirmed(), which tracks the PUBACK. A missing PUBACK means the
|
||||
* connection is dead, so the supervisor resets it; playback state is then
|
||||
* republished fresh on reconnect, reports are resent. Plain QoS 1 alone would
|
||||
* not recover anything here: with cleanSession=true the library drops unacked
|
||||
* packets on reconnect. Everything else (acks, alerts, info, logs, metrics)
|
||||
* is QoS 0. The queue is sent strictly in order and each QoS 1 message holds
|
||||
* what's behind it for one round trip (the vendored library is patched so it
|
||||
* no longer adds a ~500ms poll wait on top — lib/AsyncMqttClient/VENDORED.md).
|
||||
*
|
||||
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
|
||||
* 📅 DATE: 2025-01-04
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
@@ -18,6 +29,8 @@
|
||||
#include <Arduino.h>
|
||||
#include <AsyncMqttClient.h>
|
||||
#include <functional>
|
||||
#include <ArduinoJson.h>
|
||||
#include <vector>
|
||||
|
||||
class ConfigManager;
|
||||
class Networking;
|
||||
@@ -38,7 +51,8 @@ public:
|
||||
void begin();
|
||||
|
||||
/**
|
||||
* @brief Connect to MQTT broker
|
||||
* @brief Request a connection to the broker now (resets backoff). The
|
||||
* supervisor task performs the actual connect on its next tick.
|
||||
*/
|
||||
void connect();
|
||||
|
||||
@@ -62,7 +76,7 @@ public:
|
||||
* @return Packet ID (0 if failed, MQTT disabled, low heap, or the "command"
|
||||
* topic switch is off — control/ack shares that switch with control/command)
|
||||
*/
|
||||
uint16_t publishAck(const String& payload, int qos = 1, bool retain = false);
|
||||
uint16_t publishAck(const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Publish to an absolute, fully-qualified topic (no prefix applied).
|
||||
@@ -76,6 +90,20 @@ public:
|
||||
*/
|
||||
uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief QoS 1 publish whose PUBACK is tracked. No PUBACK within
|
||||
* CONFIRMED_ACK_TIMEOUT means the connection is dead: the supervisor
|
||||
* resets it and reconnects. Same heap guard as publishDirect(); the
|
||||
* caller still does topic-switch gating.
|
||||
* @param resendOnReconnect true for event topics (control/reports): the
|
||||
* message is kept and republished after the reconnect. false for
|
||||
* retained state topics (status/playback) whose owner republishes the
|
||||
* *current* state on every connect — resending the old one would
|
||||
* overwrite fresh state with stale.
|
||||
* @return Packet ID (0 if not sent)
|
||||
*/
|
||||
uint16_t publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect);
|
||||
|
||||
/**
|
||||
* @brief Set message received callback
|
||||
*/
|
||||
@@ -136,6 +164,24 @@ public:
|
||||
*/
|
||||
void applyCommandTopicSwitch(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Connection-health counters since boot, for post-mortem of "MQTT
|
||||
* went silent" incidents. Exposed via mqtt.status — which works over
|
||||
* WebSocket too, exactly when MQTT itself can't be asked.
|
||||
*/
|
||||
struct Diagnostics {
|
||||
uint32_t connects = 0;
|
||||
uint32_t disconnects = 0;
|
||||
uint32_t forcedResets = 0;
|
||||
const char* lastDisconnectReason = "";
|
||||
unsigned long lastDisconnectMs = 0;
|
||||
const char* lastForcedResetReason = "";
|
||||
unsigned long lastForcedResetMs = 0;
|
||||
unsigned long connectedSinceMs = 0; // 0 = not connected
|
||||
uint32_t resentMessages = 0; // reports republished after a reconnect
|
||||
};
|
||||
void writeStatus(JsonObject out) const;
|
||||
|
||||
// Minimum free heap (bytes) required before attempting a publish. Below this,
|
||||
// AsyncMqttClient's internal packet-buffer allocation risks failing outright —
|
||||
// this SDK build has CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so a failed
|
||||
@@ -176,6 +222,7 @@ private:
|
||||
* @brief Subscribe to control topic
|
||||
*/
|
||||
void subscribe();
|
||||
void doConnect();
|
||||
|
||||
/**
|
||||
* @brief MQTT event handlers
|
||||
@@ -187,32 +234,76 @@ private:
|
||||
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
|
||||
void onMqttPublish(uint16_t packetId);
|
||||
|
||||
// Reconnection Timer with Exponential Backoff
|
||||
TimerHandle_t _mqttReconnectTimer;
|
||||
// ── Supervisor ────────────────────────────────────────────────────────────
|
||||
// ONE persistent task owns everything time-driven: (re)connect with backoff,
|
||||
// network stabilization, the 30s heartbeat, and wedge detection. It replaced
|
||||
// three FreeRTOS timers that each spawned a short-lived task per firing —
|
||||
// a single failed xTaskCreate() (fragmented heap after days of uptime) ended
|
||||
// a one-shot reconnect chain for good, leaving MQTT dead until reboot while
|
||||
// WebSocket kept working. See docs/features/feature-catalog.md F-071.
|
||||
TaskHandle_t _supervisorTask;
|
||||
static void supervisorTaskFn(void* param);
|
||||
void supervise();
|
||||
void wakeSupervisor();
|
||||
void forceReset(const char* reason);
|
||||
|
||||
static const unsigned long SUPERVISOR_TICK_MS = 500;
|
||||
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds after WiFi is up
|
||||
static const unsigned long MQTT_RECONNECT_BASE_DELAY = 5000; // 5 seconds base
|
||||
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 300000; // 5 minutes max
|
||||
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 60000; // 1 minute max
|
||||
static const uint8_t MQTT_MAX_QUICK_RETRIES = 3; // Try 3 times quickly
|
||||
uint8_t _reconnectAttempts; // Track failed attempts
|
||||
unsigned long _lastConnectionAttempt; // Track last attempt time
|
||||
void attemptReconnection();
|
||||
static void mqttReconnectTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttReconnectTaskFn(void* param);
|
||||
unsigned long getReconnectDelay(); // Calculate backoff delay
|
||||
// A connect() that produces neither CONNACK nor a disconnect callback within
|
||||
// this window means AsyncMqttClient is wedged in CONNECTING/DISCONNECTING
|
||||
// (it ignores AsyncClient::connect()'s return value, and a failed tcp_close
|
||||
// never fires onDisconnect) — every later connect() would silently no-op.
|
||||
static const unsigned long CONNECT_STUCK_TIMEOUT = 30000;
|
||||
// PUBACK deadlines for tracked QoS 1 publishes. No PUBACK in time = the
|
||||
// connection is dead even if the library still says CONNECTED (half-open
|
||||
// socket, stalled send queue). The heartbeat is the background probe;
|
||||
// playback/reports get a tighter window because they're what the apps wait on.
|
||||
static const unsigned long HEARTBEAT_ACK_TIMEOUT = 20000;
|
||||
static const unsigned long CONFIRMED_ACK_TIMEOUT = 8000;
|
||||
|
||||
// Network Stabilization Timer (non-blocking replacement for delay)
|
||||
TimerHandle_t _networkStabilizationTimer;
|
||||
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds
|
||||
void connectAfterStabilization();
|
||||
static void networkStabilizationTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttConnectTaskFn(void* param);
|
||||
volatile uint8_t _reconnectAttempts;
|
||||
volatile unsigned long _nextConnectAtMs; // earliest time the next connect may start
|
||||
volatile unsigned long _connectAttemptMs; // 0 = no attempt in flight
|
||||
unsigned long _netUpSinceMs; // 0 = network down
|
||||
unsigned long getReconnectDelay();
|
||||
|
||||
// Heartbeat Timer (30 seconds)
|
||||
TimerHandle_t _heartbeatTimer;
|
||||
// Heartbeat (30 seconds)
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
TaskHandle_t _heartbeatTaskHandle; // Guard: only one heartbeat task at a time
|
||||
volatile bool _heartbeatDue;
|
||||
unsigned long _lastHeartbeatMs;
|
||||
void publishHeartbeat();
|
||||
static void heartbeatTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttHeartbeatTaskFn(void* param);
|
||||
void startHeartbeat();
|
||||
void stopHeartbeat();
|
||||
|
||||
// Tracked QoS 1 publishes awaiting PUBACK. Touched from the async_tcp task
|
||||
// (onMqttPublish), the supervisor, and whichever task publishes — guarded
|
||||
// by a recursive mutex (not a spinlock: entries own Strings, which allocate).
|
||||
struct PendingAck {
|
||||
uint16_t id;
|
||||
unsigned long deadlineMs;
|
||||
const char* label; // static string, used as forced-reset reason
|
||||
bool resend;
|
||||
String topic; // only kept when resend == true
|
||||
String payload;
|
||||
bool retain;
|
||||
};
|
||||
static const size_t MAX_PENDING_ACKS = 8;
|
||||
static const size_t MAX_RESEND = 4;
|
||||
SemaphoreHandle_t _pendingMutex;
|
||||
std::vector<PendingAck> _pending;
|
||||
std::vector<PendingAck> _resendQueue; // waiting for the next CONNACK
|
||||
volatile bool _resendDue;
|
||||
uint16_t publishTracked(const String& topic, const String& payload, bool retain,
|
||||
unsigned long timeoutMs, const char* label, bool resend);
|
||||
const char* expiredPendingLabel(unsigned long now); // nullptr if none
|
||||
void abandonPending(); // connection gone: drop, or keep for resend
|
||||
void flushResendQueue();
|
||||
|
||||
// Must outlive every CONNECT — AsyncMqttClient::setWill() stores the raw
|
||||
// pointer, so a temporary String here sent freed heap as the LWT payload
|
||||
// (the "gibberish on status/heartbeat" seen when a connection dropped).
|
||||
String _willPayload;
|
||||
|
||||
Diagnostics _diag;
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Summary
|
||||
|
||||
`MQTTDriver` is the low-level MQTT protocol driver. It wraps `AsyncMqttClient` and manages the full broker connection lifecycle: configuration, authentication, subscribe/publish, exponential backoff reconnection, 30-second heartbeat, network-stabilisation delay, and Last Will and Testament. It is not aware of the `CommandBus` — that coupling lives in `MQTTTransport`. The driver uses three FreeRTOS software timers with one-shot tasks deferred off the Tmr Svc stack to avoid stack overflows in timer callbacks.
|
||||
`MQTTDriver` is the low-level MQTT protocol driver. It wraps `AsyncMqttClient` and manages the full broker connection lifecycle: configuration, authentication, subscribe/publish, exponential backoff reconnection, 30-second heartbeat, network-stabilisation delay, and Last Will and Testament. It is not aware of the `CommandBus` — that coupling lives in `MQTTTransport`. All time-driven work runs on one persistent supervisor task (see Initialization).
|
||||
|
||||
See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table, per-topic switches, and `req_id` correlation. Topics:
|
||||
|
||||
@@ -21,7 +21,8 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
| `void begin()` | Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive, and registers the Last Will (see [LWT](#last-will-and-testament-lwt) below). Does not connect. |
|
||||
| `void connect()` | Calls `AsyncMqttClient::connect()`. No-op if MQTT is disabled in config or already connected. |
|
||||
| `void disconnect(bool graceful = false)` | Disconnects. If `graceful` is true, explicitly publishes the retained offline payload to `status/heartbeat` first — see [Graceful disconnect](#graceful-disconnect). |
|
||||
| `uint16_t publishAck(const String& payload, int qos = 1, bool retain = false)` | Publishes a reply to `control/ack`. Returns packet ID, or 0 on failure (not connected, low heap, or the `command` topic switch is off). |
|
||||
| `uint16_t publishAck(const String& payload, int qos = 0, bool retain = false)` | Publishes a reply to `control/ack`. Returns packet ID, or 0 on failure (not connected, low heap, or the `command` topic switch is off). |
|
||||
| `uint16_t publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect)` | QoS 1 publish with PUBACK tracking (8 s deadline). A missed deadline makes the supervisor reset the connection. `resendOnReconnect=true` keeps the message and republishes it after the reconnect (event topics); `false` for retained state the caller republishes itself on connect. Used for `status/playback` (false) and `control/reports` (true). |
|
||||
| `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false)` | Publishes to an absolute, fully-qualified topic (no prefix applied) — no topic-switch gating here; the caller (`CommunicationRouter`) checks the relevant switch before calling. Same heap guard as `publishAck()`. |
|
||||
| `bool hasHeapForPublish() const` | Returns `true` if `ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH` (20KB). Public so `MQTTTransport` can apply the same threshold before its own allocation-heavy work (JSON deserialization of incoming commands) without duplicating the constant. See [Gotchas](#gotchas--notes) below for why this exists. |
|
||||
| `const String& getCommandTopic() const` / `getAckTopic()` / `getHeartbeatTopic()` / `getPlaybackTopic()` / `getReportsTopic()` / `getAlertsTopic()` / `getInfoTopic()` / `getLogsTopic()` / `getMetricsTopic()` | Cached full topic strings, available after `begin()`. |
|
||||
@@ -30,8 +31,10 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
| `void setStateProvider(std::function<DeviceState()> provider)` | Registers the callback used to derive the heartbeat's `state`/`ok` fields — see [Heartbeat](#heartbeat) below. Wired by `CommunicationRouter` from `Player` + `HealthMonitor`. |
|
||||
| `void applyCommandTopicSwitch(bool enabled)` | Live-applies a change to the `command` topic switch: subscribes/unsubscribes `control/command` immediately if connected, no-ops otherwise (picked up naturally on next connect). Called by `MQTTHandler::handleSetTopics()`. |
|
||||
| `bool isConnected() const` | Returns the AsyncMqttClient connection state. |
|
||||
| `void onNetworkConnected()` | Starts the 2-second network-stabilisation timer; connects after it fires. Resets `_reconnectAttempts`. |
|
||||
| `void onNetworkDisconnected()` | Force-disconnects the client if connected. Reconnect logic waits for the next `onNetworkConnected()`. |
|
||||
| `void connect()` | Requests a connect now (resets backoff) and wakes the supervisor. Used by `mqtt.enable`. |
|
||||
| `void writeStatus(JsonObject out) const` | Fills the `mqtt.status` diagnostics object (connect/disconnect counters, last reasons, forced resets). |
|
||||
| `void onNetworkConnected()` | Resets `_reconnectAttempts` and wakes the supervisor, which connects once WiFi has been up for 2 s. Not required for reconnects — the supervisor polls `WiFi.status()` itself. |
|
||||
| `void onNetworkDisconnected()` | Force-disconnects the client if connected. The supervisor reconnects once WiFi is back. |
|
||||
|
||||
---
|
||||
|
||||
@@ -44,7 +47,7 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
MQTTDriver _mqttClient; // in CommunicationRouter
|
||||
```
|
||||
|
||||
The constructor creates all three FreeRTOS timers. If timer creation fails (extremely low memory), the `nullptr` guards in each callback will prevent crashes but MQTT will not reconnect automatically.
|
||||
`begin()` creates one persistent **supervisor task** (`mqttSup`, 4 KB, priority 3) that owns everything time-driven: connect/reconnect with backoff, the 2 s network stabilisation, the 30 s heartbeat, and wedge detection. It replaced three FreeRTOS timers that each spawned a short-lived task per firing; one failed `xTaskCreate()` on a fragmented heap used to end the reconnect chain for good. See F-071.
|
||||
|
||||
---
|
||||
|
||||
@@ -56,15 +59,30 @@ The constructor creates all three FreeRTOS timers. If timer creation fails (extr
|
||||
| 4 | 10 seconds |
|
||||
| 5 | 20 seconds |
|
||||
| 6 | 40 seconds |
|
||||
| 7+ | Capped at 300 seconds (5 minutes) |
|
||||
| 7+ | Capped at 60 seconds |
|
||||
|
||||
Reconnect attempts are reset to 0 on a successful connection or a new `onNetworkConnected()` event.
|
||||
|
||||
### Self-recovery (wedge detection)
|
||||
|
||||
The supervisor forces a reset (`AsyncMqttClient::disconnect(true)`, then a normal reconnect) when:
|
||||
|
||||
| Condition | Why it happens |
|
||||
|---|---|
|
||||
| A connect attempt produced neither CONNACK nor a disconnect callback within 30 s (`"connect attempt stuck"`) | AsyncMqttClient ignores `AsyncClient::connect()`'s return value and stays in CONNECTING forever if it fails (e.g. lwIP out of PCBs); a failed `tcp_close` never fires onDisconnect. Every later `connect()` is then a silent no-op. |
|
||||
| A tracked QoS 1 publish has no PUBACK by its deadline: heartbeat 20 s (`"heartbeat PUBACK timeout"`), playback / report 8 s (`"playback PUBACK timeout"`, `"report PUBACK timeout"`) | Half-open socket or stalled send queue while the library still reports CONNECTED. |
|
||||
|
||||
Counters and last reasons are reported by `mqtt.status`.
|
||||
|
||||
### QoS policy
|
||||
|
||||
QoS 1 only for the heartbeat, `status/playback` and `control/reports`, all with PUBACK tracking; everything else QoS 0. The library sends its queue strictly in order and holds later packets until a QoS 1 PUBACK arrives, so each QoS 1 message costs whatever is behind it one round trip. Upstream also waited for the next ~500 ms TCP poll after each PUBACK; the vendored copy in `lib/AsyncMqttClient` is patched to send immediately (see its `VENDORED.md`). Plain QoS 1 recovers nothing here — with `cleanSession=true` the library drops unacked packets on reconnect — which is why delivery is guaranteed by the tracking + reset + republish/resend path instead.
|
||||
|
||||
---
|
||||
|
||||
## Last Will and Testament (LWT)
|
||||
|
||||
Registered once in `begin()` via `AsyncMqttClient::setWill()`, targeting `status/heartbeat` (QoS 1, retained) with payload `{"device_id": "...", "state": "offline", "ok": false}`. `AsyncMqttClient` resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first `begin()`.
|
||||
Registered once in `begin()` via `AsyncMqttClient::setWill()`, targeting `status/heartbeat` (QoS 1, retained) with payload `{"device_id": "...", "state": "offline", "ok": false}`. The payload is kept in the `_willPayload` member: `setWill()` stores the raw pointer, and before F-071 it pointed at a freed temporary, so the broker published garbage as the LWT. `AsyncMqttClient` resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first `begin()`.
|
||||
|
||||
The broker fires the Will **only on an unclean disconnect** (network loss, crash, power loss) — it does not fire on a clean, intentional disconnect. See [Graceful disconnect](#graceful-disconnect) for the intentional case.
|
||||
|
||||
@@ -95,7 +113,7 @@ Once connected, a heartbeat is published immediately and then every 30 seconds t
|
||||
|
||||
`state` (`idle`/`playing`/`paused`/`error`/`booting`) and `ok` are produced by the `_stateProvider` callback — see `setStateProvider()` above — and are **independently derived**, never mirrored from `status/playback` or `system/alerts`, per the topic spec. `CommunicationRouter` wires this from `Player::isCurrentlyPlaying()`/`isCurrentlyPaused()` and `HealthMonitor::isFirmwareStable()`. If no provider is registered, heartbeats report `state="booting", ok=true`.
|
||||
|
||||
The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
The supervisor publishes the first heartbeat right after CONNACK, then every 30 s while connected. It is QoS 1 on purpose: if its PUBACK is missing after 20 s, the connection is treated as dead (see Self-recovery).
|
||||
|
||||
---
|
||||
|
||||
@@ -103,8 +121,8 @@ The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
|
||||
- `AsyncMqttClient` — broker protocol
|
||||
- `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID, per-topic switches (`MqttTopicConfig`)
|
||||
- `Networking` — `isConnected()` check before reconnect attempts; IP and gateway for heartbeat
|
||||
- FreeRTOS — three `TimerHandle_t` timers, one `TaskHandle_t` for heartbeat task guard
|
||||
- `Networking` — IP and gateway for heartbeat (reconnect gating uses `WiFi.status()` directly)
|
||||
- FreeRTOS — one persistent supervisor task, woken by task notifications
|
||||
- `Logging`
|
||||
|
||||
---
|
||||
@@ -112,9 +130,7 @@ The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
## Gotchas / Notes
|
||||
|
||||
- **Singleton pattern via `_instance`.** The class uses a static `_instance` pointer for routing timer callbacks back to the instance. Only one `MQTTDriver` should exist at a time. The constructor overwrites `_instance`, so creating two instances will break the first one's callbacks.
|
||||
- **Timer callbacks defer to tasks.** Timer callbacks run in the FreeRTOS Timer Service task (Tmr Svc, default 2 KB stack). Any callback that calls `LOG_*` macros, `connect()`, or JSON serialisation would overflow this stack. All three callbacks (`mqttReconnectTimerCallback`, `networkStabilizationTimerCallback`, `heartbeatTimerCallback`) spawn a 3 KB task and return immediately.
|
||||
- **Heartbeat task guard.** If the previous heartbeat task has not yet exited when the next timer fires, the new task is not spawned. This prevents task accumulation under slow broker connections.
|
||||
- **Error logging is suppressed on publish failure.** `publishAck()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because it's also reachable from the MQTT log channel and logging an error there would recurse infinitely.
|
||||
- **No per-event tasks.** Earlier versions spawned a short-lived task from every timer firing (reconnect, stabilisation, heartbeat). `xTaskCreate()` return values weren't checked, so on a fragmented heap a single failure silently ended MQTT until reboot. The supervisor task is allocated once at boot instead.
|
||||
- **Free-heap guard before publishing (`hasHeapForPublish()`).** Below `MIN_FREE_HEAP_FOR_PUBLISH` (20KB), `publishAck()`, `publishDirect()`, and `publishHeartbeat()` skip the operation entirely rather than risk `AsyncMqttClient::publish()`'s internal packet-buffer allocation failing. This SDK build has `CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0` — a failed allocation under heavy fragmentation can't even throw a catchable `std::bad_alloc`, it calls `abort()` directly. This guard exists because exactly that happened in production under a rapid MQTT command burst with verbose logging (see `docs/features/feature-catalog.md` F-055 for the full `addr2line`-decoded diagnosis). The skip is logged via `Serial.printf()` directly, not `LOG_*` — logging the skip over MQTT would itself attempt a publish, recursing into the same low-heap condition.
|
||||
- **Credentials from NVS.** The broker username and password are read from `ConfigManager`, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID and `MQTT_SECRET` (compiled in via `-DMQTT_SECRET`).
|
||||
- **`begin()` must be called before `connect()`.** `begin()` registers AsyncMqttClient event handlers, configures the server, and registers the Will. Calling `connect()` before `begin()` will silently do nothing useful.
|
||||
|
||||
@@ -9,12 +9,13 @@ MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient)
|
||||
: _configManager(configManager), _mqttClient(mqttClient) {}
|
||||
|
||||
std::vector<String> MQTTHandler::commands() const {
|
||||
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config",
|
||||
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config", "mqtt.status",
|
||||
"mqtt.get_topics", "mqtt.set_topics" };
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "mqtt.get_config") return handleGetConfig(envelope);
|
||||
if (envelope.command == "mqtt.status") return handleStatus(envelope);
|
||||
if (envelope.command == "mqtt.get_topics") return handleGetTopics(envelope);
|
||||
if (envelope.command == "mqtt.set_topics") return handleSetTopics(envelope);
|
||||
|
||||
@@ -51,6 +52,15 @@ CommandResult MQTTHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||
return CommandResult::ok("mqtt.get_config", doc);
|
||||
}
|
||||
|
||||
// Connection health since boot. Most useful over WebSocket: when the cloud
|
||||
// sees a device as offline but the local app still works, this says whether
|
||||
// the device knows it's disconnected, why, and whether self-recovery fired.
|
||||
CommandResult MQTTHandler::handleStatus(const CommandEnvelope& e) {
|
||||
JsonDocument doc;
|
||||
_mqttClient.writeStatus(doc.to<JsonObject>());
|
||||
return CommandResult::ok("mqtt.status", doc);
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::handleGetTopics(const CommandEnvelope& e) {
|
||||
const auto& t = _configManager.getMqttTopicConfig();
|
||||
JsonDocument doc;
|
||||
|
||||
@@ -20,6 +20,7 @@ private:
|
||||
MQTTDriver& _mqttClient;
|
||||
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
CommandResult handleStatus(const CommandEnvelope& e);
|
||||
CommandResult handleGetTopics(const CommandEnvelope& e);
|
||||
CommandResult handleSetTopics(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -61,6 +61,6 @@ Responses are published to `control/ack`:
|
||||
- **`control/ack` is strictly request/response plus bus-wide broadcasts — never purpose-specific events.** The broker does not distinguish a command reply from a `CommandBus::broadcast()` fan-out; clients must inspect `"type"` and `"status"` to differentiate. But playback transitions, alerts, reports, and metrics never appear here — those go to their own topics via `CommunicationRouter` (`publishPlayback()`, `publishAlert()`, `publishReport()`, `publishMetrics()`), bypassing this transport entirely.
|
||||
- **Broker connection is deferred.** `begin()` does not connect. The connection is triggered by `onNetworkConnected()`, which starts a 2-second non-blocking stabilisation timer in `MQTTDriver`.
|
||||
- **MQTT must be enabled in config, and the `command` topic switch must be on.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle the master switch with `mqtt.enable` / `mqtt.disable`. Independently, the `command` topic switch (via `mqtt.set_topics`) gates the `control/command` subscription and `control/ack` replies — turning it off while MQTT stays connected silently stops all command traffic.
|
||||
- **No per-message QoS.** Command replies and broadcasts are published at QoS 1 (matching the topic table). Heartbeats use QoS 1 with `retain = true`.
|
||||
- **No per-message QoS.** Command replies and broadcasts are published at QoS 0 (see F-072/F-073). Heartbeats use QoS 1 with `retain = true`.
|
||||
- **JSON parse errors and missing `cmd` get an `ERROR` reply on `control/ack`** (`type: "parse_error"`), not a silent drop — a `LOG_WARNING` is still emitted too. A parse-error reply necessarily has no `req_id` (it can't be read from input that failed to parse); a missing-`cmd` reply echoes `req_id` if the JSON was otherwise valid and included one.
|
||||
- **Incoming commands are dropped under critical heap pressure.** `onMessage()` checks `MQTTDriver::hasHeapForPublish()` (free heap ≥ 20KB) before even constructing the `JsonDocument` used to deserialize the incoming payload. Below that threshold, the message is dropped with no reply and no error response — indistinguishable from a lost network message to the caller. This exists because a rapid burst of commands (each involving deserialize + dispatch + reply, all allocation-heavy, all running inline on AsyncTCP's own task) previously fragmented the heap enough to crash the device with an unrecoverable `abort()` — see `docs/features/feature-catalog.md` F-055. A full fix (queueing incoming commands to a dedicated task, so this work never runs on AsyncTCP's task at all) is a scoped future improvement, not yet implemented.
|
||||
|
||||
@@ -37,8 +37,10 @@ void ConfigManager::initializeCleanDefaults() {
|
||||
// Must match the MQTT_SECRET in the backend .env exactly.
|
||||
mqttConfig.password = computeMqttPassword(deviceConfig.serial);
|
||||
|
||||
LOG_INFO(TAG, "🔑 MQTT auth — user: %s, password: %s", mqttConfig.user.c_str(), mqttConfig.password.c_str());
|
||||
LOG_INFO(TAG, "🔑 MQTT_SECRET prefix: %.8s...", MQTT_SECRET);
|
||||
// Never log the password or any part of MQTT_SECRET — serial/SD logs leave
|
||||
// the device (support sessions, log downloads), and the secret derives every
|
||||
// device's password.
|
||||
LOG_INFO(TAG, "🔑 MQTT auth — user: %s (password derived)", mqttConfig.user.c_str());
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - Clean defaults initialized with auto-generated identifiers");
|
||||
}
|
||||
|
||||
@@ -201,7 +201,7 @@ All files live under `/settings/` on the FAT SD card.
|
||||
`device_uid`, `hw_type`, and `hw_version` are written only by the factory provisioning tool. If any of these keys are absent in NVS, `begin()` logs a critical warning and the device will use empty strings. MQTT auth will fail and subsystems that gate on `getDeviceUID()` will behave incorrectly. Reflash the NVS partition using `esptool` and the provisioning binary.
|
||||
|
||||
**MQTT password is derived at boot, not stored.**
|
||||
`computeMqttPassword()` runs HMAC-SHA256(`MQTT_SECRET`, `deviceUID`) and takes the first 16 bytes (32 hex chars). The build flag `MQTT_SECRET` must match the value in the backend `.env` exactly. A mismatch will cause MQTT `CONNACK` error 5 (Not Authorized). The secret is logged at `INFO` level on boot — remove or gate this log line before shipping.
|
||||
`computeMqttPassword()` runs HMAC-SHA256(`MQTT_SECRET`, `deviceUID`) and takes the first 16 bytes (32 hex chars). The build flag `MQTT_SECRET` must match the value in the backend `.env` exactly. A mismatch will cause MQTT `CONNACK` error 5 (Not Authorized). Neither the password nor any part of the secret is logged (removed 2026-10-15); only the username is.
|
||||
|
||||
**SD card is required for user settings.**
|
||||
`begin()` returns `false` if `SD.begin()` fails. All `load*()` and `save*()` methods silently return `false` when the card is absent. The HealthMonitor reports ConfigManager as unhealthy when `isHealthy()` returns false (SD unmounted or UID empty). This is classified as a WARNING, not CRITICAL, so the firmware continues running with in-RAM defaults.
|
||||
|
||||
@@ -278,7 +278,7 @@ bool Logging::allowMqttPublish(const char* tag) {
|
||||
payload += " log message(s) (MQTT rate limit)\",\"timestamp\":";
|
||||
payload += now;
|
||||
payload += "}";
|
||||
_mqttCallback(_mqttLogTopic, payload, 1);
|
||||
_mqttCallback(_mqttLogTopic, payload, 0);
|
||||
state.droppedSinceLastPublish = 0;
|
||||
state.tokens--; // the summary line itself costs a token
|
||||
return state.tokens > 0;
|
||||
@@ -325,7 +325,7 @@ void Logging::publishToMqtt(LogLevel level, const char* levelStr, const char* ta
|
||||
payload += millis();
|
||||
payload += "}";
|
||||
|
||||
_mqttCallback(_mqttLogTopic, payload, 1);
|
||||
_mqttCallback(_mqttLogTopic, payload, 0);
|
||||
|
||||
isPublishing = false;
|
||||
}
|
||||
|
||||
@@ -383,6 +383,13 @@ void Networking::onWiFiConnected() {
|
||||
setState(NetworkState::CONNECTED_WIFI);
|
||||
setActiveConnection(ConnectionType::WIFI);
|
||||
|
||||
// Modem sleep off (the Arduino default is WIFI_PS_MIN_MODEM). With it on, the
|
||||
// radio dozes between AP beacons and inbound packets wait for the next DTIM —
|
||||
// 100ms to 1s+ per packet depending on the AP, which showed up as laggy app
|
||||
// commands and status updates. Mains-powered device; the power cost is moot.
|
||||
// Re-applied on every connect since WiFi.mode() changes can reset it.
|
||||
WiFi.setSleep(false);
|
||||
|
||||
// Reset failure/phase counters on successful connection
|
||||
_wifiConnectionFailures = 0;
|
||||
_triedSavedCredentials = false;
|
||||
@@ -548,7 +555,12 @@ void Networking::networkReconnectTaskFn(void* param) {
|
||||
|
||||
void Networking::reconnectionTimerCallback(TimerHandle_t xTimer) {
|
||||
if (_instance) {
|
||||
xTaskCreate(networkReconnectTaskFn, "netRecon", 3072, _instance, 5, NULL);
|
||||
// If the task can't be created (fragmented heap), re-arm the one-shot
|
||||
// timer to try again next interval. Before, a single failure ended the
|
||||
// reconnect chain silently. No LOG here — Tmr Svc stack is 2KB.
|
||||
if (xTaskCreate(networkReconnectTaskFn, "netRecon", 3072, _instance, 5, NULL) != pdPASS) {
|
||||
xTimerStart(xTimer, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -787,7 +787,11 @@ void Player::onMelodyLoopCompleted() {
|
||||
|
||||
// Check if it's time to pause playback
|
||||
bool Player::timeToPause(unsigned long now) {
|
||||
if (isPlaying && continuous_loop) {
|
||||
// segment_duration == 0 means "no segments" (mode "infinite", or v1
|
||||
// continuous_loop with no segment length). Without this guard every timer
|
||||
// tick paused and the next resumed, so status flipped playing/paused about
|
||||
// twice a second for the whole melody, on WebSocket and MQTT (F-074).
|
||||
if (isPlaying && continuous_loop && segment_duration > 0) {
|
||||
uint64_t timeToPause = segmentStartTime + (uint64_t)segment_duration;
|
||||
if ((uint64_t)now >= timeToPause && !isPaused) {
|
||||
_pendingPauseReason = "Segment duration reached — pausing";
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "CrashBreadcrumbs.hpp"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <esp_attr.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_system.h>
|
||||
|
||||
namespace {
|
||||
constexpr uint32_t SNAPSHOT_MAGIC = 0x56534E50; // "VSNP"
|
||||
constexpr uint32_t ABORT_MAGIC = 0x56414252; // "VABR"
|
||||
|
||||
struct RtcBreadcrumbs {
|
||||
uint32_t snapshotMagic;
|
||||
uint32_t uptimeMs;
|
||||
uint32_t freeHeap;
|
||||
uint32_t largestBlock;
|
||||
uint32_t minFreeHeap;
|
||||
uint32_t abortMagic;
|
||||
char abortMsg[sizeof(PreCrashSnapshot::abortMsg)];
|
||||
};
|
||||
|
||||
// Not zeroed on boot — that's the point. Validated by the magic words.
|
||||
RTC_NOINIT_ATTR RtcBreadcrumbs s_rtc;
|
||||
}
|
||||
|
||||
// Link-time wrapper: every esp_system_abort() call in the SDK (abort, assert,
|
||||
// stack-overflow hook) lands here first. Runs in whatever context aborted —
|
||||
// possibly with the heap lock held or the flash cache disabled — so it only
|
||||
// copies bytes into RTC memory: no allocation, no locks, no libc, IRAM only.
|
||||
extern "C" void __real_esp_system_abort(const char* details) __attribute__((noreturn));
|
||||
|
||||
extern "C" void IRAM_ATTR __attribute__((noreturn)) __wrap_esp_system_abort(const char* details) {
|
||||
size_t i = 0;
|
||||
if (details) {
|
||||
for (; i < sizeof(s_rtc.abortMsg) - 1 && details[i] != '\0'; i++) {
|
||||
s_rtc.abortMsg[i] = details[i];
|
||||
}
|
||||
}
|
||||
s_rtc.abortMsg[i] = '\0';
|
||||
s_rtc.abortMagic = ABORT_MAGIC;
|
||||
__real_esp_system_abort(details);
|
||||
}
|
||||
|
||||
namespace CrashBreadcrumbs {
|
||||
|
||||
void updateSnapshot() {
|
||||
s_rtc.uptimeMs = millis();
|
||||
s_rtc.freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT);
|
||||
s_rtc.largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
|
||||
s_rtc.minFreeHeap = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT);
|
||||
s_rtc.snapshotMagic = SNAPSHOT_MAGIC;
|
||||
}
|
||||
|
||||
PreCrashSnapshot consume() {
|
||||
PreCrashSnapshot out;
|
||||
if (s_rtc.snapshotMagic == SNAPSHOT_MAGIC) {
|
||||
out.available = true;
|
||||
out.uptimeMs = s_rtc.uptimeMs;
|
||||
out.freeHeap = s_rtc.freeHeap;
|
||||
out.largestBlock = s_rtc.largestBlock;
|
||||
out.minFreeHeap = s_rtc.minFreeHeap;
|
||||
}
|
||||
if (s_rtc.abortMagic == ABORT_MAGIC) {
|
||||
out.available = true;
|
||||
memcpy(out.abortMsg, s_rtc.abortMsg, sizeof(out.abortMsg));
|
||||
out.abortMsg[sizeof(out.abortMsg) - 1] = '\0';
|
||||
}
|
||||
s_rtc.snapshotMagic = 0;
|
||||
s_rtc.abortMagic = 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// CRASH BREADCRUMBS — context that survives a panic reboot (F-070)
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// The coredump summary (see Telemetry::captureCrashReport) only knows the CPU
|
||||
// state at the moment the chip went down. For an abort() — unhandled C++
|
||||
// exception, failed assert, FreeRTOS stack-overflow check — that state is
|
||||
// panic_abort()'s own deliberate write to address 0, so PC/cause/vaddr say
|
||||
// nothing about *why* (see F-055). Two things fill that gap, both kept in
|
||||
// RTC_NOINIT memory, which survives software/panic/watchdog resets but NOT
|
||||
// power-on or brownout:
|
||||
//
|
||||
// 1. The abort reason string — captured by wrapping esp_system_abort() at
|
||||
// link time (-Wl,--wrap=esp_system_abort in platformio.ini). Every abort
|
||||
// path in this SDK funnels through it: abort() ("abort() was called at PC
|
||||
// 0x... on core N" — that PC is abort()'s caller), assert ("assert failed:
|
||||
// func file:line (expr)"), and the FreeRTOS stack-overflow hook.
|
||||
// 2. A heap/uptime snapshot refreshed every second by TelemetryTask — the
|
||||
// last known state right before the reset (fragmentation killed us once).
|
||||
//
|
||||
// Both are consumed once at boot and cleared, so they're reported exactly once.
|
||||
|
||||
struct PreCrashSnapshot {
|
||||
bool available = false;
|
||||
uint32_t uptimeMs = 0; // millis() at the last snapshot before the reset
|
||||
uint32_t freeHeap = 0; // free heap at that snapshot
|
||||
uint32_t largestBlock = 0; // largest allocatable block at that snapshot
|
||||
uint32_t minFreeHeap = 0; // lowest free heap ever seen during that boot
|
||||
char abortMsg[160] = {0}; // empty unless the reset came from esp_system_abort()
|
||||
};
|
||||
|
||||
namespace CrashBreadcrumbs {
|
||||
// Refresh the heap/uptime snapshot. Cheap; called from TelemetryTask every 1s.
|
||||
void updateSnapshot();
|
||||
|
||||
// Read whatever the previous boot left behind, then clear it. Call once,
|
||||
// early in boot, and only trust the result on a fault-class reset — RTC
|
||||
// memory is garbage after a power-on, which the magic check guards against.
|
||||
PreCrashSnapshot consume();
|
||||
}
|
||||
Binary file not shown.
@@ -66,6 +66,7 @@
|
||||
// panic handler automatically on every crash (already enabled in this project's SDK
|
||||
// build; no custom panic hook needed). See CrashReport below.
|
||||
#include <esp_core_dump.h>
|
||||
#include "CrashBreadcrumbs.hpp"
|
||||
|
||||
// Most recent crash's coredump summary, captured once at begin() and erased from
|
||||
// flash immediately after reading so it's reported exactly once. Empty/zeroed
|
||||
@@ -77,6 +78,13 @@ struct CrashReport {
|
||||
uint32_t pc = 0; // Program counter at exception
|
||||
uint32_t excCause = 0; // Xtensa exception cause code
|
||||
uint32_t excVaddr = 0; // Faulting virtual address
|
||||
// F-070: backtrace of the faulting task (decode with addr2line against the
|
||||
// ELF whose SHA matches elfSha). For an abort() the first frames are the
|
||||
// abort machinery; the real call site follows.
|
||||
uint32_t backtrace[16] = {0};
|
||||
uint8_t backtraceDepth = 0;
|
||||
bool backtraceCorrupted = false;
|
||||
char elfSha[APP_ELF_SHA256_SZ] = {0}; // first 16 hex chars of the crashing app's ELF SHA-256
|
||||
};
|
||||
|
||||
// Maximum number of boot log entries retained on SD (rotating)
|
||||
@@ -154,6 +162,10 @@ private:
|
||||
// Most recent crash's coredump summary, if any — read once at begin().
|
||||
CrashReport crashReport;
|
||||
|
||||
// Abort reason + last heap/uptime snapshot from before a fault reset, if
|
||||
// the previous boot left them in RTC memory (F-070). See CrashBreadcrumbs.hpp.
|
||||
PreCrashSnapshot preCrash;
|
||||
|
||||
// Diagnostics — CPU temperature sampled locally every 15s, reduced to
|
||||
// min/max/avg between 5-minute batch reports. See RunningStats above for
|
||||
// why only temperature needs local sampling (stack high-water and the
|
||||
@@ -180,7 +192,10 @@ public:
|
||||
uint32_t getStrikeCount(uint8_t bellIndex);
|
||||
void resetStrikeCounters(); // User-requested reset (per bell or all)
|
||||
|
||||
// Persistence methods
|
||||
// Persistence methods.
|
||||
// saveStrikeCounters() only *requests* the SD write; TelemetryTask does it
|
||||
// within a few ms. Player calls this on stop, inside the command handler —
|
||||
// an inline SD write held the command reply back by 50-100 ms (F-075).
|
||||
void saveStrikeCounters();
|
||||
void loadStrikeCounters();
|
||||
|
||||
@@ -235,6 +250,12 @@ public:
|
||||
// if one was captured. available == false when the last reset wasn't a crash,
|
||||
// or no coredump was found for one that was.
|
||||
const CrashReport& getCrashReport() const { return crashReport; }
|
||||
const PreCrashSnapshot& getPreCrashSnapshot() const { return preCrash; }
|
||||
|
||||
// Serialize the above into the shared JSON shape used by the MQTT
|
||||
// boot_report and the SD boot log. Callers check .available first.
|
||||
void writeCrashJson(JsonObject out) const;
|
||||
void writePreCrashJson(JsonObject out) const;
|
||||
|
||||
// Reset reason (captured once at begin(), before anything else can crash again)
|
||||
esp_reset_reason_t getResetReason() const { return resetReason; }
|
||||
@@ -296,6 +317,13 @@ private:
|
||||
void checkBellLoads();
|
||||
void loadMetrics();
|
||||
void saveMetrics();
|
||||
void writeStrikeCountersNow();
|
||||
|
||||
// Deferred SD writes, set from any task, done by TelemetryTask (F-075)
|
||||
volatile bool _strikeSavePending = false;
|
||||
volatile bool _metricsSavePending = false;
|
||||
TaskHandle_t telemetryTaskHandleForNotify() const;
|
||||
void processPendingSaves();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
+6
-1
@@ -24,8 +24,13 @@
|
||||
// v2.3.0 - Remote-app playback support: richer status/playback (pid/speed/duration/
|
||||
// started_at/source/ts), republish on MQTT connect, specific playback
|
||||
// errors, "loading" state + playback_failed report for downloads
|
||||
// v2.4.0 - MQTT reliability + latency: self-recovering supervisor, LWT fix,
|
||||
// mqtt.status, confirmed QoS 1 for playback/reports (QoS 0 elsewhere),
|
||||
// WiFi modem sleep off, vendored/patched AsyncMqttClient, pinned deps,
|
||||
// WiFi/NTP task-retry, infinite-mode status flicker fix (F-071..F-074)
|
||||
// v2.4.1 - Play/stop replies no longer wait for telemetry SD writes (F-075)
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
#define FW_VERSION "2.3.0"
|
||||
#define FW_VERSION "2.4.1"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// SemVer — lightweight 3-part version struct
|
||||
|
||||
+5
-1
@@ -459,7 +459,11 @@ static void ntpSyncTask(void* param) {
|
||||
|
||||
// Non-blocking NTP sync timer callback — defers work to a task (Tmr Svc stack is only 2KB)
|
||||
void ntpSyncTimerCallback(TimerHandle_t xTimer) {
|
||||
xTaskCreate(ntpSyncTask, "ntpSync", 5120, NULL, 5, NULL);
|
||||
// Task creation can fail on a fragmented heap — re-arm the one-shot timer
|
||||
// and retry in 3s instead of silently skipping the sync.
|
||||
if (xTaskCreate(ntpSyncTask, "ntpSync", 5120, NULL, 5, NULL) != pdPASS) {
|
||||
xTimerStart(xTimer, 0);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
|
||||
// ── Connectivity ─────────────────────────────────────────────────────────────
|
||||
#define HAS_ETHERNET 0 // Ethernet removed in fw v138
|
||||
#define HAS_RF 1 // RF remote receiver present (GPIO RF_RX_PIN)
|
||||
#define RF_RX_PIN 22 // GPIO pin for RF receiver DATA line
|
||||
#define HAS_RF 0 // No RF receiver on any fielded Vesper Standard unit
|
||||
#define RF_RX_PIN 22 // Unused while HAS_RF=0 — pin the receiver would use if one is ever fitted
|
||||
#define HAS_LCD 0 // No onboard LCD
|
||||
|
||||
// ── Output hardware ──────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user