mirror of
https://github.com/jhuebert/MeshCore.git
synced 2026-12-02 02:18:36 +00:00
feat: support two MQTT observer broker slots
Rework the observer configuration to numbered mqtt1.*/mqtt2.* broker slots with shared mqtt.* settings, expand the observer target catalog, and update the user guide and tests.
This commit is contained in:
1 parent
d7987cf653
commit
3c4bb6b277
10 files changed
+1424
-916
No files matched your search
+134
-96
@@ -3,7 +3,7 @@
|
||||
MQTT observer builds publish successfully parsed packets heard over radio. The
|
||||
receive hook runs before forwarding policy, so packet filters, the battery gate,
|
||||
repeat enablement, hop/loop limits, and region policy do not suppress
|
||||
observations. This is a best-effort, live feed—not a packet archive.
|
||||
observations. This is a best-effort feed, not a packet archive.
|
||||
|
||||
## Build target and status
|
||||
|
||||
@@ -11,119 +11,139 @@ The optional targets are defined in [`observer_targets.ini`](./observer_targets.
|
||||
which is also the allowlist used by `build.sh`:
|
||||
|
||||
```sh
|
||||
pio run -e Xiao_S3_WIO_repeater_observer_mqtt
|
||||
pio run -e Xiao_S3_WIO_repeater_observer
|
||||
```
|
||||
|
||||
Only the XIAO S3 WIO target is currently listed. It compiles, but still needs
|
||||
on-device memory, RF-load, TLS, broker, and OTA acceptance testing. Treat it as
|
||||
experimental until those checks are complete. Standard repeater targets do not
|
||||
depend on the MQTT library or compile observer sources. Optional release builds
|
||||
can be selected separately with `scripts/local-release-build.sh --observers
|
||||
<release-url-or-tag>`.
|
||||
Observer-enabled Repeater targets cover the supported Observer board list:
|
||||
Heltec T190, Tracker V1.1 and V2, V3, WSL3, V4 and V4 ExpansionKit; LilyGo
|
||||
T3-S3 SX1262, T-Beam 1W, T-Beam S3 Supreme SX1262, T-Beam SX1262 and SX1276;
|
||||
RAK 3112; Station G2 and G3; ThinkNode M7; and XIAO S3 WIO.
|
||||
Room Server targets are intentionally not included. All 17 Repeater target
|
||||
environments compile, but still need per-board memory, RF-load, TLS, broker, and
|
||||
OTA acceptance testing; treat them as experimental until those checks are
|
||||
complete. The T3-S3 and T-Beam 1W observer targets use `min_spiffs.csv`, and
|
||||
Station G2/G3 use `default_16MB.csv`, to fit the larger app. Those partition
|
||||
overrides can require a merged image when converting an existing node and may
|
||||
reset filesystem-backed settings. Standard repeater targets do not depend on
|
||||
the MQTT library or compile observer sources. Optional release builds can be
|
||||
selected separately with
|
||||
`scripts/local-release-build.sh --observers <release-url-or-tag>`.
|
||||
|
||||
The MIT-licensed PsychicMqttClient is pinned to commit
|
||||
`9e3005571918fdd83a2521243c501d1af137b0b6`. TLS uses the ESP32 Arduino CA
|
||||
bundle with certificate validation and needs a valid device clock. JWT
|
||||
authentication uses the MeshCore Ed25519 identity and broker-specific audience.
|
||||
authentication uses the MeshCore Ed25519 identity and a per-broker audience.
|
||||
|
||||
## Configure
|
||||
|
||||
The observer is disabled on a fresh install. This build uses the same shared
|
||||
MQTT command names as agessaman's observer. Since it has one broker, the
|
||||
reference's slot settings (`mqtt1.*`) are unnumbered `mqtt.*` settings:
|
||||
The observer is disabled on a fresh install and supports two independent MQTT
|
||||
broker slots. Broker-specific settings always use numbered commands (`mqtt1.*`,
|
||||
`mqtt2.*`) to match agessaman's CLI; unnumbered `mqtt.*` commands are only for
|
||||
shared settings such as IATA, origin, and publish switches. Broker credentials
|
||||
and topic templates are independent. Wi-Fi, IATA, origin, NTP, status interval,
|
||||
and packet/status/raw enable switches are shared.
|
||||
|
||||
```text
|
||||
set wifi.ssid YourNetwork
|
||||
set wifi.pwd YourWiFiPassword
|
||||
set mqtt.server wss://broker.example:443/mqtt
|
||||
set mqtt.audience broker.example
|
||||
set mqtt1.server wss://first.example:443/mqtt
|
||||
set mqtt1.audience first.example
|
||||
set mqtt2.server mqtts://second.example:8883
|
||||
set mqtt2.username observer
|
||||
set mqtt2.password secret
|
||||
set mqtt.iata SEA
|
||||
set mqtt on
|
||||
set mqtt1.enabled on
|
||||
set mqtt2.enabled on
|
||||
get mqtt.status
|
||||
get mqtt1.status
|
||||
get mqtt2.status
|
||||
```
|
||||
|
||||
The server can also be configured as a hostname and port separately:
|
||||
For a username/password connection, set that slot's `username` and `password`
|
||||
and leave its `audience` empty. JWT mode takes precedence when that slot has an
|
||||
audience configured; it uses username `v1_<PUBLIC_KEY_HEX>` and a 24-hour Ed25519-signed token. The
|
||||
worker waits for valid time before connecting and renews tokens before expiry.
|
||||
Optional per-slot `owner` and `email` values are included in JWT claims. Secrets
|
||||
are not echoed by set/get replies or fleet-script logs.
|
||||
|
||||
A server may be configured as a hostname and port separately. Use `mqtts://`
|
||||
for MQTT over TLS, `wss://` for secure WebSockets, `mqtt://` for trusted private
|
||||
networks, or `ws://` for trusted private networks. Secure URLs retain hostname
|
||||
and certificate verification. Do not use plain transport on an untrusted
|
||||
network. URLs must not contain embedded `username:password@` credentials. With
|
||||
a full URL, an explicit URL port takes precedence; otherwise that slot's
|
||||
`mqttN.port` supplies the port. Host-only values infer `mqtts://` for port 8883,
|
||||
`wss://` for 443, and `mqtt://` otherwise.
|
||||
|
||||
Supported commands include:
|
||||
|
||||
```text
|
||||
set mqtt.server broker.example
|
||||
set mqtt.port 1883
|
||||
```
|
||||
|
||||
Use `mqtts://` for MQTT over TLS, `wss://` for MQTT over secure WebSockets,
|
||||
`mqtt://` for trusted private networks, or `ws://` for trusted private
|
||||
networks. Secure URLs retain hostname and certificate verification. Do not use
|
||||
plain transport on an untrusted network. URLs must not contain embedded
|
||||
`username:password@` credentials. With a full URL, an explicit URL port takes
|
||||
precedence; otherwise `mqtt.port` supplies the port. Host-only values infer
|
||||
`mqtts://` for port 8883, `wss://` for 443, and `mqtt://` otherwise.
|
||||
|
||||
For username/password authentication, set `mqtt.username` and `mqtt.password`
|
||||
and clear the JWT audience. JWT mode takes precedence whenever an audience is
|
||||
configured; it uses username `v1_<PUBLIC_KEY_HEX>` and a 24-hour Ed25519-signed
|
||||
token. The worker waits for valid time before connecting and renews the token
|
||||
before expiry. Optional `mqtt.owner` and `mqtt.email` values are included in
|
||||
JWT claims. Secrets are not echoed by set/get replies or fleet-script logs.
|
||||
|
||||
Supported commands:
|
||||
|
||||
```text
|
||||
set mqtt.origin <name> # empty follows the repeater node name
|
||||
set mqtt.iata <code> # 3 letters/digits, auto-uppercased; XXX reserved
|
||||
set mqtt.server <host-or-URL>
|
||||
set mqtt.port <1-65535>
|
||||
set mqtt.username <username>
|
||||
set mqtt.password <password>
|
||||
set mqtt.audience <JWT audience> # empty clears JWT mode
|
||||
set mqtt.owner <public-key-hex> # optional JWT claim
|
||||
set mqtt.email <email> # optional JWT claim
|
||||
set mqtt.topic <template> # optional custom topic layout
|
||||
set mqtt.token <token> # optional {token} topic-template value
|
||||
set mqtt.ntp <hostname> # none restores pool.ntp.org
|
||||
set mqtt.interval <1-60> # status interval in minutes
|
||||
set mqtt.rx on|off # gate received packet/raw events
|
||||
set mqtt.status on|off # status topic
|
||||
set mqtt.packets on|off # parsed packet topic
|
||||
set mqtt.raw on|off # raw radio frame topic
|
||||
set mqttN.server <host-or-URL>
|
||||
set mqttN.port <1-65535>
|
||||
set mqttN.username <username>
|
||||
set mqttN.password <password>
|
||||
set mqttN.audience <JWT audience> # empty clears JWT mode
|
||||
set mqttN.owner <public-key-hex> # optional JWT claim
|
||||
set mqttN.email <email> # optional JWT claim
|
||||
set mqttN.topic <template> # optional per-broker topic layout
|
||||
set mqttN.token <token> # optional {token} template value
|
||||
set mqttN.enabled on|off # enable/disable that slot
|
||||
set mqtt.origin <name> # empty follows the repeater node name
|
||||
set mqtt.iata <code> # 3 letters/digits, auto-uppercased; XXX reserved
|
||||
set mqtt.ntp <hostname> # none restores pool.ntp.org
|
||||
set mqtt.interval <1-60> # shared status interval, in minutes
|
||||
set mqtt.rx on|off # shared received-packet/raw capture gate
|
||||
set mqtt.status on|off # shared status publish switch
|
||||
set mqtt.packets on|off # shared parsed-packet publish switch
|
||||
set mqtt.raw on|off # shared raw-frame publish switch
|
||||
set wifi.powersave none|min|max
|
||||
set mqtt on|off
|
||||
get mqtt.status
|
||||
get mqtt.status # combined connection/queue summary
|
||||
get mqttN.status # one slot's connection state
|
||||
get mqttN.enabled
|
||||
get mqttN.server
|
||||
get mqttN.port
|
||||
get mqttN.audience
|
||||
get mqttN.owner
|
||||
get mqttN.email
|
||||
get mqttN.username
|
||||
get mqttN.password # configured/not set only
|
||||
get mqttN.token # configured/not set only
|
||||
get mqttN.topic
|
||||
get mqtt.iata
|
||||
get mqtt.origin
|
||||
get mqtt.server
|
||||
get mqtt.port
|
||||
get mqtt.audience
|
||||
get mqtt.owner
|
||||
get mqtt.email
|
||||
get mqtt.username
|
||||
get mqtt.password # configured/not set only
|
||||
get mqtt.token # configured/not set only
|
||||
get mqtt.topic
|
||||
get mqtt.ntp
|
||||
get mqtt.interval
|
||||
get mqtt.rx
|
||||
get mqtt.status.enabled
|
||||
get mqtt.packets
|
||||
get mqtt.raw
|
||||
get wifi.status # connection, IP, RSSI
|
||||
get wifi.status # connection, IP, RSSI
|
||||
get wifi.ssid
|
||||
get wifi.powersave
|
||||
```
|
||||
|
||||
This focused image does not include presets, additional broker slots, packet
|
||||
allowlists, TX uplink, neighbor queries, WebConfig, SNMP, or alerting. It
|
||||
reports all MeshCore packet types received when `mqtt.rx` and packet/raw
|
||||
publishing are enabled; it does not couple observation to repeater filtering.
|
||||
`N` is the one-based slot number (`1` or `2` in this build). The worker uses
|
||||
a compile-time slot array; `MQTT_OBSERVER_MAX_BROKERS` defaults to 2 and may be
|
||||
raised up to 6 at build time. Six broker records are reserved
|
||||
in `/mqtt_prefs`, so raising the active count up to 6 does not change the config
|
||||
format or require a migration. Increasing the reserved storage capacity beyond
|
||||
six would require a format migration. The observer does not include presets,
|
||||
packet allowlists, TX uplink, neighbor queries, WebConfig, SNMP, or alerting. It reports all MeshCore packet types received when the
|
||||
shared RX and packet/raw switches are enabled.
|
||||
|
||||
SSID/password values are the rest of the command line; do not quote them. An
|
||||
empty value clears a string setting. Settings are saved lazily about three
|
||||
seconds after a change. Credentials are stored in `/mqtt_prefs` using a
|
||||
versioned, CRC-checked staged save; version-1 settings migrate to version 2
|
||||
without losing Wi-Fi or broker credentials. The filesystem is not encrypted: an
|
||||
seconds after a change. The experimental `/mqtt_prefs` record is versioned and
|
||||
CRC-checked. Its six reserved broker records keep the persisted layout stable
|
||||
when `MQTT_OBSERVER_MAX_BROKERS` is raised up to 6. No migration from the earlier
|
||||
prototype format is included because this observer has not been deployed and
|
||||
there are no device configs to preserve. The filesystem is not encrypted; an
|
||||
administrator with filesystem or firmware access can recover credentials.
|
||||
Commands pass through the repeater's existing CLI permission boundary.
|
||||
|
||||
## Topics and payloads
|
||||
|
||||
By default, topics follow the MeshCore convention:
|
||||
By default each enabled broker uses the MeshCore topic convention:
|
||||
|
||||
```text
|
||||
meshcore/{IATA}/{DEVICE_PUBLIC_KEY}/status
|
||||
@@ -131,9 +151,9 @@ meshcore/{IATA}/{DEVICE_PUBLIC_KEY}/packets
|
||||
meshcore/{IATA}/{DEVICE_PUBLIC_KEY}/raw
|
||||
```
|
||||
|
||||
`DEVICE_PUBLIC_KEY` is the uppercase hexadecimal Ed25519 public key. A custom
|
||||
`mqtt.topic` template supports `{iata}`, `{device}`, `{token}`, and `{type}`
|
||||
(`status`, `packets`, or `raw`).
|
||||
`DEVICE_PUBLIC_KEY` is the uppercase hexadecimal Ed25519 public key. A
|
||||
per-broker `mqttN.topic` template supports `{iata}`, `{device}`, `{token}`, and
|
||||
`{type}` (`status`, `packets`, or `raw`).
|
||||
|
||||
The packet schema includes `type: "PACKET"`, `direction: "rx"`, an ISO-8601
|
||||
UTC timestamp, origin and device identity, MeshCore packet hash, route, wire
|
||||
@@ -146,26 +166,43 @@ client version is `meshcore-jhuebert/<firmware-version>` to distinguish this
|
||||
fork from other MeshCore clients.
|
||||
|
||||
Packet/raw publishes are QoS 0, non-retained, and sent synchronously with a
|
||||
2.5-second network timeout. Status is QoS 1, non-retained for this custom
|
||||
endpoint, sent on connect and every five minutes by default (`mqtt.interval`
|
||||
changes the interval). The broker may apply its own retention policy.
|
||||
2.5-second network timeout. Status is QoS 1, non-retained, sent on connect and
|
||||
every five minutes by default (`mqtt.interval` changes the shared interval).
|
||||
Failed status publishes are retried no faster than every 30 seconds per slot.
|
||||
The broker may apply its own retention policy.
|
||||
|
||||
## Live-only delivery and resilience
|
||||
## Bounded queue and delivery behavior
|
||||
|
||||
The radio receive hook copies raw bytes, the parsed packet, RF measurements,
|
||||
and receive timestamp before dispatcher-owned packet storage is reused. A
|
||||
four-entry RAM queue transfers snapshots to the MQTT worker. Overflow evicts
|
||||
the oldest entry to favor recent traffic. Events enter the queue only while the
|
||||
broker is connected; disconnect purges pending entries, and reconnect resumes
|
||||
with newly heard packets. Entries older than ten seconds are dropped instead
|
||||
of delivered late. No packet event, queue entry, or offline history is written
|
||||
The receive hook copies raw bytes, the parsed packet, RF measurements, and
|
||||
receive timestamp before dispatcher-owned packet storage is reused. A bounded
|
||||
RAM queue transfers snapshots to the MQTT worker, including while both brokers
|
||||
are temporarily disconnected. The default capacity is 8 events and can be
|
||||
overridden at build time with `-DMQTT_OBSERVER_QUEUE_CAPACITY=<count>`; this
|
||||
capacity is shared by all broker slots and does not change `/mqtt_prefs`. The queue holds an event at its head
|
||||
while the synchronous publish attempt is in progress, so capture-side overflow
|
||||
cannot evict that in-flight event. When full, the oldest pending event is
|
||||
replaced; with capacity 1, a new event is dropped while the sole entry is in
|
||||
flight.
|
||||
|
||||
On a failed attempt, the queue retries up to three times with a short
|
||||
300–499 ms delay. Pending events are flushed after one continuous minute with
|
||||
no connected broker. No packet event, queue entry, or offline history is written
|
||||
to flash or replayed after reboot. Publish work, TLS, NTP, and reconnects run
|
||||
outside the receive and forwarding path.
|
||||
|
||||
`get mqtt.status` reports enabled/configuration state, Wi-Fi and clock/JWT
|
||||
readiness, broker state, received/published/drop counters, queue depth, and
|
||||
free/largest heap figures. The four-entry queue and age limit are intentionally
|
||||
small: delayed packet delivery is not useful for the intended observer feed.
|
||||
Both connected slots are offered each queued event. Following the reference
|
||||
observer's queue policy, the event is considered delivered when any connected
|
||||
slot successfully publishes either the structured packet or raw frame; a
|
||||
partial success is not retried for the other slot. Thus the queue protects
|
||||
observations during transient send failures, but does not guarantee delivery to
|
||||
every configured broker during a per-slot outage. QoS 0 is also inherently
|
||||
best-effort: a connection loss after the broker accepts a publish but before
|
||||
the sender can confirm the write may result in a duplicate retry or an
|
||||
unrecoverable loss.
|
||||
|
||||
`get mqtt.status` reports Wi-Fi/clock state, connected slot count, received and
|
||||
published counters, drops, queue depth/capacity, and free/largest heap figures.
|
||||
`get mqttN.status` reports the connection state for an individual slot.
|
||||
|
||||
Capture begins at `logRx()`, after a packet object has been allocated and the
|
||||
radio frame parsed. Invalid frames are excluded. The repeater currently uses a
|
||||
@@ -180,6 +217,7 @@ packet-pool availability.
|
||||
The observer target has been compile-tested on the XIAO S3 WIO. Build success
|
||||
does not establish runtime TLS heap margin, worker stack high-water, OTA
|
||||
behavior, or capture resilience under sustained RF/outbound pressure. Complete
|
||||
hardware checks for internal heap/largest block during Wi-Fi/TLS/reconnect,
|
||||
worker stack use, a compatible local broker, outage recovery, and no late or
|
||||
replayed events before treating the target as production-qualified.
|
||||
hardware checks for internal heap/largest block during two simultaneous
|
||||
Wi-Fi/TLS connections and reconnects, queue behavior under broker outages,
|
||||
worker stack use, compatible local brokers, and no late/replayed events before
|
||||
treating the target as production-qualified.
|
||||
@@ -204,7 +204,7 @@ get_observer_envs() {
|
||||
printf '%s' "$PIO_CONFIG_JSON" | python3 -c '
|
||||
import json, sys
|
||||
for section, _ in json.load(sys.stdin):
|
||||
if section.startswith("env:") and section.endswith("_repeater_observer_mqtt"):
|
||||
if section.startswith("env:") and section.endswith("_repeater_observer"):
|
||||
print(section[4:])
|
||||
'
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -23,7 +23,6 @@ class MQTTObserver {
|
||||
uint16_t raw_len;
|
||||
time_t timestamp;
|
||||
long timestamp_usec;
|
||||
uint32_t received_ms;
|
||||
float snr;
|
||||
float rssi;
|
||||
float score;
|
||||
@@ -34,7 +33,30 @@ class MQTTObserver {
|
||||
STATE_CONNECTED, STATE_RETRY, STATE_ERROR
|
||||
};
|
||||
|
||||
static const size_t kQueueCapacity = 4;
|
||||
struct BrokerRuntime {
|
||||
PsychicMqttClient* client;
|
||||
char server_uri[sizeof(MQTTObserverBrokerConfig::server) + 16];
|
||||
char username[65];
|
||||
char password[65];
|
||||
char jwt_username[3 + 2 * PUB_KEY_SIZE + 1];
|
||||
char jwt_token[1024];
|
||||
uint32_t jwt_expiry;
|
||||
uint32_t next_connect_ms;
|
||||
uint32_t attempt_started;
|
||||
std::atomic<uint32_t> connected_at;
|
||||
uint32_t last_status_ms;
|
||||
uint32_t status_retry_ms;
|
||||
uint8_t backoff_index;
|
||||
bool status_retry_pending;
|
||||
bool client_started;
|
||||
bool configured;
|
||||
std::atomic<bool> connected;
|
||||
std::atomic<bool> status_pending;
|
||||
std::atomic<State> state;
|
||||
|
||||
BrokerRuntime();
|
||||
};
|
||||
|
||||
static const uint32_t kMinimumValidTime = 1735689600UL;
|
||||
static const uint32_t kJwtLifetimeSeconds = 86400;
|
||||
|
||||
@@ -47,28 +69,22 @@ class MQTTObserver {
|
||||
uint8_t _radio_sf;
|
||||
uint8_t _radio_cr;
|
||||
MQTTObserverConfig _config;
|
||||
MQTTObserverConfig _runtime_config;
|
||||
MQTTObserverConfig _work_config;
|
||||
MQTTObserverConfig _io_config;
|
||||
uint8_t _save_record[MQTTObserverRecord::kRecordSize];
|
||||
uint8_t _load_record[MQTTObserverRecord::kRecordSize];
|
||||
mutable portMUX_TYPE _config_mux;
|
||||
portMUX_TYPE _queue_mux;
|
||||
MQTTObserverLiveQueue<Event, kQueueCapacity> _queue;
|
||||
MQTTObserverEventQueue<Event, MQTT_OBSERVER_QUEUE_CAPACITY> _queue;
|
||||
MQTTObserverRawStager _raw_stager;
|
||||
PsychicMqttClient* _client;
|
||||
TaskHandle_t _task;
|
||||
MQTTObserverConfig _runtime_config;
|
||||
char _device_id[2 * PUB_KEY_SIZE + 1];
|
||||
// PsychicMqttClient keeps the URI pointer in its client config across async connects.
|
||||
char _server_uri[sizeof(_config.server) + 16];
|
||||
char _jwt_username[3 + 2 * PUB_KEY_SIZE + 1];
|
||||
char _jwt_token[1024];
|
||||
char _json[2048];
|
||||
bool _connected;
|
||||
bool _status_pending;
|
||||
BrokerRuntime _brokers[MQTT_OBSERVER_MAX_BROKERS];
|
||||
bool _wifi_started;
|
||||
bool _client_started;
|
||||
uint32_t _next_connect_ms;
|
||||
uint32_t _last_status_ms;
|
||||
uint32_t _jwt_expiry;
|
||||
uint8_t _backoff_index;
|
||||
TaskHandle_t _task;
|
||||
uint32_t _queue_disconnected_since;
|
||||
uint32_t _last_ntp_request;
|
||||
char _device_id[2 * PUB_KEY_SIZE + 1];
|
||||
char _json[2048];
|
||||
std::atomic<State> _state;
|
||||
LazySave _save_state;
|
||||
std::atomic<uint32_t> _received;
|
||||
@@ -80,22 +96,25 @@ class MQTTObserver {
|
||||
static void taskEntry(void* context);
|
||||
void worker();
|
||||
void copyConfig(MQTTObserverConfig& config);
|
||||
bool ready(const MQTTObserverConfig& config) const;
|
||||
bool configureClient(const MQTTObserverConfig& config);
|
||||
bool createJwt(char* token, size_t capacity, uint32_t& expires_at);
|
||||
bool ready(const MQTTObserverConfig& config, size_t slot) const;
|
||||
bool configureClient(size_t slot, const MQTTObserverBrokerConfig& config);
|
||||
bool createJwt(size_t slot, const MQTTObserverBrokerConfig& config, uint32_t& expires_at);
|
||||
bool publishEvent(const Event& event);
|
||||
bool publishStatus();
|
||||
void clearQueueOnDisconnect();
|
||||
bool publishStatus(size_t slot);
|
||||
void disconnectBroker(size_t slot);
|
||||
void flushQueue();
|
||||
size_t queueSize();
|
||||
void markDirty();
|
||||
bool saveConfig();
|
||||
static bool writeRecord(File& file, void* context);
|
||||
static bool validateRecord(File& file, void* context);
|
||||
static bool readRecord(File& file, MQTTObserverConfig& config);
|
||||
bool readRecord(File& file, MQTTObserverConfig& config);
|
||||
bool handleSetCommand(char* command, char* reply);
|
||||
bool handleGetCommand(const char* command, char* reply);
|
||||
bool setString(char* destination, size_t capacity, const char* value);
|
||||
const char* stateName() const;
|
||||
const char* stateName(State state) const;
|
||||
bool commandSlot(const char* command, const char* operation, size_t& slot,
|
||||
const char*& property) const;
|
||||
|
||||
public:
|
||||
MQTTObserver();
|
||||
|
||||
@@ -2,37 +2,60 @@
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
struct MQTTObserverConfig {
|
||||
#ifndef MQTT_OBSERVER_MAX_BROKERS
|
||||
#define MQTT_OBSERVER_MAX_BROKERS 2 // Active broker clients configured by mqttN.*
|
||||
#endif
|
||||
|
||||
// Reserve the full slot array so increasing the active count does not move the record layout.
|
||||
static const size_t MQTT_OBSERVER_CONFIG_BROKER_CAPACITY = 6;
|
||||
|
||||
#ifndef MQTT_OBSERVER_QUEUE_CAPACITY
|
||||
#define MQTT_OBSERVER_QUEUE_CAPACITY 8 // Captured packet events shared by all broker slots
|
||||
#endif
|
||||
|
||||
static_assert(MQTT_OBSERVER_MAX_BROKERS > 0 &&
|
||||
MQTT_OBSERVER_MAX_BROKERS <= MQTT_OBSERVER_CONFIG_BROKER_CAPACITY,
|
||||
"active MQTT broker count exceeds stored slot capacity");
|
||||
static_assert(MQTT_OBSERVER_QUEUE_CAPACITY > 0, "MQTT observer queue must have capacity");
|
||||
|
||||
struct MQTTObserverBrokerConfig {
|
||||
uint8_t enabled;
|
||||
uint8_t status_enabled;
|
||||
uint8_t packets_enabled;
|
||||
uint8_t raw_enabled;
|
||||
char wifi_ssid[33];
|
||||
char wifi_password[65];
|
||||
uint16_t port;
|
||||
char server[129];
|
||||
char username[65];
|
||||
char password[65];
|
||||
char audience[65];
|
||||
char iata[4];
|
||||
uint8_t rx_enabled;
|
||||
uint8_t status_interval_minutes;
|
||||
uint16_t port;
|
||||
char origin[33];
|
||||
char topic[129];
|
||||
char token[65];
|
||||
char ntp_server[65];
|
||||
char owner[65];
|
||||
char email[65];
|
||||
};
|
||||
|
||||
struct MQTTObserverConfig {
|
||||
uint8_t status_enabled;
|
||||
uint8_t packets_enabled;
|
||||
uint8_t raw_enabled;
|
||||
uint8_t rx_enabled;
|
||||
uint8_t status_interval_minutes;
|
||||
uint8_t wifi_power_save;
|
||||
char wifi_ssid[33];
|
||||
char wifi_password[65];
|
||||
char iata[4];
|
||||
char origin[33];
|
||||
char ntp_server[65];
|
||||
MQTTObserverBrokerConfig brokers[MQTT_OBSERVER_CONFIG_BROKER_CAPACITY];
|
||||
};
|
||||
|
||||
namespace MQTTObserverConfigCodec {
|
||||
|
||||
static const uint8_t kVersion = 2;
|
||||
static const size_t kLegacyPayloadSize = 4 + 33 + 65 + 129 + 65 + 65 + 65 + 4;
|
||||
static const size_t kPayloadSize = kLegacyPayloadSize + 1 + 1 + 2 + 33 + 129 + 65 + 65 + 65 + 65 + 1;
|
||||
static const uint8_t kVersion = 3;
|
||||
static const size_t kCommonPayloadSize = 6 + 33 + 65 + 4 + 33 + 65;
|
||||
static const size_t kBrokerPayloadSize = 1 + 2 + 129 + 65 + 65 + 65 + 129 + 65 + 65 + 65;
|
||||
static const size_t kPayloadSize = kCommonPayloadSize +
|
||||
MQTT_OBSERVER_CONFIG_BROKER_CAPACITY * kBrokerPayloadSize;
|
||||
|
||||
inline void setDefaults(MQTTObserverConfig& config) {
|
||||
memset(&config, 0, sizeof(config));
|
||||
@@ -41,8 +64,9 @@ inline void setDefaults(MQTTObserverConfig& config) {
|
||||
config.raw_enabled = 1;
|
||||
config.rx_enabled = 1;
|
||||
config.status_interval_minutes = 5;
|
||||
config.port = 1883;
|
||||
config.wifi_power_save = 1;
|
||||
for (size_t i = 0; i < MQTT_OBSERVER_CONFIG_BROKER_CAPACITY; i++)
|
||||
config.brokers[i].port = 1883;
|
||||
}
|
||||
|
||||
inline bool validServer(const char* server) {
|
||||
@@ -131,132 +155,117 @@ inline bool validNtpServer(const char* server) {
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool validBroker(const MQTTObserverBrokerConfig& broker) {
|
||||
if (broker.enabled > 1 || broker.port == 0) return false;
|
||||
if (!memchr(broker.server, 0, sizeof(broker.server)) ||
|
||||
!memchr(broker.username, 0, sizeof(broker.username)) ||
|
||||
!memchr(broker.password, 0, sizeof(broker.password)) ||
|
||||
!memchr(broker.audience, 0, sizeof(broker.audience)) ||
|
||||
!memchr(broker.topic, 0, sizeof(broker.topic)) ||
|
||||
!memchr(broker.token, 0, sizeof(broker.token)) ||
|
||||
!memchr(broker.owner, 0, sizeof(broker.owner)) ||
|
||||
!memchr(broker.email, 0, sizeof(broker.email))) return false;
|
||||
if (!validAudience(broker.audience) || !validTopic(broker.topic) ||
|
||||
!validTopic(broker.token) || !validOwner(broker.owner) ||
|
||||
!validEmail(broker.email)) return false;
|
||||
return broker.server[0] == 0 || validServer(broker.server);
|
||||
}
|
||||
|
||||
inline bool valid(const MQTTObserverConfig& config) {
|
||||
if (config.enabled > 1 || config.status_enabled > 1 ||
|
||||
config.packets_enabled > 1 || config.raw_enabled > 1 || config.rx_enabled > 1 ||
|
||||
config.status_interval_minutes < 1 || config.status_interval_minutes > 60 ||
|
||||
config.port == 0 || config.wifi_power_save > 2) return false;
|
||||
if (config.status_enabled > 1 || config.packets_enabled > 1 || config.raw_enabled > 1 ||
|
||||
config.rx_enabled > 1 || config.status_interval_minutes < 1 ||
|
||||
config.status_interval_minutes > 60 || config.wifi_power_save > 2) return false;
|
||||
if (!memchr(config.wifi_ssid, 0, sizeof(config.wifi_ssid)) ||
|
||||
!memchr(config.wifi_password, 0, sizeof(config.wifi_password)) ||
|
||||
!memchr(config.server, 0, sizeof(config.server)) ||
|
||||
!memchr(config.username, 0, sizeof(config.username)) ||
|
||||
!memchr(config.password, 0, sizeof(config.password)) ||
|
||||
!memchr(config.audience, 0, sizeof(config.audience)) ||
|
||||
!memchr(config.iata, 0, sizeof(config.iata)) ||
|
||||
!memchr(config.origin, 0, sizeof(config.origin)) ||
|
||||
!memchr(config.topic, 0, sizeof(config.topic)) ||
|
||||
!memchr(config.token, 0, sizeof(config.token)) ||
|
||||
!memchr(config.ntp_server, 0, sizeof(config.ntp_server)) ||
|
||||
!memchr(config.owner, 0, sizeof(config.owner)) ||
|
||||
!memchr(config.email, 0, sizeof(config.email))) return false;
|
||||
if (!validIata(config.iata) || !validAudience(config.audience) ||
|
||||
!validTopic(config.topic) || !validTopic(config.token) ||
|
||||
!validNtpServer(config.ntp_server) ||
|
||||
!validOwner(config.owner) || !validEmail(config.email)) return false;
|
||||
return config.server[0] == 0 || validServer(config.server);
|
||||
!validIata(config.iata) || !validNtpServer(config.ntp_server)) return false;
|
||||
for (size_t i = 0; i < MQTT_OBSERVER_CONFIG_BROKER_CAPACITY; i++)
|
||||
if (!validBroker(config.brokers[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline size_t encode(const MQTTObserverConfig& config, uint8_t* out, size_t capacity) {
|
||||
if (!out || capacity < kPayloadSize || !valid(config)) return 0;
|
||||
size_t pos = 0;
|
||||
out[pos++] = config.enabled;
|
||||
out[pos++] = config.status_enabled;
|
||||
out[pos++] = config.packets_enabled;
|
||||
out[pos++] = config.raw_enabled;
|
||||
#define MQTT_OBSERVER_COPY_FIELD(field) \
|
||||
memcpy(out + pos, config.field, sizeof(config.field)); \
|
||||
pos += sizeof(config.field)
|
||||
MQTT_OBSERVER_COPY_FIELD(wifi_ssid);
|
||||
MQTT_OBSERVER_COPY_FIELD(wifi_password);
|
||||
MQTT_OBSERVER_COPY_FIELD(server);
|
||||
MQTT_OBSERVER_COPY_FIELD(username);
|
||||
MQTT_OBSERVER_COPY_FIELD(password);
|
||||
MQTT_OBSERVER_COPY_FIELD(audience);
|
||||
MQTT_OBSERVER_COPY_FIELD(iata);
|
||||
#undef MQTT_OBSERVER_COPY_FIELD
|
||||
out[pos++] = config.rx_enabled;
|
||||
out[pos++] = config.status_interval_minutes;
|
||||
out[pos++] = config.port & 0xff;
|
||||
out[pos++] = config.port >> 8;
|
||||
#define MQTT_OBSERVER_COPY_TAIL(field) \
|
||||
out[pos++] = config.wifi_power_save;
|
||||
#define MQTT_OBSERVER_COPY_GLOBAL(field) \
|
||||
memcpy(out + pos, config.field, sizeof(config.field)); \
|
||||
pos += sizeof(config.field)
|
||||
MQTT_OBSERVER_COPY_TAIL(origin);
|
||||
MQTT_OBSERVER_COPY_TAIL(topic);
|
||||
MQTT_OBSERVER_COPY_TAIL(token);
|
||||
MQTT_OBSERVER_COPY_TAIL(ntp_server);
|
||||
MQTT_OBSERVER_COPY_TAIL(owner);
|
||||
MQTT_OBSERVER_COPY_TAIL(email);
|
||||
#undef MQTT_OBSERVER_COPY_TAIL
|
||||
out[pos++] = config.wifi_power_save;
|
||||
MQTT_OBSERVER_COPY_GLOBAL(wifi_ssid);
|
||||
MQTT_OBSERVER_COPY_GLOBAL(wifi_password);
|
||||
MQTT_OBSERVER_COPY_GLOBAL(iata);
|
||||
MQTT_OBSERVER_COPY_GLOBAL(origin);
|
||||
MQTT_OBSERVER_COPY_GLOBAL(ntp_server);
|
||||
#undef MQTT_OBSERVER_COPY_GLOBAL
|
||||
for (size_t i = 0; i < MQTT_OBSERVER_CONFIG_BROKER_CAPACITY; i++) {
|
||||
const MQTTObserverBrokerConfig& broker = config.brokers[i];
|
||||
out[pos++] = broker.enabled;
|
||||
out[pos++] = broker.port & 0xff;
|
||||
out[pos++] = broker.port >> 8;
|
||||
#define MQTT_OBSERVER_COPY_BROKER(field) \
|
||||
memcpy(out + pos, broker.field, sizeof(broker.field)); \
|
||||
pos += sizeof(broker.field)
|
||||
MQTT_OBSERVER_COPY_BROKER(server);
|
||||
MQTT_OBSERVER_COPY_BROKER(username);
|
||||
MQTT_OBSERVER_COPY_BROKER(password);
|
||||
MQTT_OBSERVER_COPY_BROKER(audience);
|
||||
MQTT_OBSERVER_COPY_BROKER(topic);
|
||||
MQTT_OBSERVER_COPY_BROKER(token);
|
||||
MQTT_OBSERVER_COPY_BROKER(owner);
|
||||
MQTT_OBSERVER_COPY_BROKER(email);
|
||||
#undef MQTT_OBSERVER_COPY_BROKER
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
inline bool decodeLegacyV1(const uint8_t* data, size_t len, MQTTObserverConfig& config) {
|
||||
if (!data || len != kLegacyPayloadSize) return false;
|
||||
MQTTObserverConfig decoded;
|
||||
setDefaults(decoded);
|
||||
size_t pos = 0;
|
||||
decoded.enabled = data[pos++];
|
||||
decoded.status_enabled = data[pos++];
|
||||
decoded.packets_enabled = data[pos++];
|
||||
decoded.raw_enabled = data[pos++];
|
||||
#define MQTT_OBSERVER_READ_FIELD(field) \
|
||||
memcpy(decoded.field, data + pos, sizeof(decoded.field)); \
|
||||
pos += sizeof(decoded.field)
|
||||
MQTT_OBSERVER_READ_FIELD(wifi_ssid);
|
||||
MQTT_OBSERVER_READ_FIELD(wifi_password);
|
||||
MQTT_OBSERVER_READ_FIELD(server);
|
||||
MQTT_OBSERVER_READ_FIELD(username);
|
||||
MQTT_OBSERVER_READ_FIELD(password);
|
||||
MQTT_OBSERVER_READ_FIELD(audience);
|
||||
MQTT_OBSERVER_READ_FIELD(iata);
|
||||
#undef MQTT_OBSERVER_READ_FIELD
|
||||
if (strcmp(decoded.iata, "XXX") == 0) decoded.iata[0] = 0;
|
||||
if (!valid(decoded)) return false;
|
||||
config = decoded;
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool decode(const uint8_t* data, size_t len, MQTTObserverConfig& config) {
|
||||
if (!data || len != kPayloadSize) return false;
|
||||
MQTTObserverConfig decoded;
|
||||
setDefaults(decoded);
|
||||
setDefaults(config);
|
||||
size_t pos = 0;
|
||||
decoded.enabled = data[pos++];
|
||||
decoded.status_enabled = data[pos++];
|
||||
decoded.packets_enabled = data[pos++];
|
||||
decoded.raw_enabled = data[pos++];
|
||||
#define MQTT_OBSERVER_READ_FIELD(field) \
|
||||
memcpy(decoded.field, data + pos, sizeof(decoded.field)); \
|
||||
pos += sizeof(decoded.field)
|
||||
MQTT_OBSERVER_READ_FIELD(wifi_ssid);
|
||||
MQTT_OBSERVER_READ_FIELD(wifi_password);
|
||||
MQTT_OBSERVER_READ_FIELD(server);
|
||||
MQTT_OBSERVER_READ_FIELD(username);
|
||||
MQTT_OBSERVER_READ_FIELD(password);
|
||||
MQTT_OBSERVER_READ_FIELD(audience);
|
||||
MQTT_OBSERVER_READ_FIELD(iata);
|
||||
#undef MQTT_OBSERVER_READ_FIELD
|
||||
decoded.rx_enabled = data[pos++];
|
||||
decoded.status_interval_minutes = data[pos++];
|
||||
decoded.port = static_cast<uint16_t>(data[pos]) |
|
||||
(static_cast<uint16_t>(data[pos + 1]) << 8);
|
||||
pos += 2;
|
||||
#define MQTT_OBSERVER_READ_TAIL(field) \
|
||||
memcpy(decoded.field, data + pos, sizeof(decoded.field)); \
|
||||
pos += sizeof(decoded.field)
|
||||
MQTT_OBSERVER_READ_TAIL(origin);
|
||||
MQTT_OBSERVER_READ_TAIL(topic);
|
||||
MQTT_OBSERVER_READ_TAIL(token);
|
||||
MQTT_OBSERVER_READ_TAIL(ntp_server);
|
||||
MQTT_OBSERVER_READ_TAIL(owner);
|
||||
MQTT_OBSERVER_READ_TAIL(email);
|
||||
#undef MQTT_OBSERVER_READ_TAIL
|
||||
decoded.wifi_power_save = data[pos++];
|
||||
if (!valid(decoded)) return false;
|
||||
config = decoded;
|
||||
return true;
|
||||
config.status_enabled = data[pos++];
|
||||
config.packets_enabled = data[pos++];
|
||||
config.raw_enabled = data[pos++];
|
||||
config.rx_enabled = data[pos++];
|
||||
config.status_interval_minutes = data[pos++];
|
||||
config.wifi_power_save = data[pos++];
|
||||
#define MQTT_OBSERVER_READ_GLOBAL(field) \
|
||||
memcpy(config.field, data + pos, sizeof(config.field)); \
|
||||
pos += sizeof(config.field)
|
||||
MQTT_OBSERVER_READ_GLOBAL(wifi_ssid);
|
||||
MQTT_OBSERVER_READ_GLOBAL(wifi_password);
|
||||
MQTT_OBSERVER_READ_GLOBAL(iata);
|
||||
MQTT_OBSERVER_READ_GLOBAL(origin);
|
||||
MQTT_OBSERVER_READ_GLOBAL(ntp_server);
|
||||
#undef MQTT_OBSERVER_READ_GLOBAL
|
||||
for (size_t i = 0; i < MQTT_OBSERVER_CONFIG_BROKER_CAPACITY; i++) {
|
||||
MQTTObserverBrokerConfig& broker = config.brokers[i];
|
||||
broker.enabled = data[pos++];
|
||||
broker.port = static_cast<uint16_t>(data[pos]) |
|
||||
(static_cast<uint16_t>(data[pos + 1]) << 8);
|
||||
pos += 2;
|
||||
#define MQTT_OBSERVER_READ_BROKER(field) \
|
||||
memcpy(broker.field, data + pos, sizeof(broker.field)); \
|
||||
pos += sizeof(broker.field)
|
||||
MQTT_OBSERVER_READ_BROKER(server);
|
||||
MQTT_OBSERVER_READ_BROKER(username);
|
||||
MQTT_OBSERVER_READ_BROKER(password);
|
||||
MQTT_OBSERVER_READ_BROKER(audience);
|
||||
MQTT_OBSERVER_READ_BROKER(topic);
|
||||
MQTT_OBSERVER_READ_BROKER(token);
|
||||
MQTT_OBSERVER_READ_BROKER(owner);
|
||||
MQTT_OBSERVER_READ_BROKER(email);
|
||||
#undef MQTT_OBSERVER_READ_BROKER
|
||||
}
|
||||
if (valid(config)) return true;
|
||||
setDefaults(config);
|
||||
return false;
|
||||
}
|
||||
|
||||
inline void hostLabel(const char* server, char* out, size_t capacity) {
|
||||
@@ -272,12 +281,12 @@ inline void hostLabel(const char* server, char* out, size_t capacity) {
|
||||
out[len] = 0;
|
||||
}
|
||||
|
||||
inline uint16_t configuredPort(const MQTTObserverConfig& config) {
|
||||
const char* scheme = strstr(config.server, "://");
|
||||
if (!scheme) return config.port;
|
||||
inline uint16_t configuredPort(const MQTTObserverBrokerConfig& broker) {
|
||||
const char* scheme = strstr(broker.server, "://");
|
||||
if (!scheme) return broker.port;
|
||||
const char* authority = scheme + 3;
|
||||
const char* end = strpbrk(authority, "/?#");
|
||||
if (!end) end = config.server + strlen(config.server);
|
||||
if (!end) end = broker.server + strlen(broker.server);
|
||||
const char* colon = nullptr;
|
||||
if (authority < end && *authority == '[') {
|
||||
const char* close = static_cast<const char*>(memchr(authority, ']', end - authority));
|
||||
@@ -286,25 +295,25 @@ inline uint16_t configuredPort(const MQTTObserverConfig& config) {
|
||||
for (const char* p = authority; p < end; p++) if (*p == ':') colon = p;
|
||||
}
|
||||
if (!colon || colon + 1 == end) {
|
||||
if (config.port == 1883) {
|
||||
size_t scheme_len = static_cast<size_t>(scheme - config.server);
|
||||
if (scheme_len == 5 && strncmp(config.server, "mqtts", 5) == 0) return 8883;
|
||||
if (scheme_len == 3 && strncmp(config.server, "wss", 3) == 0) return 443;
|
||||
if (scheme_len == 2 && strncmp(config.server, "ws", 2) == 0) return 80;
|
||||
if (broker.port == 1883) {
|
||||
size_t scheme_len = static_cast<size_t>(scheme - broker.server);
|
||||
if (scheme_len == 5 && strncmp(broker.server, "mqtts", 5) == 0) return 8883;
|
||||
if (scheme_len == 3 && strncmp(broker.server, "wss", 3) == 0) return 443;
|
||||
if (scheme_len == 2 && strncmp(broker.server, "ws", 2) == 0) return 80;
|
||||
}
|
||||
return config.port;
|
||||
return broker.port;
|
||||
}
|
||||
unsigned port = 0;
|
||||
for (const char* p = colon + 1; p < end; p++) {
|
||||
if (*p < '0' || *p > '9') return config.port;
|
||||
if (*p < '0' || *p > '9') return broker.port;
|
||||
port = port * 10 + static_cast<unsigned>(*p - '0');
|
||||
if (port > 65535) return config.port;
|
||||
if (port > 65535) return broker.port;
|
||||
}
|
||||
return port ? static_cast<uint16_t>(port) : config.port;
|
||||
return port ? static_cast<uint16_t>(port) : broker.port;
|
||||
}
|
||||
|
||||
inline bool buildServerUri(const MQTTObserverConfig& config, char* out, size_t capacity) {
|
||||
const char* server = config.server;
|
||||
inline bool buildServerUri(const MQTTObserverBrokerConfig& broker, char* out, size_t capacity) {
|
||||
const char* server = broker.server;
|
||||
const char* scheme = strstr(server, "://");
|
||||
if (scheme) {
|
||||
const char* authority = scheme + 3;
|
||||
@@ -321,7 +330,7 @@ inline bool buildServerUri(const MQTTObserverConfig& config, char* out, size_t c
|
||||
int len = snprintf(out, capacity, "%s", server);
|
||||
return len > 0 && static_cast<size_t>(len) < capacity;
|
||||
}
|
||||
uint16_t port = config.port;
|
||||
uint16_t port = broker.port;
|
||||
size_t scheme_len = static_cast<size_t>(scheme - server);
|
||||
if (port == 1883 && scheme_len == 5 && strncmp(server, "mqtts", 5) == 0) port = 8883;
|
||||
else if (port == 1883 && scheme_len == 3 && strncmp(server, "wss", 3) == 0) port = 443;
|
||||
@@ -331,15 +340,16 @@ inline bool buildServerUri(const MQTTObserverConfig& config, char* out, size_t c
|
||||
static_cast<unsigned>(port), path ? path : "");
|
||||
return len > 0 && static_cast<size_t>(len) < capacity;
|
||||
}
|
||||
const char* protocol = config.port == 8883 ? "mqtts" : config.port == 443 ? "wss" : "mqtt";
|
||||
const char* protocol = broker.port == 8883 ? "mqtts" : broker.port == 443 ? "wss" : "mqtt";
|
||||
int len = snprintf(out, capacity, "%s://%s:%u", protocol, server,
|
||||
static_cast<unsigned>(config.port));
|
||||
static_cast<unsigned>(broker.port));
|
||||
return len > 0 && static_cast<size_t>(len) < capacity;
|
||||
}
|
||||
|
||||
inline bool buildTopic(const MQTTObserverConfig& config, const char* device_id,
|
||||
const char* leaf, char* out, size_t capacity) {
|
||||
const char* format = config.topic[0] ? config.topic : "meshcore/{iata}/{device}/{type}";
|
||||
inline bool buildTopic(const MQTTObserverConfig& config,
|
||||
const MQTTObserverBrokerConfig& broker,
|
||||
const char* device_id, const char* leaf, char* out, size_t capacity) {
|
||||
const char* format = broker.topic[0] ? broker.topic : "meshcore/{iata}/{device}/{type}";
|
||||
size_t used = 0;
|
||||
if (!out || capacity == 0 || !device_id || !leaf) return false;
|
||||
out[0] = 0;
|
||||
@@ -353,7 +363,7 @@ inline bool buildTopic(const MQTTObserverConfig& config, const char* device_id,
|
||||
value = device_id;
|
||||
skip = 8;
|
||||
} else if (strncmp(format, "{token}", 7) == 0) {
|
||||
value = config.token;
|
||||
value = broker.token;
|
||||
skip = 7;
|
||||
} else if (strncmp(format, "{type}", 6) == 0) {
|
||||
value = leaf;
|
||||
@@ -375,4 +385,4 @@ inline bool buildTopic(const MQTTObserverConfig& config, const char* device_id,
|
||||
return used > 0;
|
||||
}
|
||||
|
||||
} // namespace MQTTObserverConfigCodec
|
||||
} // namespace MQTTObserverConfigCodec
|
||||
@@ -4,53 +4,138 @@
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace MQTTObserverCommandPolicy {
|
||||
|
||||
inline bool parseSlot(const char* command, const char* operation, size_t max_slots,
|
||||
size_t& slot, const char*& property) {
|
||||
size_t operation_len = strlen(operation);
|
||||
if (!command || strncmp(command, operation, operation_len) != 0) return false;
|
||||
const char* name = command + operation_len;
|
||||
if (strncmp(name, "mqtt", 4) != 0) return false;
|
||||
const char* p = name + 4;
|
||||
if (*p < '0' || *p > '9') return false;
|
||||
size_t number = 0;
|
||||
while (*p >= '0' && *p <= '9') {
|
||||
number = number * 10 + static_cast<size_t>(*p++ - '0');
|
||||
if (number > max_slots) return false;
|
||||
}
|
||||
if (*p++ != '.' || number == 0 || number > max_slots) return false;
|
||||
slot = number - 1;
|
||||
property = p;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace MQTTObserverCommandPolicy
|
||||
|
||||
namespace MQTTObserverQueuePolicy {
|
||||
|
||||
static const uint32_t kMaxEventAgeMs = 10000;
|
||||
static const uint32_t kDisconnectedStaleMs = 60000UL;
|
||||
static const uint8_t kMaxQos0RetryAttempts = 3;
|
||||
static const uint32_t kRetryDelayBaseMs = 300UL;
|
||||
static const uint32_t kRetryDelayJitterMs = 200UL;
|
||||
|
||||
inline bool eventExpired(uint32_t now, uint32_t received) {
|
||||
return static_cast<uint32_t>(now - received) > kMaxEventAgeMs;
|
||||
inline uint32_t elapsedMs(uint32_t now, uint32_t then) {
|
||||
return now - then;
|
||||
}
|
||||
|
||||
inline bool shouldFlushDisconnected(uint32_t now, uint32_t disconnected_since) {
|
||||
return disconnected_since != 0 &&
|
||||
elapsedMs(now, disconnected_since) >= kDisconnectedStaleMs;
|
||||
}
|
||||
|
||||
inline bool retryReady(uint32_t now, uint32_t next_retry_ms, uint8_t retry_attempts) {
|
||||
return retry_attempts == 0 || elapsedMs(now, next_retry_ms) < 0x80000000UL;
|
||||
}
|
||||
|
||||
enum class RetryAction : uint8_t { Complete, Schedule, Drop };
|
||||
|
||||
struct RetryDecision {
|
||||
RetryAction action;
|
||||
uint8_t retry_attempts;
|
||||
uint32_t delay_ms;
|
||||
uint32_t next_retry_ms;
|
||||
};
|
||||
|
||||
inline RetryDecision retryDecision(bool any_published, uint8_t retry_attempts,
|
||||
uint32_t now) {
|
||||
if (any_published) return {RetryAction::Complete, retry_attempts, 0, 0};
|
||||
if (retry_attempts >= kMaxQos0RetryAttempts)
|
||||
return {RetryAction::Drop, retry_attempts, 0, 0};
|
||||
const uint32_t delay = kRetryDelayBaseMs + (now % kRetryDelayJitterMs);
|
||||
return {RetryAction::Schedule, static_cast<uint8_t>(retry_attempts + 1),
|
||||
delay, now + delay};
|
||||
}
|
||||
|
||||
} // namespace MQTTObserverQueuePolicy
|
||||
|
||||
template <typename Event, size_t Capacity>
|
||||
class MQTTObserverLiveQueue {
|
||||
class MQTTObserverEventQueue {
|
||||
static_assert(Capacity > 0, "queue capacity must be nonzero");
|
||||
Event _events[Capacity];
|
||||
size_t _head = 0;
|
||||
size_t _count = 0;
|
||||
|
||||
public:
|
||||
enum OfferResult { QUEUED, DROPPED_OLDEST, DROPPED_DISCONNECTED };
|
||||
struct Entry {
|
||||
Event event;
|
||||
uint32_t next_retry_ms;
|
||||
uint8_t retry_attempts;
|
||||
};
|
||||
|
||||
OfferResult offer(bool connected, const Event& event) {
|
||||
if (!connected) return DROPPED_DISCONNECTED;
|
||||
enum OfferResult { QUEUED, DROPPED_OLDEST, DROPPED_NEWEST };
|
||||
|
||||
private:
|
||||
Entry _entries[Capacity];
|
||||
size_t _count = 0;
|
||||
bool _sending = false;
|
||||
|
||||
void removeAt(size_t index) {
|
||||
for (size_t i = index; i + 1 < _count; i++) _entries[i] = _entries[i + 1];
|
||||
_count--;
|
||||
}
|
||||
|
||||
public:
|
||||
OfferResult offer(const Event& event) {
|
||||
OfferResult result = QUEUED;
|
||||
if (_count == Capacity) {
|
||||
_head = (_head + 1) % Capacity;
|
||||
_count--;
|
||||
if (_sending) {
|
||||
if (Capacity == 1) return DROPPED_NEWEST;
|
||||
removeAt(1); // Keep the in-flight head stable until its send attempt finishes.
|
||||
} else {
|
||||
removeAt(0);
|
||||
}
|
||||
result = DROPPED_OLDEST;
|
||||
}
|
||||
_events[(_head + _count) % Capacity] = event;
|
||||
_entries[_count].event = event;
|
||||
_entries[_count].next_retry_ms = 0;
|
||||
_entries[_count].retry_attempts = 0;
|
||||
_count++;
|
||||
return result;
|
||||
}
|
||||
|
||||
bool pop(Event& event) {
|
||||
if (_count == 0) return false;
|
||||
event = _events[_head];
|
||||
_head = (_head + 1) % Capacity;
|
||||
_count--;
|
||||
bool beginAttempt(uint32_t now, Entry& entry) {
|
||||
if (_count == 0 || _sending ||
|
||||
!MQTTObserverQueuePolicy::retryReady(now, _entries[0].next_retry_ms,
|
||||
_entries[0].retry_attempts)) return false;
|
||||
_sending = true;
|
||||
entry = _entries[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_head = 0;
|
||||
_count = 0;
|
||||
void completeAttempt() {
|
||||
if (!_sending || _count == 0) return;
|
||||
removeAt(0);
|
||||
_sending = false;
|
||||
}
|
||||
|
||||
void retryAttempt(uint8_t attempts, uint32_t next_retry_ms) {
|
||||
if (!_sending || _count == 0) return;
|
||||
_entries[0].retry_attempts = attempts;
|
||||
_entries[0].next_retry_ms = next_retry_ms;
|
||||
_sending = false;
|
||||
}
|
||||
|
||||
void cancelAttempt() { _sending = false; }
|
||||
void clear() { _count = 0; _sending = false; }
|
||||
size_t size() const { return _count; }
|
||||
bool sending() const { return _sending; }
|
||||
};
|
||||
|
||||
class MQTTObserverRawStager {
|
||||
|
||||
@@ -7,7 +7,6 @@ namespace MQTTObserverRecord {
|
||||
|
||||
static const size_t kHeaderSize = 7;
|
||||
static const size_t kRecordSize = kHeaderSize + MQTTObserverConfigCodec::kPayloadSize + 2;
|
||||
static const size_t kLegacyV1RecordSize = kHeaderSize + MQTTObserverConfigCodec::kLegacyPayloadSize + 2;
|
||||
static const uint8_t kMagic[4] = {'M', 'Q', 'O', '1'};
|
||||
|
||||
inline size_t encode(const MQTTObserverConfig& config, uint8_t* out, size_t capacity) {
|
||||
@@ -26,19 +25,15 @@ inline size_t encode(const MQTTObserverConfig& config, uint8_t* out, size_t capa
|
||||
}
|
||||
|
||||
inline bool decode(const uint8_t* data, size_t len, MQTTObserverConfig& config) {
|
||||
if (!data || len < kHeaderSize + 2 || memcmp(data, kMagic, sizeof(kMagic)) != 0) return false;
|
||||
size_t payload_len = static_cast<size_t>(data[5]) |
|
||||
(static_cast<size_t>(data[6]) << 8);
|
||||
if (len != kHeaderSize + payload_len + 2) return false;
|
||||
uint16_t stored_crc = static_cast<uint16_t>(data[len - 2]) |
|
||||
(static_cast<uint16_t>(data[len - 1]) << 8);
|
||||
if (stored_crc != crc16_ccitt(data, len - 2)) return false;
|
||||
if (data[4] == 1 && payload_len == MQTTObserverConfigCodec::kLegacyPayloadSize)
|
||||
return MQTTObserverConfigCodec::decodeLegacyV1(data + kHeaderSize, payload_len, config);
|
||||
if (data[4] == MQTTObserverConfigCodec::kVersion &&
|
||||
payload_len == MQTTObserverConfigCodec::kPayloadSize)
|
||||
return MQTTObserverConfigCodec::decode(data + kHeaderSize, payload_len, config);
|
||||
return false;
|
||||
if (!data || len != kRecordSize || memcmp(data, kMagic, sizeof(kMagic)) != 0 ||
|
||||
data[4] != MQTTObserverConfigCodec::kVersion ||
|
||||
data[5] != (MQTTObserverConfigCodec::kPayloadSize & 0xff) ||
|
||||
data[6] != (MQTTObserverConfigCodec::kPayloadSize >> 8)) return false;
|
||||
uint16_t stored_crc = static_cast<uint16_t>(data[kRecordSize - 2]) |
|
||||
(static_cast<uint16_t>(data[kRecordSize - 1]) << 8);
|
||||
if (stored_crc != crc16_ccitt(data, kRecordSize - 2)) return false;
|
||||
return MQTTObserverConfigCodec::decode(data + kHeaderSize,
|
||||
MQTTObserverConfigCodec::kPayloadSize, config);
|
||||
}
|
||||
|
||||
} // namespace MQTTObserverRecord
|
||||
@@ -1417,10 +1417,19 @@ static void execCliLine(void* ctx, const char* key, char* line, char* reply) {
|
||||
#ifdef WITH_MQTT_OBSERVER
|
||||
const char* logged_line = line;
|
||||
while (*logged_line == ' ') logged_line++;
|
||||
if (strncmp(logged_line, "set wifi.pwd ", 13) == 0 ||
|
||||
strncmp(logged_line, "set mqtt.password ", 18) == 0 ||
|
||||
strncmp(logged_line, "set mqtt.username ", 18) == 0 ||
|
||||
strncmp(logged_line, "set mqtt.token ", 15) == 0) {
|
||||
const char* setting = logged_line;
|
||||
while (*setting && *setting != ' ') setting++;
|
||||
while (*setting == ' ') setting++;
|
||||
bool mqtt_credential = false;
|
||||
if (strncmp(setting, "mqtt", 4) == 0) {
|
||||
const char* field = setting + 4;
|
||||
while (*field >= '0' && *field <= '9') field++;
|
||||
if (*field == '.') field++;
|
||||
mqtt_credential = strncmp(field, "password ", 9) == 0 ||
|
||||
strncmp(field, "username ", 9) == 0 ||
|
||||
strncmp(field, "token ", 6) == 0;
|
||||
}
|
||||
if (strncmp(logged_line, "set wifi.pwd ", 13) == 0 || mqtt_credential) {
|
||||
Serial.printf("cli[%s] <credential setting>\n", key);
|
||||
} else
|
||||
#endif
|
||||
|
||||
+202
-5
@@ -1,6 +1,6 @@
|
||||
; Optional MQTT observer firmware environments. Keep the target catalog here so
|
||||
; build.sh and release tooling can discover it from PlatformIO's resolved config.
|
||||
[observer_mqtt]
|
||||
[observer]
|
||||
; PsychicMqttClient and the Arduino ESP32 cert-bundle adapter need these
|
||||
; framework headers in addition to the default IDF include directories.
|
||||
build_flags = -D WITH_MQTT_OBSERVER=1
|
||||
@@ -10,14 +10,211 @@ build_src_filter = +<../examples/mqtt_observer/*.cpp>
|
||||
lib_deps =
|
||||
https://github.com/theelims/PsychicMqttClient.git#9e3005571918fdd83a2521243c501d1af137b0b6
|
||||
|
||||
[env:Xiao_S3_WIO_repeater_observer_mqtt]
|
||||
; Repeater-only targets for the supported Observer hardware list.
|
||||
[env:Heltec_T190_repeater_observer]
|
||||
extends = env:Heltec_T190_repeater_
|
||||
build_flags =
|
||||
${env:Heltec_T190_repeater_.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Heltec_T190_repeater_.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Heltec_T190_repeater_.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Heltec_Wireless_Tracker_repeater_observer]
|
||||
extends = env:Heltec_Wireless_Tracker_repeater
|
||||
build_flags =
|
||||
${env:Heltec_Wireless_Tracker_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Heltec_Wireless_Tracker_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Heltec_Wireless_Tracker_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:heltec_tracker_v2_repeater_observer]
|
||||
extends = env:heltec_tracker_v2_repeater
|
||||
build_flags =
|
||||
${env:heltec_tracker_v2_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:heltec_tracker_v2_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:heltec_tracker_v2_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Heltec_v3_repeater_observer]
|
||||
extends = env:Heltec_v3_repeater
|
||||
build_flags =
|
||||
${env:Heltec_v3_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Heltec_v3_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Heltec_v3_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Heltec_WSL3_repeater_observer]
|
||||
extends = env:Heltec_WSL3_repeater
|
||||
build_flags =
|
||||
${env:Heltec_WSL3_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Heltec_WSL3_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Heltec_WSL3_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:heltec_v4_repeater_observer]
|
||||
extends = env:heltec_v4_repeater
|
||||
build_flags =
|
||||
${env:heltec_v4_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:heltec_v4_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:heltec_v4_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:heltec_v4_expansionkit_repeater_observer]
|
||||
extends = env:heltec_v4_expansionkit_repeater
|
||||
build_flags =
|
||||
${env:heltec_v4_expansionkit_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:heltec_v4_expansionkit_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:heltec_v4_expansionkit_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:LilyGo_T3S3_sx1262_repeater_observer]
|
||||
extends = env:LilyGo_T3S3_sx1262_repeater
|
||||
board_build.partitions = min_spiffs.csv
|
||||
build_flags =
|
||||
${env:LilyGo_T3S3_sx1262_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:LilyGo_T3S3_sx1262_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:LilyGo_T3S3_sx1262_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:LilyGo_TBeam_1W_repeater_observer]
|
||||
extends = env:LilyGo_TBeam_1W_repeater
|
||||
board_build.partitions = min_spiffs.csv
|
||||
build_flags =
|
||||
${env:LilyGo_TBeam_1W_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:LilyGo_TBeam_1W_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:LilyGo_TBeam_1W_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:T_Beam_S3_Supreme_SX1262_repeater_observer]
|
||||
extends = env:T_Beam_S3_Supreme_SX1262_repeater
|
||||
build_flags =
|
||||
${env:T_Beam_S3_Supreme_SX1262_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:T_Beam_S3_Supreme_SX1262_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:T_Beam_S3_Supreme_SX1262_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Tbeam_SX1262_repeater_observer]
|
||||
extends = env:Tbeam_SX1262_repeater
|
||||
build_flags =
|
||||
${env:Tbeam_SX1262_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Tbeam_SX1262_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Tbeam_SX1262_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Tbeam_SX1276_repeater_observer]
|
||||
extends = env:Tbeam_SX1276_repeater
|
||||
build_flags =
|
||||
${env:Tbeam_SX1276_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Tbeam_SX1276_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Tbeam_SX1276_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:RAK_3112_repeater_observer]
|
||||
extends = env:RAK_3112_repeater
|
||||
build_flags =
|
||||
${env:RAK_3112_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:RAK_3112_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:RAK_3112_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Station_G2_repeater_observer]
|
||||
extends = env:Station_G2_repeater
|
||||
board_build.partitions = default_16MB.csv
|
||||
build_flags =
|
||||
${env:Station_G2_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Station_G2_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Station_G2_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Station_G3_ESP32_repeater_observer]
|
||||
extends = env:Station_G3_ESP32_repeater
|
||||
board_build.partitions = default_16MB.csv
|
||||
build_flags =
|
||||
${env:Station_G3_ESP32_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Station_G3_ESP32_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Station_G3_ESP32_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:ThinkNode_M7_repeater_observer]
|
||||
extends = env:ThinkNode_M7_repeater
|
||||
build_flags =
|
||||
${env:ThinkNode_M7_repeater.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:ThinkNode_M7_repeater.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:ThinkNode_M7_repeater.lib_deps}
|
||||
${observer.lib_deps}
|
||||
|
||||
[env:Xiao_S3_WIO_repeater_observer]
|
||||
extends = env:Xiao_S3_WIO_repeater
|
||||
build_flags =
|
||||
${env:Xiao_S3_WIO_repeater.build_flags}
|
||||
${observer_mqtt.build_flags}
|
||||
${observer.build_flags}
|
||||
build_src_filter =
|
||||
${env:Xiao_S3_WIO_repeater.build_src_filter}
|
||||
${observer_mqtt.build_src_filter}
|
||||
${observer.build_src_filter}
|
||||
lib_deps =
|
||||
${env:Xiao_S3_WIO_repeater.lib_deps}
|
||||
${observer_mqtt.lib_deps}
|
||||
${observer.lib_deps}
|
||||
@@ -7,58 +7,64 @@
|
||||
#include "MQTTObserverRecord.h"
|
||||
#include "PersistUtil.h"
|
||||
|
||||
TEST(MQTTObserverConfig, RoundTripsFixedPayload) {
|
||||
TEST(MQTTObserverConfig, RoundTripsTwoBrokerSettings) {
|
||||
MQTTObserverConfig config;
|
||||
MQTTObserverConfigCodec::setDefaults(config);
|
||||
config.enabled = 1;
|
||||
strcpy(config.wifi_ssid, "mesh-net");
|
||||
strcpy(config.wifi_password, "wifi-secret");
|
||||
strcpy(config.server, "wss://mqtt.example:443/mqtt");
|
||||
strcpy(config.username, "v1_public-key");
|
||||
strcpy(config.password, "broker-secret");
|
||||
strcpy(config.audience, "mqtt.example");
|
||||
strcpy(config.iata, "SEA");
|
||||
config.rx_enabled = 1;
|
||||
config.status_interval_minutes = 12;
|
||||
config.port = 8883;
|
||||
strcpy(config.origin, "Roof Repeater");
|
||||
strcpy(config.topic, "meshcore/{iata}/{device}/{type}");
|
||||
strcpy(config.token, "site-token");
|
||||
strcpy(config.ntp_server, "192.168.1.1");
|
||||
strcpy(config.owner, "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
|
||||
strcpy(config.email, "operator@example.org");
|
||||
config.status_interval_minutes = 12;
|
||||
config.wifi_power_save = 2;
|
||||
config.brokers[0].enabled = 1;
|
||||
strcpy(config.brokers[0].server, "wss://mqtt.example:443/mqtt");
|
||||
strcpy(config.brokers[0].username, "v1_public-key");
|
||||
strcpy(config.brokers[0].password, "broker-secret");
|
||||
strcpy(config.brokers[0].audience, "mqtt.example");
|
||||
strcpy(config.brokers[0].topic, "meshcore/{iata}/{device}/{type}");
|
||||
strcpy(config.brokers[0].token, "site-token");
|
||||
strcpy(config.brokers[0].owner,
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
|
||||
strcpy(config.brokers[0].email, "operator@example.org");
|
||||
config.brokers[0].port = 8883;
|
||||
config.brokers[1].enabled = 1;
|
||||
strcpy(config.brokers[1].server, "mqtt://second.example");
|
||||
strcpy(config.brokers[1].username, "second-user");
|
||||
config.brokers[5].enabled = 1;
|
||||
strcpy(config.brokers[5].server, "mqtt://reserved-slot.example");
|
||||
|
||||
uint8_t payload[MQTTObserverConfigCodec::kPayloadSize];
|
||||
ASSERT_EQ(MQTTObserverConfigCodec::encode(config, payload, sizeof(payload)), sizeof(payload));
|
||||
MQTTObserverConfig decoded;
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::decode(payload, sizeof(payload), decoded));
|
||||
EXPECT_EQ(decoded.enabled, 1);
|
||||
EXPECT_STREQ(decoded.wifi_ssid, "mesh-net");
|
||||
EXPECT_STREQ(decoded.wifi_password, "wifi-secret");
|
||||
EXPECT_STREQ(decoded.server, "wss://mqtt.example:443/mqtt");
|
||||
EXPECT_STREQ(decoded.password, "broker-secret");
|
||||
EXPECT_STREQ(decoded.audience, "mqtt.example");
|
||||
EXPECT_STREQ(decoded.iata, "SEA");
|
||||
EXPECT_EQ(decoded.rx_enabled, 1);
|
||||
EXPECT_EQ(decoded.status_interval_minutes, 12);
|
||||
EXPECT_EQ(decoded.port, 8883);
|
||||
EXPECT_STREQ(decoded.origin, "Roof Repeater");
|
||||
EXPECT_STREQ(decoded.topic, "meshcore/{iata}/{device}/{type}");
|
||||
EXPECT_STREQ(decoded.token, "site-token");
|
||||
EXPECT_STREQ(decoded.ntp_server, "192.168.1.1");
|
||||
EXPECT_STREQ(decoded.owner, config.owner);
|
||||
EXPECT_STREQ(decoded.email, "operator@example.org");
|
||||
EXPECT_EQ(decoded.status_interval_minutes, 12);
|
||||
EXPECT_EQ(decoded.wifi_power_save, 2);
|
||||
EXPECT_EQ(decoded.brokers[0].enabled, 1);
|
||||
EXPECT_STREQ(decoded.brokers[0].server, "wss://mqtt.example:443/mqtt");
|
||||
EXPECT_STREQ(decoded.brokers[0].password, "broker-secret");
|
||||
EXPECT_STREQ(decoded.brokers[0].audience, "mqtt.example");
|
||||
EXPECT_STREQ(decoded.brokers[0].owner, config.brokers[0].owner);
|
||||
EXPECT_STREQ(decoded.brokers[0].email, "operator@example.org");
|
||||
EXPECT_EQ(decoded.brokers[0].port, 8883);
|
||||
EXPECT_STREQ(decoded.brokers[1].server, "mqtt://second.example");
|
||||
EXPECT_STREQ(decoded.brokers[1].username, "second-user");
|
||||
EXPECT_EQ(decoded.brokers[5].enabled, 1);
|
||||
EXPECT_STREQ(decoded.brokers[5].server, "mqtt://reserved-slot.example");
|
||||
}
|
||||
|
||||
TEST(MQTTObserverConfig, RejectsInvalidValuesAndIntegrityChanges) {
|
||||
MQTTObserverConfig config;
|
||||
MQTTObserverConfigCodec::setDefaults(config);
|
||||
strcpy(config.server, "https://mqtt.example");
|
||||
strcpy(config.brokers[0].server, "https://mqtt.example");
|
||||
EXPECT_EQ(MQTTObserverConfigCodec::encode(config, nullptr, 0), 0u);
|
||||
|
||||
strcpy(config.server, "mqtts://mqtt.example");
|
||||
strcpy(config.brokers[0].server, "mqtts://mqtt.example");
|
||||
strcpy(config.iata, "Sea");
|
||||
EXPECT_EQ(MQTTObserverConfigCodec::encode(config, nullptr, 0), 0u);
|
||||
|
||||
@@ -69,21 +75,28 @@ TEST(MQTTObserverConfig, RejectsInvalidValuesAndIntegrityChanges) {
|
||||
payload[0] = 2;
|
||||
EXPECT_NE(crc16_ccitt(payload, sizeof(payload)), checksum);
|
||||
EXPECT_FALSE(MQTTObserverConfigCodec::decode(payload, sizeof(payload), config));
|
||||
EXPECT_EQ(config.status_enabled, 1);
|
||||
EXPECT_FALSE(MQTTObserverConfigCodec::decode(payload, sizeof(payload) - 1, config));
|
||||
}
|
||||
|
||||
TEST(MQTTObserverRecord, ChecksVersionLengthAndChecksum) {
|
||||
MQTTObserverConfig original;
|
||||
MQTTObserverConfigCodec::setDefaults(original);
|
||||
original.enabled = 1;
|
||||
strcpy(original.server, "mqtts://broker.example");
|
||||
original.brokers[0].enabled = 1;
|
||||
strcpy(original.brokers[0].server, "mqtts://broker.example");
|
||||
original.brokers[1].enabled = 1;
|
||||
strcpy(original.brokers[1].server, "mqtt://second.example");
|
||||
original.brokers[5].enabled = 1;
|
||||
strcpy(original.brokers[5].server, "mqtt://reserved.example");
|
||||
strcpy(original.iata, "SEA");
|
||||
uint8_t record[MQTTObserverRecord::kRecordSize];
|
||||
ASSERT_EQ(MQTTObserverRecord::encode(original, record, sizeof(record)), sizeof(record));
|
||||
|
||||
MQTTObserverConfig decoded;
|
||||
ASSERT_TRUE(MQTTObserverRecord::decode(record, sizeof(record), decoded));
|
||||
EXPECT_STREQ(decoded.server, original.server);
|
||||
EXPECT_STREQ(decoded.brokers[0].server, original.brokers[0].server);
|
||||
EXPECT_STREQ(decoded.brokers[1].server, original.brokers[1].server);
|
||||
EXPECT_STREQ(decoded.brokers[5].server, original.brokers[5].server);
|
||||
EXPECT_STREQ(decoded.iata, original.iata);
|
||||
EXPECT_FALSE(MQTTObserverRecord::decode(record, sizeof(record) - 1, decoded));
|
||||
|
||||
@@ -100,52 +113,6 @@ TEST(MQTTObserverRecord, ChecksVersionLengthAndChecksum) {
|
||||
EXPECT_FALSE(MQTTObserverRecord::decode(damaged, sizeof(damaged), decoded));
|
||||
}
|
||||
|
||||
TEST(MQTTObserverRecord, MigratesV1SettingsWithNewDefaults) {
|
||||
uint8_t record[MQTTObserverRecord::kLegacyV1RecordSize] = {};
|
||||
memcpy(record, MQTTObserverRecord::kMagic, sizeof(MQTTObserverRecord::kMagic));
|
||||
record[4] = 1;
|
||||
record[5] = MQTTObserverConfigCodec::kLegacyPayloadSize & 0xff;
|
||||
record[6] = MQTTObserverConfigCodec::kLegacyPayloadSize >> 8;
|
||||
uint8_t* payload = record + MQTTObserverRecord::kHeaderSize;
|
||||
size_t pos = 0;
|
||||
payload[pos++] = 1;
|
||||
payload[pos++] = 1;
|
||||
payload[pos++] = 1;
|
||||
payload[pos++] = 1;
|
||||
#define COPY_OLD_FIELD(name) \
|
||||
memcpy(payload + pos, legacy.name, sizeof(legacy.name)); \
|
||||
pos += sizeof(legacy.name)
|
||||
MQTTObserverConfig legacy;
|
||||
MQTTObserverConfigCodec::setDefaults(legacy);
|
||||
strcpy(legacy.wifi_ssid, "old-wifi");
|
||||
strcpy(legacy.wifi_password, "old-password");
|
||||
strcpy(legacy.server, "mqtts://old-broker.example");
|
||||
strcpy(legacy.username, "old-user");
|
||||
strcpy(legacy.password, "old-broker-password");
|
||||
strcpy(legacy.audience, "old-audience");
|
||||
strcpy(legacy.iata, "SEA");
|
||||
COPY_OLD_FIELD(wifi_ssid);
|
||||
COPY_OLD_FIELD(wifi_password);
|
||||
COPY_OLD_FIELD(server);
|
||||
COPY_OLD_FIELD(username);
|
||||
COPY_OLD_FIELD(password);
|
||||
COPY_OLD_FIELD(audience);
|
||||
COPY_OLD_FIELD(iata);
|
||||
#undef COPY_OLD_FIELD
|
||||
uint16_t crc = crc16_ccitt(record, sizeof(record) - 2);
|
||||
record[sizeof(record) - 2] = crc & 0xff;
|
||||
record[sizeof(record) - 1] = crc >> 8;
|
||||
|
||||
MQTTObserverConfig migrated;
|
||||
ASSERT_TRUE(MQTTObserverRecord::decode(record, sizeof(record), migrated));
|
||||
EXPECT_STREQ(migrated.wifi_ssid, "old-wifi");
|
||||
EXPECT_STREQ(migrated.server, "mqtts://old-broker.example");
|
||||
EXPECT_STREQ(migrated.iata, "SEA");
|
||||
EXPECT_EQ(migrated.rx_enabled, 1);
|
||||
EXPECT_EQ(migrated.status_interval_minutes, 5);
|
||||
EXPECT_EQ(migrated.port, 1883);
|
||||
EXPECT_EQ(migrated.wifi_power_save, 1);
|
||||
}
|
||||
|
||||
TEST(MQTTObserverConfig, IataSupportsAlphanumericAndRejectsPlaceholder) {
|
||||
EXPECT_TRUE(MQTTObserverConfigCodec::validIata("A1B"));
|
||||
@@ -164,37 +131,37 @@ TEST(MQTTObserverConfig, BuildsBrokerUrisAndHonorsExplicitPorts) {
|
||||
MQTTObserverConfig config;
|
||||
MQTTObserverConfigCodec::setDefaults(config);
|
||||
char uri[192];
|
||||
strcpy(config.server, "broker.example");
|
||||
config.port = 8883;
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildServerUri(config, uri, sizeof(uri)));
|
||||
strcpy(config.brokers[0].server, "broker.example");
|
||||
config.brokers[0].port = 8883;
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildServerUri(config.brokers[0], uri, sizeof(uri)));
|
||||
EXPECT_STREQ(uri, "mqtts://broker.example:8883");
|
||||
|
||||
strcpy(config.server, "wss://broker.example/mqtt");
|
||||
config.port = 1883;
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildServerUri(config, uri, sizeof(uri)));
|
||||
strcpy(config.brokers[0].server, "wss://broker.example/mqtt");
|
||||
config.brokers[0].port = 1883;
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildServerUri(config.brokers[0], uri, sizeof(uri)));
|
||||
EXPECT_STREQ(uri, "wss://broker.example:443/mqtt");
|
||||
EXPECT_EQ(MQTTObserverConfigCodec::configuredPort(config), 443);
|
||||
EXPECT_EQ(MQTTObserverConfigCodec::configuredPort(config.brokers[0]), 443);
|
||||
|
||||
strcpy(config.server, "mqtts://broker.example:9000/mqtt");
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildServerUri(config, uri, sizeof(uri)));
|
||||
strcpy(config.brokers[0].server, "mqtts://broker.example:9000/mqtt");
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildServerUri(config.brokers[0], uri, sizeof(uri)));
|
||||
EXPECT_STREQ(uri, "mqtts://broker.example:9000/mqtt");
|
||||
EXPECT_EQ(MQTTObserverConfigCodec::configuredPort(config), 9000);
|
||||
EXPECT_EQ(MQTTObserverConfigCodec::configuredPort(config.brokers[0]), 9000);
|
||||
}
|
||||
|
||||
TEST(MQTTObserverConfig, ExpandsReferenceTopicTemplate) {
|
||||
MQTTObserverConfig config;
|
||||
MQTTObserverConfigCodec::setDefaults(config);
|
||||
strcpy(config.iata, "A1B");
|
||||
strcpy(config.token, "region-token");
|
||||
strcpy(config.brokers[0].token, "region-token");
|
||||
char topic[160];
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildTopic(config, "AABB", "packets", topic, sizeof(topic)));
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildTopic(config, config.brokers[0], "AABB", "packets", topic, sizeof(topic)));
|
||||
EXPECT_STREQ(topic, "meshcore/A1B/AABB/packets");
|
||||
strcpy(config.topic, "local/{token}/{device}/{type}");
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildTopic(config, "AABB", "raw", topic, sizeof(topic)));
|
||||
strcpy(config.brokers[0].topic, "local/{token}/{device}/{type}");
|
||||
ASSERT_TRUE(MQTTObserverConfigCodec::buildTopic(config, config.brokers[0], "AABB", "raw", topic, sizeof(topic)));
|
||||
EXPECT_STREQ(topic, "local/region-token/AABB/raw");
|
||||
char short_topic[8];
|
||||
EXPECT_FALSE(MQTTObserverConfigCodec::buildTopic(config, "AABB", "packets", short_topic,
|
||||
sizeof(short_topic)));
|
||||
EXPECT_FALSE(MQTTObserverConfigCodec::buildTopic(config, config.brokers[0], "AABB", "packets",
|
||||
short_topic, sizeof(short_topic)));
|
||||
}
|
||||
|
||||
TEST(MQTTObserverRawStager, ConsumesOnlyTheImmediatelyStagedFrame) {
|
||||
@@ -226,33 +193,83 @@ TEST(MQTTObserverRawStager, ConsumesOnlyTheImmediatelyStagedFrame) {
|
||||
EXPECT_FALSE(stager.consume(copied, sizeof(copied), copied_len, copied_snr, copied_rssi));
|
||||
}
|
||||
|
||||
TEST(MQTTObserverQueuePolicy, ExpiresStaleEventsWrapSafely) {
|
||||
EXPECT_FALSE(MQTTObserverQueuePolicy::eventExpired(10000, 1000));
|
||||
EXPECT_TRUE(MQTTObserverQueuePolicy::eventExpired(11001, 1000));
|
||||
EXPECT_FALSE(MQTTObserverQueuePolicy::eventExpired(5, 0xfffffff0));
|
||||
TEST(MQTTObserverCommandPolicy, ParsesNumberedSlotsAndRejectsUnnumberedBrokerSettings) {
|
||||
size_t slot = 99;
|
||||
const char* property = nullptr;
|
||||
EXPECT_FALSE(MQTTObserverCommandPolicy::parseSlot("set mqtt.server broker", "set ", 2,
|
||||
slot, property));
|
||||
ASSERT_TRUE(MQTTObserverCommandPolicy::parseSlot("set mqtt1.server broker", "set ", 2,
|
||||
slot, property));
|
||||
EXPECT_EQ(slot, 0u);
|
||||
EXPECT_STREQ(property, "server broker");
|
||||
ASSERT_TRUE(MQTTObserverCommandPolicy::parseSlot("get mqtt1.password", "get ", 2,
|
||||
slot, property));
|
||||
EXPECT_EQ(slot, 0u);
|
||||
EXPECT_STREQ(property, "password");
|
||||
ASSERT_TRUE(MQTTObserverCommandPolicy::parseSlot("get mqtt2.status", "get ", 2,
|
||||
slot, property));
|
||||
EXPECT_EQ(slot, 1u);
|
||||
EXPECT_STREQ(property, "status");
|
||||
EXPECT_FALSE(MQTTObserverCommandPolicy::parseSlot("get mqtt3.server", "get ", 2,
|
||||
slot, property));
|
||||
EXPECT_FALSE(MQTTObserverCommandPolicy::parseSlot("get mqtt2x.server", "get ", 2,
|
||||
slot, property));
|
||||
}
|
||||
|
||||
TEST(MQTTObserverLiveQueue, DropsDisconnectedEventsAndKeepsNewestOnOverflow) {
|
||||
TEST(MQTTObserverQueuePolicy, FlushesOnlyAfterLongDisconnectAndRetriesBoundedly) {
|
||||
EXPECT_FALSE(MQTTObserverQueuePolicy::shouldFlushDisconnected(60099, 100));
|
||||
EXPECT_TRUE(MQTTObserverQueuePolicy::shouldFlushDisconnected(60100, 100));
|
||||
EXPECT_FALSE(MQTTObserverQueuePolicy::shouldFlushDisconnected(4, 0xfffffff0));
|
||||
EXPECT_TRUE(MQTTObserverQueuePolicy::retryReady(1200, 1100, 1));
|
||||
EXPECT_FALSE(MQTTObserverQueuePolicy::retryReady(1099, 1100, 1));
|
||||
EXPECT_FALSE(MQTTObserverQueuePolicy::retryReady(0xfffffff8, 4, 1));
|
||||
EXPECT_TRUE(MQTTObserverQueuePolicy::retryReady(4, 4, 1));
|
||||
EXPECT_EQ(MQTTObserverQueuePolicy::retryDecision(false, 0, 10).action,
|
||||
MQTTObserverQueuePolicy::RetryAction::Schedule);
|
||||
EXPECT_EQ(MQTTObserverQueuePolicy::retryDecision(false, 3, 10).action,
|
||||
MQTTObserverQueuePolicy::RetryAction::Drop);
|
||||
EXPECT_EQ(MQTTObserverQueuePolicy::retryDecision(true, 0, 10).action,
|
||||
MQTTObserverQueuePolicy::RetryAction::Complete);
|
||||
}
|
||||
|
||||
TEST(MQTTObserverEventQueue, BoundedRetriesAndProtectsInFlightHead) {
|
||||
struct Event { int id; };
|
||||
typedef MQTTObserverLiveQueue<Event, 2> EventQueue;
|
||||
typedef MQTTObserverEventQueue<Event, 2> EventQueue;
|
||||
EventQueue queue;
|
||||
Event one = {1}, two = {2}, three = {3};
|
||||
EXPECT_EQ(queue.offer(false, one), EventQueue::DROPPED_DISCONNECTED);
|
||||
EventQueue::Entry entry;
|
||||
Event one = {1}, two = {2}, three = {3}, event;
|
||||
EXPECT_EQ(queue.offer(one), EventQueue::QUEUED);
|
||||
EXPECT_TRUE(queue.beginAttempt(0, entry));
|
||||
EXPECT_EQ(entry.event.id, 1);
|
||||
EXPECT_EQ(queue.offer(two), EventQueue::QUEUED);
|
||||
EXPECT_EQ(queue.offer(three), EventQueue::DROPPED_OLDEST);
|
||||
EXPECT_FALSE(queue.beginAttempt(0, entry));
|
||||
queue.retryAttempt(1, 300);
|
||||
EXPECT_FALSE(queue.beginAttempt(299, entry));
|
||||
EXPECT_TRUE(queue.beginAttempt(300, entry));
|
||||
EXPECT_EQ(entry.event.id, 1);
|
||||
queue.completeAttempt();
|
||||
EXPECT_EQ(queue.size(), 1u);
|
||||
EXPECT_TRUE(queue.beginAttempt(301, entry));
|
||||
EXPECT_EQ(entry.event.id, 3);
|
||||
queue.completeAttempt();
|
||||
EXPECT_EQ(queue.size(), 0u);
|
||||
EXPECT_EQ(queue.offer(true, one), EventQueue::QUEUED);
|
||||
EXPECT_EQ(queue.offer(true, two), EventQueue::QUEUED);
|
||||
EXPECT_EQ(queue.offer(true, three), EventQueue::DROPPED_OLDEST);
|
||||
Event event;
|
||||
ASSERT_TRUE(queue.pop(event));
|
||||
EXPECT_EQ(event.id, 2);
|
||||
ASSERT_TRUE(queue.pop(event));
|
||||
EXPECT_EQ(event.id, 3);
|
||||
EXPECT_FALSE(queue.pop(event));
|
||||
Event four = {4};
|
||||
queue.offer(true, four);
|
||||
queue.clear();
|
||||
EXPECT_EQ(queue.size(), 0u);
|
||||
EXPECT_FALSE(queue.pop(event));
|
||||
EXPECT_FALSE(queue.beginAttempt(400, entry));
|
||||
}
|
||||
|
||||
TEST(MQTTObserverEventQueue, OverflowReplacesOldestPendingEntry) {
|
||||
struct Event { int id; };
|
||||
typedef MQTTObserverEventQueue<Event, 2> EventQueue;
|
||||
EventQueue queue;
|
||||
EventQueue::Entry entry;
|
||||
EXPECT_EQ(queue.offer(Event{1}), EventQueue::QUEUED);
|
||||
EXPECT_EQ(queue.offer(Event{2}), EventQueue::QUEUED);
|
||||
EXPECT_EQ(queue.offer(Event{3}), EventQueue::DROPPED_OLDEST);
|
||||
ASSERT_TRUE(queue.beginAttempt(0, entry));
|
||||
EXPECT_EQ(entry.event.id, 2);
|
||||
queue.completeAttempt();
|
||||
ASSERT_TRUE(queue.beginAttempt(0, entry));
|
||||
EXPECT_EQ(entry.event.id, 3);
|
||||
}
|
||||
|
||||
TEST(MQTTObserverFormat, PacketMessageMatchesObserverSchema) {
|
||||
|
||||
Reference in new issue
Block a user