publishing: MQTT works in satellite mode + Redis publishes per-client status blob

- Move MQTT init above the satellite early-return in Reflector::initialize so
  satellite-mode reflectors publish to MQTT (client connect/disconnect, talker
  events, full status, etc.) just like full reflectors.
- Add reflector-sat (SATELLITE_OF=reflector-a) to the default test compose so
  satellite mode is exercised end-to-end. New test_31 verifies MQTT
  client-connect/disconnect events under the satellite's own topic prefix.
- Add RedisStore::pushClientStatus and Reflector::publishClientStatus to write
  the per-client status JSON (qth, rx siglev/sql_open/enabled/active,
  monitoredTGs, selected TG, ...) to live:client:<callsign>.status. Hooked
  from publishRxUpdate, handleNodeInfo, setMonitoredTGs, and setTg.
- New Redis test_live_client_status_blob sends a synthetic MsgNodeInfoV2 with
  qth+rx and asserts the parsed blob contains the expected fields.

31/31 trunk + 10/10 twin + 14/14 redis pass.
This commit is contained in:
Audric committed 2026-04-17 01:05:37 +02:00
1 parent 6b7a1f0306
commit 688a62ec5b
10 files changed
+299 -33

No files matched your search

+15
View File
@@ -314,6 +314,21 @@ void RedisStore::clearLiveClient(const std::string& callsign) {
m_live_queue->push(std::move(op)); m_live_queue->push(std::move(op));
} }
void RedisStore::pushClientStatus(const std::string& callsign,
const std::string& status_json) {
if (!m_live_queue) return;
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::HSET;
op.key = keyFor("live:client:" + callsign);
m_live_keys.insert(op.key);
op.fields = {
{"status", status_json},
{"updated_at", std::to_string(std::time(nullptr))}
};
op.ttl_s = 60;
m_live_queue->push(std::move(op));
}
void RedisStore::pushPeerNode(const std::string& peer_id, void RedisStore::pushPeerNode(const std::string& peer_id,
const std::string& callsign, const std::string& callsign,
uint32_t tg, uint32_t tg,
+5
View File
@@ -78,6 +78,11 @@ class RedisStore : public sigc::trackable
const std::string& codecs, const std::string& codecs,
uint32_t current_tg); uint32_t current_tg);
void clearLiveClient(const std::string& callsign); void clearLiveClient(const std::string& callsign);
// Publish the rich per-client status blob (rx levels, monitoredTGs,
// qth/location etc.) as a serialized JSON string in the `status`
// field of the existing live:client:<callsign> hash.
void pushClientStatus(const std::string& callsign,
const std::string& status_json);
void pushLiveTrunk(const std::string& section, void pushLiveTrunk(const std::string& section,
const std::string& state, const std::string& state,
const std::string& peer_id); const std::string& peer_id);
+43 -28
View File
@@ -483,6 +483,35 @@ bool Reflector::initialize(Async::Config &cfg)
// Parse CLUSTER_TGS — comma-separated list of TG numbers broadcast to all peers // Parse CLUSTER_TGS — comma-separated list of TG numbers broadcast to all peers
reloadClusterTgs(); reloadClusterTgs();
// Initialize MQTT publisher if [MQTT] section is configured.
// Done before the satellite early-return so satellites publish too.
std::string mqtt_host;
if (cfg.getValue("MQTT", "HOST", mqtt_host))
{
m_mqtt = new MqttPublisher(cfg);
if (!m_mqtt->initialize())
{
cerr << "*** WARNING: MQTT publisher failed to initialize, continuing without MQTT" << endl;
delete m_mqtt;
m_mqtt = nullptr;
}
else
{
// Set up periodic status publishing
unsigned status_interval = 1000;
cfg.getValue("MQTT", "STATUS_INTERVAL", status_interval);
m_mqtt_status_timer.setTimeout(status_interval);
m_mqtt_status_timer.setEnable(true);
m_mqtt_status_timer.expired.connect(
[this](Async::Timer*)
{
refreshStatus();
m_mqtt->publishFullStatus(m_status);
m_mqtt_status_timer.setEnable(true);
});
}
}
// Satellite mode: connect to parent instead of joining the trunk mesh // Satellite mode: connect to parent instead of joining the trunk mesh
std::string satellite_of; std::string satellite_of;
if (cfg.getValue("GLOBAL", "SATELLITE_OF", satellite_of) && if (cfg.getValue("GLOBAL", "SATELLITE_OF", satellite_of) &&
@@ -518,34 +547,6 @@ bool Reflector::initialize(Async::Config &cfg)
initTwinServer(); initTwinServer();
initSatelliteServer(); initSatelliteServer();
// Initialize MQTT publisher if [MQTT] section is configured
std::string mqtt_host;
if (cfg.getValue("MQTT", "HOST", mqtt_host))
{
m_mqtt = new MqttPublisher(cfg);
if (!m_mqtt->initialize())
{
cerr << "*** WARNING: MQTT publisher failed to initialize, continuing without MQTT" << endl;
delete m_mqtt;
m_mqtt = nullptr;
}
else
{
// Set up periodic status publishing
unsigned status_interval = 1000;
cfg.getValue("MQTT", "STATUS_INTERVAL", status_interval);
m_mqtt_status_timer.setTimeout(status_interval);
m_mqtt_status_timer.setEnable(true);
m_mqtt_status_timer.expired.connect(
[this](Async::Timer*)
{
refreshStatus();
m_mqtt->publishFullStatus(m_status);
m_mqtt_status_timer.setEnable(true);
});
}
}
return true; return true;
} /* Reflector::initialize */ } /* Reflector::initialize */
@@ -2961,9 +2962,23 @@ void Reflector::publishRxUpdate(ReflectorClient* client)
{ {
m_mqtt->onRxUpdate(client->callsign(), client->rxStatusJson()); m_mqtt->onRxUpdate(client->callsign(), client->rxStatusJson());
} }
publishClientStatus(client);
} /* Reflector::publishRxUpdate */ } /* Reflector::publishRxUpdate */
void Reflector::publishClientStatus(ReflectorClient* client)
{
if (m_redis == nullptr || client == nullptr) return;
const std::string& cs = client->callsign();
if (cs.empty()) return;
if (!m_status["nodes"].isMember(cs)) return;
Json::StreamWriterBuilder wb;
wb["indentation"] = "";
m_redis->pushClientStatus(cs,
Json::writeString(wb, m_status["nodes"][cs]));
} /* Reflector::publishClientStatus */
void Reflector::onClientAuthenticated(const std::string& callsign, void Reflector::onClientAuthenticated(const std::string& callsign,
uint32_t tg, const std::string& ip) uint32_t tg, const std::string& ip)
{ {
+3
View File
@@ -260,6 +260,9 @@ class Reflector : public sigc::trackable
void forwardFlushToSatellitesExcept(SatelliteLink* except, uint32_t tg); void forwardFlushToSatellitesExcept(SatelliteLink* except, uint32_t tg);
void publishRxUpdate(ReflectorClient* client); void publishRxUpdate(ReflectorClient* client);
// Push the rich per-client status blob (rx, monitoredTGs, qth, ...)
// to Redis. Cheap no-op if Redis is not configured.
void publishClientStatus(ReflectorClient* client);
void onClientAuthenticated(const std::string& callsign, uint32_t tg, void onClientAuthenticated(const std::string& callsign, uint32_t tg,
const std::string& ip); const std::string& ip);
void notifyExternalTrunkTalkerStart(uint32_t tg, void notifyExternalTrunkTalkerStart(uint32_t tg,
@@ -1016,6 +1016,7 @@ void ReflectorClient::handleNodeInfo(std::istream& is)
<< "]: Failed to parse MsgNodeInfo JSON object: " << "]: Failed to parse MsgNodeInfo JSON object: "
<< e.what() << std::endl; << e.what() << std::endl;
} }
if (m_reflector != nullptr) m_reflector->publishClientStatus(this);
} /* ReflectorClient::handleNodeInfo */ } /* ReflectorClient::handleNodeInfo */
@@ -1433,6 +1434,7 @@ void ReflectorClient::setMonitoredTGs(const std::set<uint32_t>& tgs)
monitored_tgs.append(tg); monitored_tgs.append(tg);
} }
} }
if (m_reflector != nullptr) m_reflector->publishClientStatus(this);
} /* ReflectorClient::setMonitoredTGs */ } /* ReflectorClient::setMonitoredTGs */
@@ -1467,6 +1469,7 @@ void ReflectorClient::setTg(uint32_t tg)
} }
updateIsTalker(); updateIsTalker();
if (m_reflector != nullptr) m_reflector->publishClientStatus(this);
} /* ReflectorClient::setTg */ } /* ReflectorClient::setTg */
+7 -4
View File
@@ -5,7 +5,7 @@
The integration tests verify the trunk protocol, satellite links, twin (HA-pair) protocol, Redis-backed config store, and end-to-end audio routing by spinning up reflector meshes in Docker Compose and connecting fake peers and clients from a Python test harness. The integration tests verify the trunk protocol, satellite links, twin (HA-pair) protocol, Redis-backed config store, and end-to-end audio routing by spinning up reflector meshes in Docker Compose and connecting fake peers and clients from a Python test harness.
`run_tests.sh` runs in **two phases**: `run_tests.sh` runs in **two phases**:
1. A 3-reflector trunk mesh exercising `test_trunk.py` (30 tests). 1. A 3-reflector trunk mesh + a satellite-mode reflector exercising `test_trunk.py` (31 tests).
2. A 4-reflector twin topology exercising `test_twin.py` (10 tests). 2. A 4-reflector twin topology exercising `test_twin.py` (10 tests).
A separate harness (`run_redis_tests.sh`) runs `test_redis.py` (13 tests) against a single-reflector + Redis stack. See [Redis Integration Tests](#redis-integration-tests) below. A separate harness (`run_redis_tests.sh`) runs `test_redis.py` (13 tests) against a single-reflector + Redis stack. See [Redis Integration Tests](#redis-integration-tests) below.
@@ -22,7 +22,7 @@ bash run_tests.sh
This will: This will:
1. Generate the default configs and `docker-compose.test.yml` from `topology.py` 1. Generate the default configs and `docker-compose.test.yml` from `topology.py`
2. Build and start the 3-reflector mesh 2. Build and start the 3-reflector mesh
3. Run 30 automated trunk/satellite/MQTT tests (`test_trunk.py`) 3. Run 31 automated trunk/satellite/MQTT tests (`test_trunk.py`)
4. Enter an interactive prompt to manually test any TG number 4. Enter an interactive prompt to manually test any TG number
5. Tear down the default mesh 5. Tear down the default mesh
6. Regenerate with `--topology twin` (4-reflector twin topology) 6. Regenerate with `--topology twin` (4-reflector twin topology)
@@ -58,7 +58,7 @@ Two fake trunk peers connect from the test harness:
Two V2 clients are configured on every reflector: Two V2 clients are configured on every reflector:
- **N0TEST** / **N0SEND** (group `TestGroup`, password `testpass`) - **N0TEST** / **N0SEND** (group `TestGroup`, password `testpass`)
A satellite server is enabled on reflector-a (port 5303, secret `sat_secret`). A satellite server is enabled on reflector-a (port 5303, secret `sat_secret`). A real satellite-mode reflector (`reflector-sat`, `SATELLITE_OF=reflector-a`) also runs in the compose so tests can verify satellite-mode behavior end-to-end (e.g. that MQTT publishing still works).
All test configs have `TRUNK_DEBUG=1` enabled for verbose trunk logging during test runs. All test configs have `TRUNK_DEBUG=1` enabled for verbose trunk logging during test runs.
@@ -69,6 +69,7 @@ All test configs have `TRUNK_DEBUG=1` enabled for verbose trunk logging during t
| a | 15300 | 15302 | 18080| 15303 | | a | 15300 | 15302 | 18080| 15303 |
| b | 25300 | 25302 | 28080| — | | b | 25300 | 25302 | 28080| — |
| c | 35300 | 35302 | 38080| — | | c | 35300 | 35302 | 38080| — |
| sat | 55300 | — | 58080| — |
Internal ports inside Docker are always 5300, 5302, 8080, 5303. Internal ports inside Docker are always 5300, 5302, 8080, 5303.
@@ -113,7 +114,7 @@ Internal port for `[TWIN]` is always 5304; satellite is 5303.
|------|---------| |------|---------|
| `topology.py` | Single source of truth — prefixes, ports, secrets, cluster TGs, test clients. Contains both the default mesh (`REFLECTORS`) and the `TWIN_REFLECTORS` / `TWIN_TRUNKS` definitions. | | `topology.py` | Single source of truth — prefixes, ports, secrets, cluster TGs, test clients. Contains both the default mesh (`REFLECTORS`) and the `TWIN_REFLECTORS` / `TWIN_TRUNKS` definitions. |
| `generate_configs.py` | Generates `configs/*.conf` and `docker-compose.test.yml` from topology. Supports `--topology default` (implicit) and `--topology twin`. | | `generate_configs.py` | Generates `configs/*.conf` and `docker-compose.test.yml` from topology. Supports `--topology default` (implicit) and `--topology twin`. |
| `test_trunk.py` | Test harness: fake trunk peers, satellite peer, V2 client, 30 test cases, interactive loop. | | `test_trunk.py` | Test harness: fake trunk peers, satellite peer, V2 client, 31 test cases, interactive loop. |
| `test_twin.py` | TWIN-protocol tests (10 cases) using the twin topology. Reuses `ClientPeer` and `SatellitePeer` from `test_trunk.py`. | | `test_twin.py` | TWIN-protocol tests (10 cases) using the twin topology. Reuses `ClientPeer` and `SatellitePeer` from `test_trunk.py`. |
| `run_tests.sh` | Orchestrator: generate → build → trunk tests → teardown → regenerate twin → build → twin tests → teardown. | | `run_tests.sh` | Orchestrator: generate → build → trunk tests → teardown → regenerate twin → build → twin tests → teardown. |
| `configs/` | Generated reflector config files (do not edit manually) | | `configs/` | Generated reflector config files (do not edit manually) |
@@ -187,6 +188,7 @@ Simulates a V2 SvxLink client. Performs the full TCP authentication handshake (P
| 28 | MQTT client connect/disconnect | V2 client connect publishes `client/<callsign>/connected` (with `tg`, `ip`); disconnect publishes `client/<callsign>/disconnected` | | 28 | MQTT client connect/disconnect | V2 client connect publishes `client/<callsign>/connected` (with `tg`, `ip`); disconnect publishes `client/<callsign>/disconnected` |
| 29 | MQTT full status | Periodic retained `status` message arrives and contains `nodes` and `trunks` keys | | 29 | MQTT full status | Periodic retained `status` message arrives and contains `nodes` and `trunks` keys |
| 30 | MQTT local nodes | Client connect triggers retained `nodes/local` message listing the client's callsign with `timestamp` | | 30 | MQTT local nodes | Client connect triggers retained `nodes/local` message listing the client's callsign with `timestamp` |
| 31 | MQTT works in satellite mode | A satellite-mode reflector (`reflector-sat`, `SATELLITE_OF=reflector-a`) publishes `client/<callsign>/connected` and `disconnected` events under its own topic prefix |
### Per-Trunk Filters and Mapping (jayReflector additions) ### Per-Trunk Filters and Mapping (jayReflector additions)
@@ -250,6 +252,7 @@ Each test writes directly to Redis via `redis-cli` inside the container, publish
| 4 | Allow change triggers reload | Adding an allow-list entry produces a matching `Reloaded filters` line | | 4 | Allow change triggers reload | Adding an allow-list entry produces a matching `Reloaded filters` line |
| 5 | `live:client` appears on auth | On V2 authentication, `live:client:<callsign>` hash is populated with `connected_at`, `ip`, `tg`, `codecs` | | 5 | `live:client` appears on auth | On V2 authentication, `live:client:<callsign>` hash is populated with `connected_at`, `ip`, `tg`, `codecs` |
| 6 | `live:client` disappears on disconnect | After forceful TCP close the hash is removed within ~5 s | | 6 | `live:client` disappears on disconnect | After forceful TCP close the hash is removed within ~5 s |
| 6b | `live:client` rich status blob | After the client sends `MsgNodeInfo`, `live:client:<callsign>.status` holds the full per-client JSON (qth, rx params, monitoredTGs) and `updated_at` |
| 7 | Outage + resync | Stopping Redis keeps existing clients connected; on restart the reflector logs `config.changed: all` and accepts newly-written users | | 7 | Outage + resync | Stopping Redis keeps existing clients connected; on restart the reflector logs `config.changed: all` and accepts newly-written users |
| 8 | `--import-conf-to-redis` idempotent | Running the importer twice against the same `.conf` produces identical keyspace dumps | | 8 | `--import-conf-to-redis` idempotent | Running the importer twice against the same `.conf` produces identical keyspace dumps |
| 9 | Peer node list populates + diffs | Inbound `MsgTrunkNodeList` creates `live:peer_node:<section>:<callsign>` hashes; a shrunk follow-up list DELs dropped callsigns and updates mutated fields (e.g. `tg`) | | 9 | Peer node list populates + diffs | Inbound `MsgTrunkNodeList` creates `live:peer_node:<section>:<callsign>` hashes; a shrunk follow-up list DELs dropped callsigns and updates mutated fields (e.g. `tg`) |
+82
View File
@@ -126,6 +126,57 @@ def generate_reflector_conf(name: str) -> str:
return "\n".join(lines) return "\n".join(lines)
def generate_satellite_node_conf() -> str:
"""Generate svxreflector.conf for a satellite-mode reflector that
connects to the primary reflector as a satellite peer."""
sat = T.SATELLITE_NODE
parent = T.sat_node_parent()
parent_svc = T.service_name(parent)
parent_prefix = T.prefix_str(T.REFLECTORS[parent]["prefix"])
lines = [
"[GLOBAL]",
'TIMESTAMP_FORMAT="%c"',
f"LISTEN_PORT={T.INTERNAL_CLIENT_PORT}",
"TG_FOR_V1_CLIENTS=999",
f"LOCAL_PREFIX={parent_prefix}",
f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}",
f"SATELLITE_OF={parent_svc}",
f"SATELLITE_PORT={T.SATELLITE['listen_port']}",
f"SATELLITE_SECRET={T.SATELLITE['secret']}",
f"SATELLITE_ID={sat['id']}",
"",
"[SERVER_CERT]",
f"COMMON_NAME={T.sat_node_service_name()}",
"",
"[USERS]",
]
groups_seen = set()
for client in T.TEST_CLIENTS:
lines.append(f"{client['callsign']}={client['group']}")
groups_seen.add(client['group'])
lines += [
"",
"[PASSWORDS]",
]
for client in T.TEST_CLIENTS:
if client['group'] in groups_seen:
lines.append(f"{client['group']}={client['password']}")
groups_seen.discard(client['group'])
lines += [
"",
"[MQTT]",
f"HOST={T.MQTT['host']}",
f"PORT={T.MQTT['port']}",
f"USERNAME={T.MQTT['username']}",
f"PASSWORD={T.MQTT['password']}",
f"TOPIC_PREFIX=svxreflector/{sat['name']}",
"STATUS_INTERVAL=1000",
"",
]
return "\n".join(lines)
def generate_docker_compose() -> str: def generate_docker_compose() -> str:
"""Generate docker-compose.test.yml content.""" """Generate docker-compose.test.yml content."""
services = [] services = []
@@ -174,6 +225,30 @@ def generate_docker_compose() -> str:
networks: networks:
- trunk_mesh{depends_on_line}""") - trunk_mesh{depends_on_line}""")
# Satellite-mode reflector — joins the primary as a satellite. Used
# to verify satellite-mode behavior (MQTT publishing, V2 client server).
sat_svc = T.sat_node_service_name()
sat_vol = f"pki-{T.SATELLITE_NODE['name']}"
volumes.append(sat_vol)
services.append(f""" {sat_svc}:
build:
context: ..
dockerfile: Dockerfile
volumes:
- ./configs/{sat_svc}.conf:/etc/svxlink/svxreflector.conf:ro
- {sat_vol}:/var/lib/svxlink/pki
ports:
- "{T.sat_node_mapped_client_port()}:{T.INTERNAL_CLIENT_PORT}/tcp"
- "{T.sat_node_mapped_client_port()}:{T.INTERNAL_CLIENT_PORT}/udp"
- "{T.sat_node_mapped_http_port()}:{T.INTERNAL_HTTP_PORT}/tcp"
healthcheck:
test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/{T.INTERNAL_HTTP_PORT}) 2>/dev/null'"]
interval: 2s
timeout: 2s
retries: 15
networks:
- trunk_mesh""")
# Mosquitto broker for MQTT testing # Mosquitto broker for MQTT testing
services.append(""" mosquitto: services.append(""" mosquitto:
image: eclipse-mosquitto:2 image: eclipse-mosquitto:2
@@ -496,6 +571,13 @@ def main():
f.write(content) f.write(content)
print(f" wrote {os.path.relpath(path, script_dir)}") print(f" wrote {os.path.relpath(path, script_dir)}")
# Satellite-mode reflector config
sat_path = os.path.join(configs_dir,
f"{T.sat_node_service_name()}.conf")
with open(sat_path, "w") as f:
f.write(generate_satellite_node_conf())
print(f" wrote {os.path.relpath(sat_path, script_dir)}")
# Generate docker-compose # Generate docker-compose
compose_path = os.path.join(script_dir, "docker-compose.test.yml") compose_path = os.path.join(script_dir, "docker-compose.test.yml")
with open(compose_path, "w") as f: with open(compose_path, "w") as f:
+56 -1
View File
@@ -14,7 +14,7 @@ import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import topology_redis as T import topology_redis as T
from test_trunk import ClientPeer, TrunkPeer from test_trunk import ClientPeer, TrunkPeer, send_frame, pack_string
HOST = "127.0.0.1" HOST = "127.0.0.1"
@@ -230,6 +230,61 @@ class RedisLiveStateTest(unittest.TestCase):
except Exception: except Exception:
pass pass
def test_live_client_status_blob(self):
"""After a V2 client sends MsgNodeInfo (qth + rx + monitoredTGs),
the rich status blob lands in live:client:<callsign>.status as a
serialized JSON string containing qth, rx params, and monitoredTGs."""
import json as _json
import struct as _struct
MSG_NODE_INFO_V2 = 111
peer = ClientPeer()
peer.connect(HOST, R1_CLIENT_PORT)
try:
peer.authenticate(callsign="N0TEST", password="testpass")
self._wait_for_hash(k("live:client:N0TEST"), present=True)
node_info = {
"swInfo": "test-client/1.0",
"qth": [{
"name": "Test QTH",
"lat": 45.5,
"lon": 9.2,
"rx": {"A": {"name": "TestRx"}},
"tx": {"A": {"name": "TestTx"}},
}],
}
payload = _struct.pack("!H", MSG_NODE_INFO_V2)
payload += pack_string(_json.dumps(node_info))
send_frame(peer.tcp, payload)
# Wait for status field to appear and parse as JSON
deadline = time.time() + 3.0
blob = ""
while time.time() < deadline:
blob = redis_cli("HGET", k("live:client:N0TEST"), "status")
if blob:
break
time.sleep(0.1)
self.assertNotEqual(blob, "",
"status field never appeared on live:client:N0TEST")
status = _json.loads(blob)
self.assertIn("qth", status)
self.assertEqual(status["qth"][0]["name"], "Test QTH")
self.assertAlmostEqual(status["qth"][0]["lat"], 45.5)
self.assertIn("rx", status["qth"][0])
self.assertIn("A", status["qth"][0]["rx"])
# Reflector populates default rx params after parsing NodeInfo
self.assertIn("siglev", status["qth"][0]["rx"]["A"])
self.assertIn("sql_open", status["qth"][0]["rx"]["A"])
self.assertIn("monitoredTGs", status)
finally:
try:
peer.tcp.close()
except Exception:
pass
def test_live_client_hash_disappears_on_disconnect(self): def test_live_client_hash_disappears_on_disconnect(self):
peer = ClientPeer() peer = ClientPeer()
peer.connect(HOST, R1_CLIENT_PORT) peer.connect(HOST, R1_CLIENT_PORT)
+63
View File
@@ -1872,6 +1872,69 @@ class TestTrunkIntegration(unittest.TestCase):
mc.loop_stop() mc.loop_stop()
mc.disconnect() mc.disconnect()
# ------------------------------------------------------------------
# Test 31: MQTT works in satellite mode
# ------------------------------------------------------------------
def test_31_mqtt_satellite_client_events(self):
"""A satellite-mode reflector publishes MQTT client connect and
disconnect events under its own topic prefix, just like a full
reflector. Verifies that the MQTT init runs before the satellite
early-return in Reflector::initialize()."""
sat_name = T.SATELLITE_NODE["name"]
sat_topic = f"svxreflector/{sat_name}/client/{CLIENT_CALLSIGN}"
received = []
sub_event = threading.Event()
def on_connect(client, userdata, flags, rc):
client.subscribe(f"{sat_topic}/#")
sub_event.set()
def on_message(client, userdata, msg):
try:
payload = json.loads(msg.payload)
except (ValueError, json.JSONDecodeError):
payload = msg.payload
received.append((msg.topic, payload))
mc = mqtt_client.Client()
mc.on_connect = on_connect
mc.on_message = on_message
mc.connect(HOST, 11883, 60)
mc.loop_start()
try:
self.assertTrue(sub_event.wait(timeout=5),
"MQTT subscribe timed out")
time.sleep(0.5)
client = ClientPeer()
client.connect(HOST, T.sat_node_mapped_client_port())
client.authenticate(callsign=CLIENT_CALLSIGN,
password=CLIENT_PASSWORD)
time.sleep(2)
connected_topic = f"{sat_topic}/connected"
conn_events = [r for r in received if r[0] == connected_topic]
self.assertTrue(len(conn_events) > 0,
f"Expected MQTT connected event from satellite, "
f"got topics: {[r[0] for r in received]}")
payload = conn_events[0][1]
self.assertIn("tg", payload)
self.assertIn("ip", payload)
received.clear()
client.close()
time.sleep(2)
disconnected_topic = f"{sat_topic}/disconnected"
disc_events = [r for r in received if r[0] == disconnected_topic]
self.assertTrue(len(disc_events) > 0,
f"Expected MQTT disconnected event from satellite, "
f"got topics: {[r[0] for r in received]}")
finally:
mc.loop_stop()
mc.disconnect()
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Custom test runner with clean, readable output # Custom test runner with clean, readable output
+22
View File
@@ -61,6 +61,15 @@ SATELLITE = {
"listen_port": 5303, "listen_port": 5303,
} }
# A real satellite-mode reflector — runs as a satellite of the primary
# reflector. Used to verify that satellite mode preserves features like
# MQTT publishing and the V2 client server.
SATELLITE_NODE = {
"name": "sat",
"id": "SAT_NODE",
"port_base": 55000,
}
# Redis broker — used by reflectors flagged `redis: True`. # Redis broker — used by reflectors flagged `redis: True`.
# Each reflector uses its own DB index to avoid pollution between tests. # Each reflector uses its own DB index to avoid pollution between tests.
REDIS = { REDIS = {
@@ -206,6 +215,19 @@ def service_name(name: str) -> str:
def mapped_satellite_port(name: str) -> int: def mapped_satellite_port(name: str) -> int:
return REFLECTORS[name]["trunk_port_base"] + 303 return REFLECTORS[name]["trunk_port_base"] + 303
def sat_node_service_name() -> str:
return f"reflector-{SATELLITE_NODE['name']}"
def sat_node_parent() -> str:
"""Parent reflector that the satellite-mode node attaches to."""
return sorted(REFLECTORS)[0]
def sat_node_mapped_client_port() -> int:
return SATELLITE_NODE["port_base"] + 300
def sat_node_mapped_http_port() -> int:
return SATELLITE_NODE["port_base"] + 3080
def trunk_section_name(name_a: str, name_b: str = "") -> str: def trunk_section_name(name_a: str, name_b: str = "") -> str:
"""Shared trunk section name for a link between two reflectors. """Shared trunk section name for a link between two reflectors.