diff --git a/docs/MESSAGING_IDEAS.md b/docs/MESSAGING_IDEAS.md index 886e492..3d62fbc 100644 --- a/docs/MESSAGING_IDEAS.md +++ b/docs/MESSAGING_IDEAS.md @@ -193,10 +193,17 @@ CHAT_ID = "YOUR_CHAT_ID" def on_message(client, userdata, msg): data = json.loads(msg.payload) + tg = msg.topic.split("/")[-2] if msg.topic.endswith("/start"): - tg = msg.topic.split("/")[-2] bot.send_message(CHAT_ID, f"📡 {data['callsign']} talking on TG {tg}") + elif msg.topic.endswith("/stop") and "duration_ms" in data: + # Skip kerchunks under 1 s; pretty-print the rest. + if data["duration_ms"] >= 1000: + secs = data["duration_ms"] / 1000 + bot.send_message(CHAT_ID, + f"🔇 {data['callsign']} stopped on TG {tg} " + f"({secs:.1f} s)") client = mqtt.Client() client.username_pw_set("user", "pass") @@ -206,6 +213,13 @@ client.subscribe("svxreflector/+/talker/#") client.loop_forever() ``` +The `start` and `stop` payloads carry `ts` (Unix epoch ms) and `stop` +additionally carries `duration_ms` when a matching start was observed — +see [`docs/MQTT.md`](MQTT.md) for the schema and edge cases. Filtering +on `duration_ms < 1000` is a cheap way to suppress kerchunks; using +`ts` lets you compute end-to-end latency between the reflector and +your bot pipeline. + --- ## Contributing Ideas diff --git a/docs/MQTT.md b/docs/MQTT.md index 1b1ccf7..8fde145 100644 --- a/docs/MQTT.md +++ b/docs/MQTT.md @@ -62,11 +62,32 @@ below). {TOPIC_PREFIX}/talker/{tg}/stop ``` -Payload: +Payload (start): ```json -{"callsign": "ON4ABC", "source": "local"} +{"callsign": "ON4ABC", "source": "local", "ts": 1730981234567} ``` +Payload (stop): +```json +{"callsign": "ON4ABC", "source": "local", "ts": 1730981258912, "duration_ms": 24345} +``` + +`ts` is the reflector's wall-clock time at publish, in Unix-epoch +milliseconds. `duration_ms` is included on the stop event when a matching +start was observed by the same `MqttPublisher` instance **and** the +resulting duration is non-negative. It is omitted in two cases: + +- The reflector restarted (or the talker started before this process was + running) — no matching start was recorded. +- Wall-clock time moved backwards between start and stop (e.g. an NTP + correction during a transmission). Negative durations are useless, so + the field is dropped rather than published as a confusing value; + consumers that need a duration can fall back to the gap between their + own observation timestamps for the start/stop topics. + +Both fields are **additive** — older consumers that only read `callsign` +continue to work unchanged. + These topics are **local-only** — they fire only for clients directly connected to this reflector. Non-retained. Dashboards that want every talker on the mesh (local + peer) must also subscribe to `peer/+/talker/+/start` and @@ -181,6 +202,11 @@ purely additive change. `rx` and `status` payloads are JSON strings with the same schema as their local equivalents (`client/.../rx` and `client/.../status`). +`peer/.../talker/.../start` and `.../stop` carry the same `ts` / +`duration_ms` fields as the local `talker/.../{start,stop}` topics +(see above). On stop, `duration_ms` is included when a matching start +was observed for the same `(peer_id, tg)` pair. + **Retained-store growth note.** When a peer client disconnects, the retained `peer/{peer_id}/client/{callsign}/rx` and `.../status` topics survive in the broker until cleared. The reflector **does not automatically clear** them on diff --git a/src/svxlink/reflector/MqttPublisher.cpp b/src/svxlink/reflector/MqttPublisher.cpp index 7390477..7a70787 100644 --- a/src/svxlink/reflector/MqttPublisher.cpp +++ b/src/svxlink/reflector/MqttPublisher.cpp @@ -1,5 +1,6 @@ #include "MqttPublisher.h" +#include #include #include #include @@ -9,6 +10,14 @@ using namespace std; +int64_t MqttPublisher::nowMs(void) +{ + using namespace std::chrono; + return duration_cast( + system_clock::now().time_since_epoch()).count(); +} + + static void on_connect_cb(struct mosquitto*, void*, int rc) { if (rc == 0) @@ -239,9 +248,13 @@ void MqttPublisher::publish(const std::string& topic_suffix, void MqttPublisher::onTalkerStart(uint32_t tg, const std::string& callsign, bool is_trunk) { + const int64_t ts = nowMs(); + m_talker_start_ms[{string(), tg}] = ts; + Json::Value payload; payload["callsign"] = callsign; - payload["source"] = is_trunk ? "trunk" : "local"; + payload["source"] = is_trunk ? "trunk" : "local"; + payload["ts"] = static_cast(ts); Json::StreamWriterBuilder wb; wb["indentation"] = ""; string topic = "talker/" + to_string(tg) + "/start"; @@ -252,9 +265,23 @@ void MqttPublisher::onTalkerStart(uint32_t tg, const std::string& callsign, void MqttPublisher::onTalkerStop(uint32_t tg, const std::string& callsign, bool is_trunk) { + const int64_t ts = nowMs(); Json::Value payload; payload["callsign"] = callsign; - payload["source"] = is_trunk ? "trunk" : "local"; + payload["source"] = is_trunk ? "trunk" : "local"; + payload["ts"] = static_cast(ts); + + auto it = m_talker_start_ms.find({string(), tg}); + if (it != m_talker_start_ms.end()) + { + const int64_t dur = ts - it->second; + // Omit duration_ms on a backwards clock jump (NTP correction mid-talker). + // The map entry is still consumed — there is no recovery from a + // jumped clock at the next stop event. + if (dur >= 0) payload["duration_ms"] = static_cast(dur); + m_talker_start_ms.erase(it); + } + Json::StreamWriterBuilder wb; wb["indentation"] = ""; string topic = "talker/" + to_string(tg) + "/stop"; @@ -272,9 +299,13 @@ void MqttPublisher::onPeerTalkerStart(const std::string& peer_id, " (tg=", tg, " callsign='", callsign, "')"); return; } + const int64_t ts = nowMs(); + m_talker_start_ms[{peer_id, tg}] = ts; + Json::Value payload; payload["callsign"] = callsign; - payload["tg"] = static_cast(tg); + payload["tg"] = static_cast(tg); + payload["ts"] = static_cast(ts); Json::StreamWriterBuilder wb; wb["indentation"] = ""; string topic = "peer/" + peer_id + "/talker/" + to_string(tg) + "/start"; @@ -292,9 +323,21 @@ void MqttPublisher::onPeerTalkerStop(const std::string& peer_id, " (tg=", tg, " callsign='", callsign, "')"); return; } + const int64_t ts = nowMs(); Json::Value payload; payload["callsign"] = callsign; - payload["tg"] = static_cast(tg); + payload["tg"] = static_cast(tg); + payload["ts"] = static_cast(ts); + + auto it = m_talker_start_ms.find({peer_id, tg}); + if (it != m_talker_start_ms.end()) + { + const int64_t dur = ts - it->second; + // Omit duration_ms on a backwards clock jump (NTP correction mid-talker). + if (dur >= 0) payload["duration_ms"] = static_cast(dur); + m_talker_start_ms.erase(it); + } + Json::StreamWriterBuilder wb; wb["indentation"] = ""; string topic = "peer/" + peer_id + "/talker/" + to_string(tg) + "/stop"; diff --git a/src/svxlink/reflector/MqttPublisher.h b/src/svxlink/reflector/MqttPublisher.h index f8c1d80..bfbc093 100644 --- a/src/svxlink/reflector/MqttPublisher.h +++ b/src/svxlink/reflector/MqttPublisher.h @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include "ReflectorMsg.h" @@ -92,6 +94,14 @@ class MqttPublisher time_t m_last_pub_err_logged = 0; uint64_t m_pub_err_suppressed = 0; + // Talker-start timestamps, used to compute duration_ms on stop. + // Key for local talkers is ("", tg); for peer talkers ("", tg). + // At most one talker is active per (peer_id, tg) at any moment, so the + // pair is a sufficient key. + std::map, int64_t> m_talker_start_ms; + + static int64_t nowMs(void); + void publish(const std::string& topic_suffix, const std::string& payload, bool retain = false); diff --git a/tests/test_trunk.py b/tests/test_trunk.py index 331aec8..412fd42 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -1518,6 +1518,7 @@ class TestTrunkIntegration(unittest.TestCase): peer_id = "TRUNK_TEST" tg = 1220 # Owned by reflector-a (prefix 122) + t0_ms = int(time.time() * 1000) peer.send_talker_start(tg, "N0MQTT") time.sleep(2) # Allow propagation @@ -1530,7 +1531,15 @@ class TestTrunkIntegration(unittest.TestCase): self.assertTrue(len(start_events) > 0, f"Expected MQTT talker start at '{expected_start_topic}', " f"got topics: {[r[0] for r in received]}") - self.assertEqual(start_events[0][1]["callsign"], "N0MQTT") + start_payload = start_events[0][1] + self.assertEqual(start_payload["callsign"], "N0MQTT") + # New schema: ts is Unix epoch ms, close to "now". + self.assertIn("ts", start_payload, + "talker start payload missing 'ts' field") + start_ts = start_payload["ts"] + self.assertIsInstance(start_ts, int) + self.assertGreaterEqual(start_ts, t0_ms - 5_000) + self.assertLessEqual(start_ts, t0_ms + 60_000) # Flat talker//start should NOT be published for trunk talkers flat_start_events = [r for r in received @@ -1539,7 +1548,8 @@ class TestTrunkIntegration(unittest.TestCase): "Flat talker//start must not be published for " "trunk talkers (should use peer-namespaced topic)") - # Send talker stop and verify + # Hold the talker briefly so duration_ms is non-zero. + time.sleep(0.5) peer.send_talker_stop(tg) time.sleep(2) @@ -1551,6 +1561,28 @@ class TestTrunkIntegration(unittest.TestCase): self.assertTrue(len(stop_events) > 0, f"Expected MQTT talker stop at '{expected_stop_topic}', " f"got topics: {[r[0] for r in received]}") + stop_payload = stop_events[0][1] + self.assertIn("ts", stop_payload, + "talker stop payload missing 'ts' field") + self.assertGreaterEqual(stop_payload["ts"], start_ts) + # duration_ms should be present (matching start was observed) + # and roughly match the time between start and stop. + self.assertIn("duration_ms", stop_payload, + "talker stop payload missing 'duration_ms' field") + self.assertGreaterEqual(stop_payload["duration_ms"], 400) + self.assertEqual( + stop_payload["duration_ms"], stop_payload["ts"] - start_ts, + "duration_ms should equal stop ts minus start ts") + + # Note on edge cases not exercised here: + # MqttPublisher omits duration_ms when no matching start was + # recorded (reflector restart) or when the wall clock moved + # backwards between start and stop (NTP correction yielding a + # negative duration). Both paths are guarded in + # MqttPublisher::onTalkerStop / onPeerTalkerStop. Reaching + # them from this integration suite would require restarting + # the reflector mid-talker or manipulating its clock; the + # behaviour is documented in docs/MQTT.md instead. peer.close() finally: