feat: publish a retained offline status as the observer last will

Register a retained QoS 1 status:"offline" last will on each broker's status
topic so a feed flips the node offline as soon as the broker notices an
unexpected session drop. The will body and topic live in BrokerRuntime because
the library keeps the pointers; the topic/status are reused via a shared
buildStatusMessage() so online and offline share one schema.
This commit is contained in:
Jason Huebert committed 2026-10-16 21:03:39 -05:00
1 parent 8579db8e80
commit 2db295ed0e
6 files changed
+65 -29

No files matched your search

+4 -1
View File
@@ -182,7 +182,10 @@ Packet/raw publishes are QoS 0, non-retained, and sent synchronously with a
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.
Each broker also registers a retained QoS 1 `status: "offline"` last will on the
status topic, so a feed shows the node offline as soon as the broker notices an
unexpected session drop (the will is only armed while the shared `mqtt.status`
switch is on). The broker may apply its own retention policy.
## Bounded queue and delivery behavior
+41 -24
View File
@@ -127,7 +127,8 @@ bool sameBrokerConnection(const MQTTObserverBrokerConfig& a,
} // namespace
MQTTObserver::BrokerRuntime::BrokerRuntime()
: client(nullptr), server_uri{}, client_id{}, username{}, password{}, jwt_username{},
: client(nullptr), server_uri{}, client_id{}, status_topic{}, offline_payload{},
username{}, password{}, jwt_username{},
jwt_token{}, jwt_expiry(0),
next_connect_ms(0), attempt_started(0), connected_at(0), last_status_ms(0),
status_retry_ms(0), backoff_index(0), status_retry_pending(false),
@@ -454,8 +455,9 @@ bool MQTTObserver::createJwt(size_t slot, const MQTTObserverBrokerConfig& config
return true;
}
bool MQTTObserver::configureClient(size_t slot, const MQTTObserverBrokerConfig& config) {
bool MQTTObserver::configureClient(size_t slot, const MQTTObserverConfig& config) {
if (slot >= MQTT_OBSERVER_MAX_BROKERS) return false;
const MQTTObserverBrokerConfig& broker = config.brokers[slot];
BrokerRuntime& runtime = _brokers[slot];
if (!runtime.client) {
runtime.client = new (std::nothrow) PsychicMqttClient();
@@ -475,7 +477,7 @@ bool MQTTObserver::configureClient(size_t slot, const MQTTObserverBrokerConfig&
_brokers[slot].state.store(STATE_ERROR, std::memory_order_relaxed);
});
}
if (!MQTTObserverConfigCodec::buildServerUri(config, runtime.server_uri,
if (!MQTTObserverConfigCodec::buildServerUri(broker, runtime.server_uri,
sizeof(runtime.server_uri)) ||
!MQTTObserverConfigCodec::buildClientId(_device_id, slot, runtime.client_id,
sizeof(runtime.client_id))) return false;
@@ -505,20 +507,31 @@ bool MQTTObserver::configureClient(size_t slot, const MQTTObserverBrokerConfig&
mqtt_config->password = nullptr;
#endif
}
if (config.audience[0]) {
if (broker.audience[0]) {
runtime.username[0] = 0;
runtime.password[0] = 0;
if (!createJwt(slot, config, runtime.jwt_expiry)) return false;
if (!createJwt(slot, broker, runtime.jwt_expiry)) return false;
runtime.client->setCredentials(runtime.jwt_username, runtime.jwt_token);
} else {
runtime.jwt_expiry = 0;
strncpy(runtime.username, config.username, sizeof(runtime.username) - 1);
strncpy(runtime.username, broker.username, sizeof(runtime.username) - 1);
runtime.username[sizeof(runtime.username) - 1] = 0;
strncpy(runtime.password, config.password, sizeof(runtime.password) - 1);
strncpy(runtime.password, broker.password, sizeof(runtime.password) - 1);
runtime.password[sizeof(runtime.password) - 1] = 0;
runtime.client->setCredentials(runtime.username[0] ? runtime.username : nullptr,
runtime.password[0] ? runtime.password : nullptr);
}
// A retained last will flips the node offline on the feed as soon as the
// broker notices the session drop. The topic and body must outlive connect()
// (the library keeps the pointers), so they live in BrokerRuntime.
if (config.status_enabled &&
MQTTObserverConfigCodec::buildTopic(config, broker, _device_id, "status",
runtime.status_topic, sizeof(runtime.status_topic))) {
size_t will_len = 0;
if (buildStatusMessage(false, runtime.offline_payload, sizeof(runtime.offline_payload), will_len))
runtime.client->setWill(runtime.status_topic, 1, true, runtime.offline_payload,
static_cast<int>(will_len));
}
return true;
}
@@ -648,7 +661,7 @@ void MQTTObserver::worker() {
runtime.configured = false;
runtime.status_retry_pending = false;
runtime.last_status_ms = 0;
if (!configureClient(i, broker)) {
if (!configureClient(i, _work_config)) {
runtime.state.store(STATE_ERROR, std::memory_order_relaxed);
continue;
}
@@ -748,19 +761,7 @@ void MQTTObserver::worker() {
}
}
bool MQTTObserver::publishStatus(size_t slot, const MQTTObserverConfig& config) {
if (slot >= MQTT_OBSERVER_MAX_BROKERS) return false;
BrokerRuntime& runtime = _brokers[slot];
if (!runtime.client || !runtime.client->connected() || !config.status_enabled) return false;
const MQTTObserverBrokerConfig& broker = config.brokers[slot];
char topic[128];
if (!MQTTObserverConfigCodec::buildTopic(config, broker, _device_id, "status",
topic, sizeof(topic))) return false;
struct timeval now;
gettimeofday(&now, nullptr);
char timestamp[40];
if (!MQTTObserverFormat::formatTimestamp(now.tv_sec, now.tv_usec, timestamp,
sizeof(timestamp))) return false;
bool MQTTObserver::buildStatusMessage(bool online, char* out, size_t capacity, size_t& written) {
char radio[64];
char origin[sizeof(_origin)];
float freq, bw;
@@ -774,10 +775,26 @@ bool MQTTObserver::publishStatus(size_t slot, const MQTTObserverConfig& config)
portEXIT_CRITICAL(&_config_mux);
snprintf(radio, sizeof(radio), "%.3f,%.1f,%u,%u", static_cast<double>(freq),
static_cast<double>(bw), static_cast<unsigned>(sf), static_cast<unsigned>(cr));
struct timeval now;
gettimeofday(&now, nullptr);
char timestamp[40];
if (!MQTTObserverFormat::formatTimestamp(now.tv_sec, now.tv_usec, timestamp,
sizeof(timestamp))) return false;
return MQTTObserverFormat::buildStatus(origin, _device_id, "MeshCore Repeater",
FIRMWARE_VERSION, radio, timestamp,
out, capacity, written, online);
}
bool MQTTObserver::publishStatus(size_t slot, const MQTTObserverConfig& config) {
if (slot >= MQTT_OBSERVER_MAX_BROKERS) return false;
BrokerRuntime& runtime = _brokers[slot];
if (!runtime.client || !runtime.client->connected() || !config.status_enabled) return false;
const MQTTObserverBrokerConfig& broker = config.brokers[slot];
char topic[128];
if (!MQTTObserverConfigCodec::buildTopic(config, broker, _device_id, "status",
topic, sizeof(topic))) return false;
size_t written = 0;
if (!MQTTObserverFormat::buildStatus(origin, _device_id,
"MeshCore Repeater", FIRMWARE_VERSION, radio, timestamp,
_json, sizeof(_json), written)) return false;
if (!buildStatusMessage(true, _json, sizeof(_json), written)) return false;
return runtime.client->publish(topic, 1, false, _json, written, true) >= 0;
}
+4 -1
View File
@@ -38,6 +38,8 @@ class MQTTObserver {
PsychicMqttClient* client;
char server_uri[sizeof(MQTTObserverBrokerConfig::server) + 16];
char client_id[2 * PUB_KEY_SIZE + 3];
char status_topic[128];
char offline_payload[512]; // retained last-will body (setWill keeps the pointer)
char username[65];
char password[65];
char jwt_username[3 + 2 * PUB_KEY_SIZE + 1];
@@ -101,10 +103,11 @@ class MQTTObserver {
bool ready(const MQTTObserverConfig& config, size_t slot) const;
bool hasEnabledBrokerLocked() const; // caller holds _config_mux
bool hasConnectHeadroom(bool secure) const;
bool configureClient(size_t slot, const MQTTObserverBrokerConfig& config);
bool configureClient(size_t slot, const MQTTObserverConfig& config);
bool createJwt(size_t slot, const MQTTObserverBrokerConfig& config, uint32_t& expires_at);
bool publishEvent(const Event& event, const MQTTObserverConfig& config);
bool publishStatus(size_t slot, const MQTTObserverConfig& config);
bool buildStatusMessage(bool online, char* out, size_t capacity, size_t& written);
void disconnectBroker(size_t slot);
void trackDisconnectedQueue(uint32_t now);
void flushQueue();
@@ -201,11 +201,11 @@ bool buildRaw(const char* origin, const char* origin_id, const char* timestamp,
bool buildStatus(const char* origin, const char* origin_id, const char* model,
const char* firmware, const char* radio, const char* timestamp,
char* out, size_t capacity, size_t& written) {
char* out, size_t capacity, size_t& written, bool online) {
if (!origin || !origin_id || !model || !firmware || !radio || !timestamp) return false;
JsonWriter writer(out, capacity);
writer.append("{");
appendKey(writer, "status", "online", false);
appendKey(writer, "status", online ? "online" : "offline", false);
appendKey(writer, "timestamp", timestamp);
appendKey(writer, "origin", origin);
appendKey(writer, "origin_id", origin_id);
+1 -1
View File
@@ -34,6 +34,6 @@ bool buildRaw(const char* origin, const char* origin_id, const char* timestamp,
const uint8_t* bytes, size_t len, char* out, size_t capacity, size_t& written);
bool buildStatus(const char* origin, const char* origin_id, const char* model,
const char* firmware, const char* radio, const char* timestamp,
char* out, size_t capacity, size_t& written);
char* out, size_t capacity, size_t& written, bool online = true);
} // namespace MQTTObserverFormat
@@ -440,6 +440,19 @@ TEST(MQTTObserverFormat, RawStatusAndTruncationAreBounded) {
EXPECT_EQ(short_json[0], 0);
}
TEST(MQTTObserverFormat, OfflineStatusIsARetainedLastWillBody) {
char json[512];
size_t written = 0;
ASSERT_TRUE(MQTTObserverFormat::buildStatus("node", "AABB", "MeshCore", "1.0", "radio",
"timestamp", json, sizeof(json), written, false));
std::string payload(json, written);
EXPECT_NE(payload.find("\"status\":\"offline\""), std::string::npos);
EXPECT_EQ(payload.find("\"status\":\"online\""), std::string::npos);
// Same identity/version fields as the online status message.
EXPECT_NE(payload.find("\"origin_id\":\"AABB\""), std::string::npos);
EXPECT_NE(payload.find("\"client_version\":\"meshcore-jhuebert/1.0\""), std::string::npos);
}
TEST(MQTTObserverFormat, ClientVersionIsSharedByStatusAndClaims) {
char version[96];
ASSERT_TRUE(MQTTObserverFormat::buildClientVersion("1.2.3", version, sizeof(version)));