feat(mqtt): add ts and duration_ms to talker start/stop events

Talker MQTT payloads now carry a Unix-epoch-ms `ts` field on both start
and stop. Stop additionally carries `duration_ms` whenever a matching
start was observed by the same MqttPublisher instance and the resulting
duration is non-negative. Both fields are additive — older consumers
that only read `callsign` continue to work unchanged.

Implementation
- MqttPublisher tracks per-(peer_id, tg) start_ms in a small std::map.
  Local talkers use peer_id="" as the map key. The entry is consumed on
  the matching stop.
- On stop, duration_ms is computed as `now - start_ms`. The field is
  omitted when:
  * no matching start was recorded (e.g. reflector restarted mid-talker)
  * the resulting duration is negative (backwards NTP correction during
    the transmission)
  Both edge cases are documented in docs/MQTT.md.
- Applies symmetrically across the four publish paths:
  onTalkerStart / onTalkerStop / onPeerTalkerStart / onPeerTalkerStop.

Tests
- test_trunk.py::test_18_mqtt_talker_event extended:
  * asserts `ts` is present on start, parses as int, lies within a
    +/- 60s window of the test's local clock.
  * asserts `ts` on stop is >= start ts.
  * asserts `duration_ms` on stop is present, >= the held-talker time
    (~500 ms), and equals stop_ts - start_ts.
- Edge-case behaviour (no-start, backwards clock jump) is guarded in
  code and documented; reaching it from the integration suite would
  require restarting the reflector mid-talker or injecting a clock
  step, so it is not asserted from outside.

Docs
- docs/MQTT.md: payload examples updated for both flat and
  peer-namespaced talker topics; new paragraph spelling out the two
  conditions under which duration_ms is omitted.
- docs/MESSAGING_IDEAS.md: Telegram-bot example extended to also
  handle /stop with a `duration_ms >= 1000` filter (kerchunk
  suppression) and a short note on how `ts`/`duration_ms` map to
  end-to-end pipeline latency and session length.
This commit is contained in:
Audric committed 2026-05-07 17:02:39 +02:00
1 parent 52b5e4f3cf
commit ccf34adbe6
5 files changed
+130 -5

No files matched your search

+15 -1
View File
@@ -193,10 +193,17 @@ CHAT_ID = "YOUR_CHAT_ID"
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
data = json.loads(msg.payload) data = json.loads(msg.payload)
if msg.topic.endswith("/start"):
tg = msg.topic.split("/")[-2] tg = msg.topic.split("/")[-2]
if msg.topic.endswith("/start"):
bot.send_message(CHAT_ID, bot.send_message(CHAT_ID,
f"📡 {data['callsign']} talking on TG {tg}") 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 = mqtt.Client()
client.username_pw_set("user", "pass") client.username_pw_set("user", "pass")
@@ -206,6 +213,13 @@ client.subscribe("svxreflector/+/talker/#")
client.loop_forever() 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 ## Contributing Ideas
+28 -2
View File
@@ -62,11 +62,32 @@ below).
{TOPIC_PREFIX}/talker/{tg}/stop {TOPIC_PREFIX}/talker/{tg}/stop
``` ```
Payload: Payload (start):
```json ```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 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 to this reflector. Non-retained. Dashboards that want every talker on the mesh
(local + peer) must also subscribe to `peer/+/talker/+/start` and (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 `rx` and `status` payloads are JSON strings with the same schema as their
local equivalents (`client/.../rx` and `client/.../status`). 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 **Retained-store growth note.** When a peer client disconnects, the retained
`peer/{peer_id}/client/{callsign}/rx` and `.../status` topics survive in the `peer/{peer_id}/client/{callsign}/rx` and `.../status` topics survive in the
broker until cleared. The reflector **does not automatically clear** them on broker until cleared. The reflector **does not automatically clear** them on
+43
View File
@@ -1,5 +1,6 @@
#include "MqttPublisher.h" #include "MqttPublisher.h"
#include <chrono>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <mosquitto.h> #include <mosquitto.h>
@@ -9,6 +10,14 @@
using namespace std; using namespace std;
int64_t MqttPublisher::nowMs(void)
{
using namespace std::chrono;
return duration_cast<milliseconds>(
system_clock::now().time_since_epoch()).count();
}
static void on_connect_cb(struct mosquitto*, void*, int rc) static void on_connect_cb(struct mosquitto*, void*, int rc)
{ {
if (rc == 0) 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, void MqttPublisher::onTalkerStart(uint32_t tg, const std::string& callsign,
bool is_trunk) bool is_trunk)
{ {
const int64_t ts = nowMs();
m_talker_start_ms[{string(), tg}] = ts;
Json::Value payload; Json::Value payload;
payload["callsign"] = callsign; payload["callsign"] = callsign;
payload["source"] = is_trunk ? "trunk" : "local"; payload["source"] = is_trunk ? "trunk" : "local";
payload["ts"] = static_cast<Json::Int64>(ts);
Json::StreamWriterBuilder wb; Json::StreamWriterBuilder wb;
wb["indentation"] = ""; wb["indentation"] = "";
string topic = "talker/" + to_string(tg) + "/start"; 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, void MqttPublisher::onTalkerStop(uint32_t tg, const std::string& callsign,
bool is_trunk) bool is_trunk)
{ {
const int64_t ts = nowMs();
Json::Value payload; Json::Value payload;
payload["callsign"] = callsign; payload["callsign"] = callsign;
payload["source"] = is_trunk ? "trunk" : "local"; payload["source"] = is_trunk ? "trunk" : "local";
payload["ts"] = static_cast<Json::Int64>(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<Json::Int64>(dur);
m_talker_start_ms.erase(it);
}
Json::StreamWriterBuilder wb; Json::StreamWriterBuilder wb;
wb["indentation"] = ""; wb["indentation"] = "";
string topic = "talker/" + to_string(tg) + "/stop"; string topic = "talker/" + to_string(tg) + "/stop";
@@ -272,9 +299,13 @@ void MqttPublisher::onPeerTalkerStart(const std::string& peer_id,
" (tg=", tg, " callsign='", callsign, "')"); " (tg=", tg, " callsign='", callsign, "')");
return; return;
} }
const int64_t ts = nowMs();
m_talker_start_ms[{peer_id, tg}] = ts;
Json::Value payload; Json::Value payload;
payload["callsign"] = callsign; payload["callsign"] = callsign;
payload["tg"] = static_cast<Json::UInt>(tg); payload["tg"] = static_cast<Json::UInt>(tg);
payload["ts"] = static_cast<Json::Int64>(ts);
Json::StreamWriterBuilder wb; Json::StreamWriterBuilder wb;
wb["indentation"] = ""; wb["indentation"] = "";
string topic = "peer/" + peer_id + "/talker/" + to_string(tg) + "/start"; 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, "')"); " (tg=", tg, " callsign='", callsign, "')");
return; return;
} }
const int64_t ts = nowMs();
Json::Value payload; Json::Value payload;
payload["callsign"] = callsign; payload["callsign"] = callsign;
payload["tg"] = static_cast<Json::UInt>(tg); payload["tg"] = static_cast<Json::UInt>(tg);
payload["ts"] = static_cast<Json::Int64>(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<Json::Int64>(dur);
m_talker_start_ms.erase(it);
}
Json::StreamWriterBuilder wb; Json::StreamWriterBuilder wb;
wb["indentation"] = ""; wb["indentation"] = "";
string topic = "peer/" + peer_id + "/talker/" + to_string(tg) + "/stop"; string topic = "peer/" + peer_id + "/talker/" + to_string(tg) + "/stop";
+10
View File
@@ -5,6 +5,8 @@
#include <cstdint> #include <cstdint>
#include <ctime> #include <ctime>
#include <vector> #include <vector>
#include <map>
#include <utility>
#include <json/json.h> #include <json/json.h>
#include "ReflectorMsg.h" #include "ReflectorMsg.h"
@@ -92,6 +94,14 @@ class MqttPublisher
time_t m_last_pub_err_logged = 0; time_t m_last_pub_err_logged = 0;
uint64_t m_pub_err_suppressed = 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 ("<peer_id>", tg).
// At most one talker is active per (peer_id, tg) at any moment, so the
// pair is a sufficient key.
std::map<std::pair<std::string, uint32_t>, int64_t> m_talker_start_ms;
static int64_t nowMs(void);
void publish(const std::string& topic_suffix, const std::string& payload, void publish(const std::string& topic_suffix, const std::string& payload,
bool retain = false); bool retain = false);
+34 -2
View File
@@ -1518,6 +1518,7 @@ class TestTrunkIntegration(unittest.TestCase):
peer_id = "TRUNK_TEST" peer_id = "TRUNK_TEST"
tg = 1220 # Owned by reflector-a (prefix 122) tg = 1220 # Owned by reflector-a (prefix 122)
t0_ms = int(time.time() * 1000)
peer.send_talker_start(tg, "N0MQTT") peer.send_talker_start(tg, "N0MQTT")
time.sleep(2) # Allow propagation time.sleep(2) # Allow propagation
@@ -1530,7 +1531,15 @@ class TestTrunkIntegration(unittest.TestCase):
self.assertTrue(len(start_events) > 0, self.assertTrue(len(start_events) > 0,
f"Expected MQTT talker start at '{expected_start_topic}', " f"Expected MQTT talker start at '{expected_start_topic}', "
f"got topics: {[r[0] for r in received]}") 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/<tg>/start should NOT be published for trunk talkers # Flat talker/<tg>/start should NOT be published for trunk talkers
flat_start_events = [r for r in received flat_start_events = [r for r in received
@@ -1539,7 +1548,8 @@ class TestTrunkIntegration(unittest.TestCase):
"Flat talker/<tg>/start must not be published for " "Flat talker/<tg>/start must not be published for "
"trunk talkers (should use peer-namespaced topic)") "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) peer.send_talker_stop(tg)
time.sleep(2) time.sleep(2)
@@ -1551,6 +1561,28 @@ class TestTrunkIntegration(unittest.TestCase):
self.assertTrue(len(stop_events) > 0, self.assertTrue(len(stop_events) > 0,
f"Expected MQTT talker stop at '{expected_stop_topic}', " f"Expected MQTT talker stop at '{expected_stop_topic}', "
f"got topics: {[r[0] for r in received]}") 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() peer.close()
finally: finally: