From c3f3ff72d68e797c0f01c4d4da83ab0fe6f33bdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20P=C3=A9rez?= Date: Tue, 9 Jun 2026 12:58:47 -0400 Subject: [PATCH] feat(parrot): integrate playback via adn-server.py --parrot Add parrot runtime module, --no-proxy flag, minimal adn-parrot.example.yaml, systemd unit examples, and remove standalone adn-parrot.py launcher. --- CHANGELOG.md | 10 + README.md | 10 +- adn-parrot.example.yaml | 79 +------- adn-parrot.py | 49 ----- adn-server.py | 3 +- docs/en/server/user-guide/configuration.md | 6 +- docs/en/server/user-guide/introduction.md | 2 +- docs/en/server/user-guide/parrot.md | 24 ++- docs/es/server/user-guide/configuration.md | 6 +- docs/es/server/user-guide/introduction.md | 2 +- docs/es/server/user-guide/parrot.md | 24 ++- examples/systemd/adn-parrot.service | 32 ++++ examples/systemd/adn-server.service | 31 ++++ pyproject.toml | 1 - .../infrastructure/config_normalizer.py | 2 +- .../infrastructure/parrot/__init__.py | 5 + .../infrastructure/parrot/runtime.py | 110 +++++++++++ src/adn_server/main.py | 34 +++- src/adn_server/parrot_main.py | 175 ------------------ tests/infrastructure/test_parrot_cli.py | 122 ++++++++++++ tests/infrastructure/test_parrot_config.py | 34 ++++ 21 files changed, 438 insertions(+), 323 deletions(-) delete mode 100644 adn-parrot.py create mode 100644 examples/systemd/adn-parrot.service create mode 100644 examples/systemd/adn-server.service create mode 100644 src/adn_server/infrastructure/parrot/__init__.py create mode 100644 src/adn_server/infrastructure/parrot/runtime.py delete mode 100644 src/adn_server/parrot_main.py create mode 100644 tests/infrastructure/test_parrot_cli.py create mode 100644 tests/infrastructure/test_parrot_config.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3530eab..be72edc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to **adn-server** are documented here. Versioning follows [SemVer](https://semver.org/). +## [Unreleased] + +### Changed + +- Parrot: integrated in `adn-server.py --parrot`; minimal `adn-parrot.yaml` (PEER → ECHO MASTER). + +### Removed + +- **`adn-parrot.py`** and **`parrot_main.py`** — use `adn-server.py --parrot` instead. + ## [1.0.0] - 2026-06-06 First stable public release. diff --git a/README.md b/README.md index a09f5fb..ec3fea3 100644 --- a/README.md +++ b/README.md @@ -68,13 +68,15 @@ python adn-server.py -c /path/to/adn-server.yaml python adn-server.py --logging DEBUG ``` -## Parrot (Playback) +## Parrot (playback) -A separate entrypoint records incoming group voice and plays it back (echo/parrot). +Separate process (same binary) records group voice and plays it back on TG 9990. ```bash cp adn-parrot.example.yaml adn-parrot.yaml -python adn-parrot.py +python adn-server.py --parrot -c adn-parrot.yaml ``` -See [Parrot (playback)](docs/en/server/user-guide/parrot.md) in the docs site for an overview; extended notes may exist in private `docs-priv/` checkouts. +See [Parrot (playback)](docs/en/server/user-guide/parrot.md) in the docs site for an overview. + +**systemd:** example units in `examples/systemd/` (`adn-server.service`, `adn-parrot.service`). diff --git a/adn-parrot.example.yaml b/adn-parrot.example.yaml index 5b08c7a..f8dc240 100644 --- a/adn-parrot.example.yaml +++ b/adn-parrot.example.yaml @@ -1,84 +1,25 @@ -# ADN DMR Parrot (playback) - example configuration -# Copy to adn-parrot.yaml and set real secrets there (never commit adn-parrot.yaml). +# ADN DMR Parrot — minimal PEER config (copy to adn-parrot.yaml; do not commit). # -# The parrot runs as a PEER that connects to the ECHO MASTER (defined in adn-server.yaml). -# When a user transmits to TG 9990, the bridge forwards the call to ECHO, the parrot -# records the audio and plays it back. +# Separate process, same binary as adn-server: +# python adn-server.py --parrot -c adn-parrot.yaml +# +# Connects to ECHO (MASTER) in adn-server.yaml — match MASTER_PORT and PASSPHRASE. GLOBAL: - PATH: ./ - PING_TIME: 10 - MAX_MISSED: 3 - USE_ACL: true - REG_ACL: PERMIT:ALL - SUB_ACL: DENY:1 - TGID_TS1_ACL: PERMIT:ALL - TGID_TS2_ACL: PERMIT:ALL - ALLOW_NULL_PASSPHRASE: false - ANNOUNCEMENT_LANGUAGES: en_GB SERVER_ID: 9990 - DATA_GATEWAY: false - VALIDATE_SERVER_IDS: false - -REPORTS: - REPORT: false - REPORT_INTERVAL: 60 - REPORT_PORT: 4821 - REPORT_CLIENTS: "127.0.0.1" LOGGER: - # ENABLED: false # omit or true = normal; false = no console/file logs (NullHandler) LOG_FILE: /var/log/adn-server/parrot.log - LOG_HANDLERS: file-timed - LOG_LEVEL: DEBUG - LOG_NAME: ADN - -ALIASES: - TRY_DOWNLOAD: false - PATH: ./json/ - PEER_FILE: peer_ids.json - SUBSCRIBER_FILE: subscriber_ids.json - TGID_FILE: talkgroup_ids.json - PEER_URL: https://servers.adn.systems/peer_ids.json - SUBSCRIBER_URL: https://servers.adn.systems/subscriber_ids.json - TGID_URL: https://servers.adn.systems/talkgroup_ids.json - LOCAL_SUBSCRIBER_FILE: local_subscriber_ids.json - STALE_DAYS: 1 - SUB_MAP_FILE: "" - SERVER_ID_URL: https://servers.adn.systems/server_ids.tsv - SERVER_ID_FILE: server_ids.tsv + LOG_LEVEL: INFO SYSTEMS: PARROT: MODE: PEER - ENABLED: true - LOOSE: false - EXPORT_AMBE: false IP: 127.0.0.1 - PORT: 54915 # parrot local port + PORT: 54915 MASTER_IP: 127.0.0.1 - MASTER_PORT: 54917 # must match ECHO.PORT in adn-server.yaml - PASSPHRASE: "" # must match ECHO.PASSPHRASE - CALLSIGN: ECHO + MASTER_PORT: 54917 # = ECHO.PORT in adn-server.yaml + PASSPHRASE: "" RADIO_ID: 9990 - RX_FREQ: 000000000 - TX_FREQ: 000000000 - TX_POWER: 25 - COLORCODE: 1 - SLOTS: 2 - LATITUDE: 0 - LONGITUDE: 0 - HEIGHT: 0 - LOCATION: "9990 Parrot" - DESCRIPTION: ECHO - URL: adn.systems - SOFTWARE_ID: "20170620" - PACKAGE_ID: MMDVM_ADN-Systems - GROUP_HANGTIME: 5 + CALLSIGN: ECHO OPTIONS: "TS2=9990;" - USE_ACL: true - SUB_ACL: DENY:1 - TGID_TS1_ACL: DENY:ALL - TGID_TS2_ACL: PERMIT:9990 - ANNOUNCEMENT_LANGUAGE: en_GB - ALLOW_UNREG_ID: true diff --git a/adn-parrot.py b/adn-parrot.py deleted file mode 100644 index e39dc7d..0000000 --- a/adn-parrot.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python3 -# ADN DMR Parrot (playback) - launcher script -# Copyright (C) 2026 Rodrigo Pérez, CE5RPY -# -# Derived from ADN DMR Server / FreeDMR / HBlink. Original license: -############################################################################### -# Copyright (C) 2020 Simon Adlem, G7RZU -# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software Foundation, -# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -############################################################################### - -""" -Run the ADN DMR Parrot (playback) from the project root. - - python adn-parrot.py - python adn-parrot.py -c adn-parrot.yaml - python adn-parrot.py --logging DEBUG - -Config default: adn-parrot.yaml in this directory. -""" - -from __future__ import annotations - -import sys -from pathlib import Path - -_ROOT = Path(__file__).resolve().parent -if str(_ROOT) not in sys.path: - sys.path.insert(0, str(_ROOT)) -if str(_ROOT / "src") not in sys.path: - sys.path.insert(0, str(_ROOT / "src")) - -from adn_server.parrot_main import main - -if __name__ == "__main__": - main() diff --git a/adn-server.py b/adn-server.py index cd86c9f..e41806a 100644 --- a/adn-server.py +++ b/adn-server.py @@ -28,8 +28,9 @@ Run the ADN DMR Peer Server from the project root. python adn-server.py python adn-server.py -c adn-server.yaml python adn-server.py --logging DEBUG + python adn-server.py --parrot -c adn-parrot.yaml -Config default: adn-server.yaml in this directory. +Config default: adn-server.yaml (or adn-parrot.yaml with --parrot). """ from __future__ import annotations diff --git a/docs/en/server/user-guide/configuration.md b/docs/en/server/user-guide/configuration.md index fa44756..24086a7 100644 --- a/docs/en/server/user-guide/configuration.md +++ b/docs/en/server/user-guide/configuration.md @@ -27,11 +27,7 @@ After editing the main config you can reload **without restarting** the process kill -HUP $(pidof adn-server.py) # or: systemctl reload adn-server ``` -With **systemd**, add to your unit file: - -```ini -ExecReload=/bin/kill -HUP $MAINPID -``` +Example unit: **`examples/systemd/adn-server.service`** (copy to `/etc/systemd/system/`; includes `ExecReload` for `systemctl reload`). **Reload applies:** `GLOBAL`, `REPORTS`, `ALIASES`, **`LOGGER.LOG_LEVEL`** (without process restart), **`PROXY`** (timeouts, debug, block lists — not bind or target), **`SELF_SERVICE`** (merged; enabling/disabling DB loops needs restart), per-system settings, **new/removed SYSTEMS** (including `GENERATOR` expansion/collapse and new OpenBridge legs), and updated bind addresses (listener restart for that system only). diff --git a/docs/en/server/user-guide/introduction.md b/docs/en/server/user-guide/introduction.md index 236bc5c..5a588f6 100644 --- a/docs/en/server/user-guide/introduction.md +++ b/docs/en/server/user-guide/introduction.md @@ -26,7 +26,7 @@ Routing, timers, OpenBridge loop control, and protocol handling are implemented ## Related programs -- **Parrot / playback** — separate entrypoint (`adn-parrot.py`) for record-and-playback; see [Parrot](parrot.md). +- **Parrot / playback** — `adn-server.py --parrot` with minimal `adn-parrot.yaml`; see [Parrot](parrot.md). - **Integrated hotspot proxy** — `PROXY` in **`adn-server.yaml`**; see [Hotspot proxy](hotspot-proxy.md). ## Next steps diff --git a/docs/en/server/user-guide/parrot.md b/docs/en/server/user-guide/parrot.md index 6214f2f..56b1ea2 100644 --- a/docs/en/server/user-guide/parrot.md +++ b/docs/en/server/user-guide/parrot.md @@ -2,15 +2,35 @@ ## What it is -**Parrot** is a **separate entrypoint** (`adn-parrot.py` / `parrot_main`) that records incoming **group** voice and plays it back (echo / parrot), independent of the main bridge process. +**Parrot** records incoming **group** voice and plays it back (echo / parrot). It runs as a **PEER** that connects to the **ECHO** master on the main peer server (TG 9990 bridge). + +The playback runtime is part of **`adn-server`**; run **`adn-server.py --parrot`** with minimal **`adn-parrot.yaml`**. ## Configuration +Use a **small separate YAML** — only what the PEER needs to attach to **ECHO** in `adn-server.yaml`: + +| Field | Role | +|-------|------| +| `GLOBAL.SERVER_ID` | Parrot network identity (often `9990`) | +| `LOGGER` | Log file (optional but recommended) | +| `SYSTEMS.PARROT` | `MODE: PEER`, local `IP`/`PORT`, `MASTER_IP`/`MASTER_PORT`, `PASSPHRASE`, `RADIO_ID`, `CALLSIGN`, `OPTIONS` | + +No `PROXY`, `ALIASES`, or `REPORTS` required. **`MASTER_PORT`** and **`PASSPHRASE`** must match **`ECHO`** on the main server. + - Copy **`adn-parrot.example.yaml`** → **`adn-parrot.yaml`** (not committed). - Run: ```bash -python adn-parrot.py -c adn-parrot.yaml +python adn-server.py --parrot -c adn-parrot.yaml +``` + +Typical production: separate **systemd** unit (see `examples/systemd/adn-parrot.service` in the repo), same binary: + +```bash +sudo cp examples/systemd/adn-parrot.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now adn-parrot ``` ## Relation to TG 9990 / ECHO diff --git a/docs/es/server/user-guide/configuration.md b/docs/es/server/user-guide/configuration.md index 5508d43..fa971cd 100644 --- a/docs/es/server/user-guide/configuration.md +++ b/docs/es/server/user-guide/configuration.md @@ -27,11 +27,7 @@ Tras editar la config principal puedes recargar **sin reiniciar** el proceso (se kill -HUP $(pidof adn-server.py) # o: systemctl reload adn-server ``` -Con **systemd**, en la unidad: - -```ini -ExecReload=/bin/kill -HUP $MAINPID -``` +Unidad de ejemplo: **`examples/systemd/adn-server.service`** (copiar a `/etc/systemd/system/`; incluye `ExecReload` para `systemctl reload`). **Se recarga:** `GLOBAL`, `REPORTS`, `ALIASES`, **`LOGGER.LOG_LEVEL`** (sin reiniciar el proceso), **`PROXY`** (timeouts, debug, listas de bloqueo — no bind ni destino), **`SELF_SERVICE`** (fusionado; activar/desactivar bucles BD requiere reinicio), parámetros por system, **systems nuevos/eliminados** (incluida expansión/colapso `GENERATOR` y OBP nuevos), y cambios de IP/puerto (solo reinicia el listener de ese system). diff --git a/docs/es/server/user-guide/introduction.md b/docs/es/server/user-guide/introduction.md index 277a1db..edafaa0 100644 --- a/docs/es/server/user-guide/introduction.md +++ b/docs/es/server/user-guide/introduction.md @@ -26,7 +26,7 @@ Enrutado, temporizadores, control de bucle OpenBridge y manejo de protocolo est ## Programas relacionados -- **Parrot / reproducción** — punto de entrada aparte (`adn-parrot.py`) para grabar y reproducir; ver [Parrot](parrot.md). +- **Parrot / reproducción** — `adn-server.py --parrot` con `adn-parrot.yaml` mínimo; ver [Parrot](parrot.md). - **Proxy hotspot integrado** — `PROXY` en **`adn-server.yaml`**; ver [Proxy hotspot](hotspot-proxy.md). ## Siguientes pasos diff --git a/docs/es/server/user-guide/parrot.md b/docs/es/server/user-guide/parrot.md index 65e5a98..fcd8b98 100644 --- a/docs/es/server/user-guide/parrot.md +++ b/docs/es/server/user-guide/parrot.md @@ -2,15 +2,35 @@ ## Qué es -**Parrot** es un **punto de entrada separado** (`adn-parrot.py` / `parrot_main`) que graba voz de **grupo** entrante y la reproduce (eco / parrot), independiente del proceso principal del bridge. +**Parrot** graba voz de **grupo** entrante y la reproduce (eco / parrot). Corre como **PEER** conectado al master **ECHO** del peer server principal (bridge TG 9990). + +El runtime de playback forma parte de **`adn-server`**; ejecuta **`adn-server.py --parrot`** con un **`adn-parrot.yaml`** mínimo. ## Configuración +Usa un **YAML aparte y mínimo** — solo lo que el PEER necesita para unirse a **ECHO** en `adn-server.yaml`: + +| Campo | Rol | +|-------|-----| +| `GLOBAL.SERVER_ID` | Identidad de red del parrot (suele ser `9990`) | +| `LOGGER` | Fichero de log (opcional pero recomendado) | +| `SYSTEMS.PARROT` | `MODE: PEER`, `IP`/`PORT` local, `MASTER_IP`/`MASTER_PORT`, `PASSPHRASE`, `RADIO_ID`, `CALLSIGN`, `OPTIONS` | + +No hace falta `PROXY`, `ALIASES` ni `REPORTS`. **`MASTER_PORT`** y **`PASSPHRASE`** deben coincidir con **`ECHO`** en el servidor principal. + - Copiar **`adn-parrot.example.yaml`** → **`adn-parrot.yaml`** (no versionada). - Ejecutar: ```bash -python adn-parrot.py -c adn-parrot.yaml +python adn-server.py --parrot -c adn-parrot.yaml +``` + +En producción: unidad **systemd** aparte (plantilla `examples/systemd/adn-parrot.service`): + +```bash +sudo cp examples/systemd/adn-parrot.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now adn-parrot ``` ## Relación con TG 9990 / ECHO diff --git a/examples/systemd/adn-parrot.service b/examples/systemd/adn-parrot.service new file mode 100644 index 0000000..8540c70 --- /dev/null +++ b/examples/systemd/adn-parrot.service @@ -0,0 +1,32 @@ +# ADN DMR Parrot (playback) – systemd unit (PEER → ECHO on adn-server) +# +# Copy: +# sudo cp /opt/adn-server/examples/systemd/adn-parrot.service /etc/systemd/system/ +# Edit User / paths if needed, then: +# sudo systemctl daemon-reload +# sudo systemctl enable --now adn-parrot +# +# Minimal adn-parrot.yaml — MASTER_PORT / PASSPHRASE must match ECHO in adn-server.yaml. +# Logrotate: SIGUSR2 reopens log files (not SIGHUP). postrotate example: +# kill -USR2 $(systemctl show adn-parrot -p MainPID --value) +# Or: systemctl reload adn-parrot (ExecReload below sends USR2) + +[Unit] +Description=ADN DMR Parrot (playback) +After=network-online.target adn-server.service +Wants=network-online.target + +[Service] +User=adn +Type=simple +Restart=always +RestartSec=3 +SyslogIdentifier=adn-parrot +WorkingDirectory=/opt/adn-server +ExecStart=/opt/.pyenv/versions/3.11.8/bin/python3 /opt/adn-server/adn-server.py --parrot -c /opt/adn-server/adn-parrot.yaml +ExecReload=/bin/kill -USR2 $MAINPID +KillSignal=SIGTERM +TimeoutStopSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/examples/systemd/adn-server.service b/examples/systemd/adn-server.service new file mode 100644 index 0000000..d7cb059 --- /dev/null +++ b/examples/systemd/adn-server.service @@ -0,0 +1,31 @@ +# ADN DMR Peer Server – systemd unit (bridge, integrated PROXY, reports) +# +# Copy: +# sudo cp /opt/adn-server/examples/systemd/adn-server.service /etc/systemd/system/ +# Edit User / paths if needed, then: +# sudo systemctl daemon-reload +# sudo systemctl enable --now adn-server +# +# Config: adn-server.yaml (copy from adn-server.example.yaml; not committed). +# Reload YAML: systemctl reload adn-server (SIGHUP via ExecReload — not logrotate) +# Logrotate: kill -USR2 $(systemctl show adn-server -p MainPID --value) + +[Unit] +Description=ADN DMR Peer Server +After=network-online.target +Wants=network-online.target + +[Service] +User=adn +Type=simple +Restart=always +RestartSec=3 +SyslogIdentifier=adn-dmr-server +WorkingDirectory=/opt/adn-server +ExecStart=/opt/.pyenv/versions/3.11.8/bin/python3 /opt/adn-server/adn-server.py -c /opt/adn-server/adn-server.yaml +ExecReload=/bin/kill -HUP $MAINPID +KillSignal=SIGTERM +TimeoutStopSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/pyproject.toml b/pyproject.toml index b84af12..6a173a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,6 @@ markers = [ [tool.ruff.lint.per-file-ignores] # Entrypoints adjust sys.path before importing the package (intentional E402). "src/adn_server/main.py" = ["E402"] -"src/adn_server/parrot_main.py" = ["E402"] [project.scripts] adn-server = "adn_server.main:main" diff --git a/src/adn_server/infrastructure/config_normalizer.py b/src/adn_server/infrastructure/config_normalizer.py index 52dad17..46c819b 100644 --- a/src/adn_server/infrastructure/config_normalizer.py +++ b/src/adn_server/infrastructure/config_normalizer.py @@ -22,7 +22,7 @@ # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ############################################################################### -"""Shared config normalization: PEER, OBP, MASTER runtime state. Used by main.py and parrot_main.py.""" +"""Shared config normalization: PEER, OBP, MASTER runtime state. Used by main and parrot runtime.""" from __future__ import annotations diff --git a/src/adn_server/infrastructure/parrot/__init__.py b/src/adn_server/infrastructure/parrot/__init__.py new file mode 100644 index 0000000..5b194f8 --- /dev/null +++ b/src/adn_server/infrastructure/parrot/__init__.py @@ -0,0 +1,5 @@ +"""Integrated parrot (playback) runtime.""" + +from .runtime import run_parrot + +__all__ = ["run_parrot"] diff --git a/src/adn_server/infrastructure/parrot/runtime.py b/src/adn_server/infrastructure/parrot/runtime.py new file mode 100644 index 0000000..3187b71 --- /dev/null +++ b/src/adn_server/infrastructure/parrot/runtime.py @@ -0,0 +1,110 @@ +"""Wire parrot (playback) PEER systems at startup.""" + +from __future__ import annotations + +import logging +import signal +import sys +from typing import Any + +from twisted.internet import reactor, task + +from adn_server.application.playback_use_cases import PlaybackUseCases +from adn_server.infrastructure import reopen_file_handlers +from adn_server.infrastructure.bridge_router_impl import InMemoryBridgeRouter +from adn_server.infrastructure.config_normalizer import ( + ensure_system_runtime_config, + normalize_obp_config, + normalize_peer_config, +) +from adn_server.infrastructure.twisted_adapters.report_server import ReportServerFactory +from adn_server.infrastructure.twisted_adapters.udp_hbp import HBPProtocolFactory + + +def _looping_errback(logger_obj: logging.Logger, failure: Any) -> None: + logger_obj.error("(GLOBAL) Unhandled error in timed loop: %s", failure.getTraceback()) + + +def run_parrot(config: dict[str, Any], *, logger: logging.Logger) -> None: + """Start playback PEER(s) and run the Twisted reactor (blocks until shutdown).""" + ensure_system_runtime_config(config) + normalize_peer_config(config) + normalize_obp_config(config) + + g = config.setdefault("GLOBAL", {}) + sid = g.get("SERVER_ID", 0) + g["SERVER_ID"] = (int(sid) & 0xFFFFFFFF).to_bytes(4, "big") if not isinstance(sid, bytes) else sid + + protocols: dict[str, Any] = {} + router = InMemoryBridgeRouter() + report_factory = ReportServerFactory(config) + systems_cfg = config.get("SYSTEMS", {}) + report_factory.set_systems(systems_cfg) + + if config.get("REPORTS", {}).get("REPORT", False): + port = config["REPORTS"].get("REPORT_PORT", 4321) + reactor.listenTCP(port, report_factory) + logger.info("(REPORT) Report server listening on TCP %s", port) + + def reporting_loop() -> None: + report_factory.set_systems(config.get("SYSTEMS", {})) + report_factory.send_config() + + report_interval = config.get("REPORTS", {}).get("REPORT_INTERVAL", 60) + task.LoopingCall(reporting_loop).start(report_interval).addErrback(_looping_errback, logger) + + def sig_handler(sig: int, _frame: Any) -> None: + logger.info("SHUTDOWN: PARROT IS TERMINATING WITH SIGNAL %s", sig) + if reactor.running: + reactor.stop() + + def sigusr2_reopen_logs(_sig: int, _frame: Any) -> None: + n = reopen_file_handlers() + logger.info("(LOGGER) Reopened %s file log handler(s) after SIGUSR2", n) + + def sighup_ignore(_sig: int, _frame: Any) -> None: + logger.debug("(PARROT) SIGHUP ignored (no config hot-reload; use SIGUSR2 for logrotate)") + + signal.signal(signal.SIGTERM, sig_handler) + signal.signal(signal.SIGINT, sig_handler) + signal.signal(signal.SIGUSR2, sigusr2_reopen_logs) + if hasattr(signal, "SIGHUP"): + signal.signal(signal.SIGHUP, sighup_ignore) + + logger.info("ADN Parrot -- SYSTEM STARTING...") + started = 0 + for system_name, sys_cfg in systems_cfg.items(): + if not sys_cfg.get("ENABLED", True): + continue + if sys_cfg.get("MODE") != "PEER": + logger.debug("(PARROT) skip %s (MODE=%s; parrot only runs PEER systems)", system_name, sys_cfg.get("MODE")) + continue + + pb = PlaybackUseCases(system_name, get_protocol=lambda sn=system_name: protocols.get(sn)) + + protocol = HBPProtocolFactory( + system_name, + config, + report_factory, + router=router, + dmrd_received=pb.dmrd_received, + ) + protocols[system_name] = protocol + ip = sys_cfg.get("IP", "") + udp_port = sys_cfg.get("PORT", 56400) + reactor.listenUDP(udp_port, protocol, interface=ip or "0.0.0.0") + started += 1 + logger.info( + "(PARROT) %s PEER on %s:%s → master %s:%s", + system_name, + ip or "0.0.0.0", + udp_port, + sys_cfg.get("MASTER_IP", "?"), + sys_cfg.get("MASTER_PORT", "?"), + ) + + if started == 0: + logger.critical("(PARROT) no enabled PEER systems in config") + sys.exit("parrot config must define at least one enabled SYSTEMS. with MODE: PEER") + + reactor.run() diff --git a/src/adn_server/main.py b/src/adn_server/main.py index 96727d1..e712e06 100644 --- a/src/adn_server/main.py +++ b/src/adn_server/main.py @@ -26,7 +26,8 @@ ADN DMR Peer Server entrypoint. Run: python -m adn_server.main [-c adn-server.yaml] [--logging LEVEL] -Config default: adn-server.yaml at project root. + python -m adn_server.main --parrot [-c adn-parrot.yaml] +Config default: adn-server.yaml (or adn-parrot.yaml with --parrot). """ from __future__ import annotations @@ -82,6 +83,7 @@ from .infrastructure.config_normalizer import ( ) from .infrastructure.config_reload import BindSpec, reload_server_config from .application.proxy.deployment import is_proxy_inject_only, normalize_proxy_target, proxy_target_system +from .infrastructure.parrot import run_parrot from .infrastructure.proxy import apply_proxy_config_reload, start_proxy_service from .domain.dmr.bptc import encode_emblc from .infrastructure.persistence import PickleSubMapStore @@ -206,15 +208,26 @@ def main() -> None: from . import __version__ parser = argparse.ArgumentParser(description="ADN DMR Peer Server") - parser.add_argument("-c", "--config", dest="CONFIG_FILE", default=None, help="Path to adn-server.yaml") + parser.add_argument("-c", "--config", dest="CONFIG_FILE", default=None, help="Path to YAML config") parser.add_argument("--logging", dest="LOG_LEVEL", default=None, help="Override log level") + parser.add_argument( + "--parrot", + action="store_true", + help="Playback mode: run parrot PEER(s) from adn-parrot.yaml (default config)", + ) + parser.add_argument( + "--no-proxy", + action="store_true", + help="Disable integrated hotspot PROXY even when PROXY is set in config", + ) parser.add_argument("--version", action="version", version=f"adn-server {__version__}") args = parser.parse_args() project_root = os.path.dirname(os.path.abspath(__file__)) if project_root.endswith("/adn_server"): project_root = str(Path(project_root).parent.parent) - config_path = args.CONFIG_FILE or os.path.join(project_root, "adn-server.yaml") + default_config = "adn-parrot.yaml" if args.parrot else "adn-server.yaml" + config_path = args.CONFIG_FILE or os.path.join(project_root, default_config) loader = YamlConfigLoader(project_root) try: @@ -222,11 +235,13 @@ def main() -> None: except ConfigError as exc: print(f"(CONFIG) {exc}", file=sys.stderr) sys.exit(1) - _apply_talker_alias_defaults(config) + + if not args.parrot: + _apply_talker_alias_defaults(config) # Voice config lives in a separate file for hot-reload without restart voice_config_path = os.path.join(os.path.dirname(os.path.abspath(config_path)), "adn-voice.yaml") - voice_data = loader.load_voice_config(voice_config_path) + voice_data = loader.load_voice_config(voice_config_path) if not args.parrot else None if voice_data: config.setdefault("VOICE", {}).update(voice_data) @@ -241,6 +256,10 @@ def main() -> None: logger.info("\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Regents of the K0USY Group. All rights reserved.") logger.debug("\n\n(GLOBAL) Logging system started, anything from here on gets logged") + if args.parrot: + run_parrot(config, logger=logger) + return + # Aliases alias_loader = DefaultAliasLoader() peer_ids, subscriber_ids, talkgroup_ids, local_subscriber_ids, server_ids, checksums = ( @@ -567,6 +586,7 @@ def main() -> None: # UDP / proxy listeners (proxy_state declared before reload handler uses nonlocal) proxy_state = None + proxy_enabled = not args.no_proxy and proxy_target_system(config) is not None def _should_bind_udp(system_name: str, sys_cfg: dict[str, Any]) -> bool: return not is_proxy_inject_only(config, system_name) @@ -592,7 +612,7 @@ def main() -> None: if proxy_state is not None: apply_proxy_config_reload(proxy_state, config, logger=logger) _wire_proxy_report_slots(report_factory, proxy_state) - elif proxy_target_system(config): + elif proxy_enabled and proxy_target_system(config): proxy_state = start_proxy_service(config, protocols, logger=logger) _wire_proxy_report_slots(report_factory, proxy_state) else: @@ -685,7 +705,7 @@ def main() -> None: protocol, ) - if proxy_target_system(config): + if proxy_enabled: try: proxy_state = start_proxy_service(config, protocols, logger=logger) except Exception as exc: diff --git a/src/adn_server/parrot_main.py b/src/adn_server/parrot_main.py deleted file mode 100644 index 48f7a68..0000000 --- a/src/adn_server/parrot_main.py +++ /dev/null @@ -1,175 +0,0 @@ -# ADN DMR Peer Server - parrot (playback) entrypoint -# Copyright (C) 2026 Rodrigo Pérez, CE5RPY -# -# Derived from ADN DMR Server / FreeDMR / HBlink. Original license: -############################################################################### -# Copyright (C) 2020 Simon Adlem, G7RZU -# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software Foundation, -# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -############################################################################### - -""" -ADN DMR Parrot (playback) entrypoint. - -Exact port of legacy playback.py: record group voice, play back with new stream ID. -Uses the same YAML config as adn-server (only MASTER/PEER systems, no OPENBRIDGE). - - python adn-parrot.py - python adn-parrot.py -c adn-parrot.yaml - python adn-parrot.py --logging DEBUG -""" - -from __future__ import annotations - -import argparse -import logging -import os -import signal -import sys -from pathlib import Path -from typing import Any - -_ROOT = Path(__file__).resolve().parent.parent.parent -if str(_ROOT) not in sys.path: - sys.path.insert(0, str(_ROOT)) - -from twisted.internet import reactor, task - -from .application.playback_use_cases import PlaybackUseCases -from .domain.errors import ConfigError -from .infrastructure import YamlConfigLoader, reopen_file_handlers, setup_logging -from .infrastructure.bridge_router_impl import InMemoryBridgeRouter -from .infrastructure.config_normalizer import ( - ensure_system_runtime_config, - normalize_obp_config, - normalize_peer_config, -) -from .infrastructure.twisted_adapters.report_server import ReportServerFactory -from .infrastructure.twisted_adapters.udp_hbp import HBPProtocolFactory - - -def _looping_errback(logger_obj: logging.Logger, failure): - logger_obj.error("(GLOBAL) Unhandled error in timed loop: %s", failure.getTraceback()) - - -def main() -> None: - parser = argparse.ArgumentParser(description="ADN DMR Parrot (playback)") - parser.add_argument("-c", "--config", dest="CONFIG_FILE", default=None, help="Path to YAML config") - parser.add_argument("--logging", dest="LOG_LEVEL", default=None, help="Override log level") - args = parser.parse_args() - - project_root = os.path.dirname(os.path.abspath(__file__)) - if project_root.endswith("/adn_server"): - project_root = str(Path(project_root).parent.parent) - config_path = args.CONFIG_FILE or os.path.join(project_root, "adn-parrot.yaml") - - loader = YamlConfigLoader(project_root) - try: - config = loader.load(config_path) - except ConfigError as exc: - print(f"(CONFIG) {exc}", file=sys.stderr) - sys.exit(1) - - if args.LOG_LEVEL: - config.setdefault("LOGGER", {})["LOG_LEVEL"] = args.LOG_LEVEL - logger = setup_logging(config.get("LOGGER", {})) - logger.info("\n\nCopyright (c) 2026 Rodrigo Pérez, CE5RPY ce5rpy@qmd.cl") - logger.info("\n\nCopyright (c) 2026 Joaquin Madrid Belando, EA5GVK ea5gvk@gmail.com") - logger.info("\nCopyright (c) 2024-2026 Esteban Mackay, HP3ICC setcom40@gmail.com") - logger.info("\nCopyright (c) 2020-2023 Simon Adlem, G7RZU g7rzu@gb7fr.org.uk") - logger.info("\nCopyright (c) 2016-2019 Cortney T. Buffington, N0MJS n0mjs@me.com") - logger.info("\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Regents of the K0USY Group. All rights reserved.") - logger.debug("\n\n(GLOBAL) Logging system started, anything from here on gets logged") - - ensure_system_runtime_config(config) - normalize_peer_config(config) - normalize_obp_config(config) - - g = config.setdefault("GLOBAL", {}) - sid = g.get("SERVER_ID", 0) - g["SERVER_ID"] = (int(sid) & 0xFFFFFFFF).to_bytes(4, "big") if not isinstance(sid, bytes) else sid - - protocols: dict[str, Any] = {} - router = InMemoryBridgeRouter() - report_factory = ReportServerFactory(config) - systems_cfg = config.get("SYSTEMS", {}) - report_factory.set_systems(systems_cfg) - - if config.get("REPORTS", {}).get("REPORT", False): - port = config["REPORTS"].get("REPORT_PORT", 4321) - reactor.listenTCP(port, report_factory) - logger.info("(REPORT) Report server listening on TCP %s", port) - - def reporting_loop(): - report_factory.set_systems(config.get("SYSTEMS", {})) - report_factory.send_config() - - report_interval = config.get("REPORTS", {}).get("REPORT_INTERVAL", 60) - task.LoopingCall(reporting_loop).start(report_interval).addErrback(_looping_errback, logger) - - playback_instances: dict[str, PlaybackUseCases] = {} - - def sig_handler(sig, frame): - logger.info("SHUTDOWN: PARROT IS TERMINATING WITH SIGNAL %s", sig) - if reactor.running: - reactor.stop() - - def sigusr2_reopen_logs(_sig, _frame): - """Logrotate: reopen file log handlers (does not reload config).""" - n = reopen_file_handlers() - logger.info("(LOGGER) Reopened %s file log handler(s) after SIGUSR2", n) - - signal.signal(signal.SIGTERM, sig_handler) - signal.signal(signal.SIGINT, sig_handler) - signal.signal(signal.SIGUSR2, sigusr2_reopen_logs) - - logger.info("ADN Parrot -- SYSTEM STARTING...") - for system_name, sys_cfg in systems_cfg.items(): - if not sys_cfg.get("ENABLED", True): - continue - if sys_cfg.get("MODE") == "OPENBRIDGE": - logger.critical( - "%s FATAL: Instance is mode 'OPENBRIDGE', which would be tragic for playback. " - "playback only works with MMDVM-based systems", - system_name, - ) - sys.exit( - "playback cannot function with OPENBRIDGE systems. System {} is configured as OPENBRIDGE".format( - system_name - ) - ) - - pb = PlaybackUseCases(system_name, get_protocol=lambda sn=system_name: protocols.get(sn)) - playback_instances[system_name] = pb - - protocol = HBPProtocolFactory( - system_name, - config, - report_factory, - router=router, - dmrd_received=pb.dmrd_received, - ) - protocols[system_name] = protocol - ip = sys_cfg.get("IP", "") - udp_port = sys_cfg.get("PORT", 56400) - reactor.listenUDP(udp_port, protocol, interface=ip or "0.0.0.0") - logger.debug("%s instance created: %s, %s", sys_cfg.get("MODE", "?"), system_name, protocol) - - reactor.run() - - -if __name__ == "__main__": - main() diff --git a/tests/infrastructure/test_parrot_cli.py b/tests/infrastructure/test_parrot_cli.py new file mode 100644 index 0000000..b306a53 --- /dev/null +++ b/tests/infrastructure/test_parrot_cli.py @@ -0,0 +1,122 @@ +"""CLI and integrated parrot entry (Phase 4).""" + +from __future__ import annotations + +import sys +from unittest.mock import patch + +import pytest + +from adn_server.main import main + + +def test_parrot_flag_routes_to_run_parrot() -> None: + with ( + patch("adn_server.main.run_parrot") as mock_run, + patch("adn_server.main.YamlConfigLoader") as mock_loader_cls, + patch("adn_server.main.setup_logging") as mock_log, + ): + mock_loader_cls.return_value.load.return_value = {"GLOBAL": {"SERVER_ID": 9990}, "LOGGER": {}} + mock_log.return_value = _FakeLogger() + with patch.object(sys, "argv", ["adn-server", "--parrot", "-c", "/tmp/adn-parrot.yaml"]): + main() + mock_run.assert_called_once() + + +def test_no_proxy_skips_proxy_startup(monkeypatch: pytest.MonkeyPatch) -> None: + """--no-proxy must not call start_proxy_service at bridge startup.""" + import adn_server.main as main_mod + + calls: list[str] = [] + + def _track(*_a, **_k): + calls.append("proxy") + raise AssertionError("proxy should not start") + + monkeypatch.setattr(main_mod, "start_proxy_service", _track) + monkeypatch.setattr(main_mod, "run_parrot", lambda *_a, **_k: None) + monkeypatch.setattr(main_mod.reactor, "run", lambda: None) + monkeypatch.setattr(main_mod, "ReportServerFactory", lambda *a, **k: _FakeReportFactory()) + monkeypatch.setattr(main_mod, "create_report_mqtt_publisher", lambda *_: None) + monkeypatch.setattr(main_mod, "start_report_queue_worker", lambda *_a, **_k: None) + monkeypatch.setattr(main_mod, "DefaultAliasLoader", _FakeAliasLoader) + monkeypatch.setattr(main_mod, "PickleSubMapStore", _FakeSubMapStore) + monkeypatch.setattr(main_mod, "JsonKeysStore", lambda *_: None) + monkeypatch.setattr(main_mod, "DefaultSecurityDownloader", lambda *_: None) + monkeypatch.setattr(main_mod, "UserPasswordsLoader", lambda *_: _FakeUserPw()) + monkeypatch.setattr(main_mod, "DefaultVoiceProvider", lambda *_: None) + monkeypatch.setattr(main_mod, "RecordingHandler", lambda *_: None) + monkeypatch.setattr(main_mod, "IdentUseCases", lambda *_: _FakeIdent()) + monkeypatch.setattr(main_mod, "HBPProtocolFactory", lambda *a, **k: object()) + + config = { + "GLOBAL": {"SERVER_ID": 1}, + "LOGGER": {}, + "ALIASES": {"PATH": "."}, + "REPORTS": {"REPORT": False}, + "PROXY": {"LISTEN_PORT": 62031, "TARGET_SYSTEM": "SYSTEM"}, + "SYSTEMS": { + "SYSTEM": {"MODE": "MASTER", "ENABLED": True, "IP": "127.0.0.1", "PORT": 62030, "MAX_PEERS": 4}, + }, + } + + with patch("adn_server.main.YamlConfigLoader") as mock_loader_cls: + loader = mock_loader_cls.return_value + loader.load.return_value = config + loader.load_voice_config.return_value = None + with patch("adn_server.main.setup_logging") as mock_log: + mock_log.return_value = _FakeLogger() + with patch.object(sys, "argv", ["adn-server", "--no-proxy", "-c", "/tmp/adn-server.yaml"]): + try: + main() + except Exception: + pass + assert calls == [] + + +class _FakeLogger: + def info(self, *_a, **_k): + pass + + def debug(self, *_a, **_k): + pass + + def error(self, *_a, **_k): + pass + + def warning(self, *_a, **_k): + pass + + +class _FakeReportFactory: + def set_systems(self, *_a, **_k): + pass + + def set_bridges(self, *_a, **_k): + pass + + def set_config(self, *_a, **_k): + pass + + +class _FakeAliasLoader: + def load_aliases(self, *_a, **_k): + return ({}, {}, {}, {}, {}, {}) + + def load_subscriber_profiles(self, *_a, **_k): + return {} + + +class _FakeSubMapStore: + def load(self, *_a, **_k): + return {} + + +class _FakeUserPw: + def load(self, *_a, **_k): + pass + + +class _FakeIdent: + def run_ident(self): + pass diff --git a/tests/infrastructure/test_parrot_config.py b/tests/infrastructure/test_parrot_config.py new file mode 100644 index 0000000..27881f4 --- /dev/null +++ b/tests/infrastructure/test_parrot_config.py @@ -0,0 +1,34 @@ +"""Minimal adn-parrot.yaml validation.""" + +from __future__ import annotations + +from adn_server.infrastructure.config_validator import validate_config + + +MINIMAL_PARROT = { + "GLOBAL": {"SERVER_ID": 9990}, + "LOGGER": {"LOG_FILE": "/var/log/adn-server/parrot.log"}, + "SYSTEMS": { + "PARROT": { + "MODE": "PEER", + "IP": "127.0.0.1", + "PORT": 54915, + "MASTER_IP": "127.0.0.1", + "MASTER_PORT": 54917, + "PASSPHRASE": "secret", + "RADIO_ID": 9990, + "CALLSIGN": "ECHO", + "OPTIONS": "TS2=9990;", + }, + }, +} + + +def test_minimal_parrot_config_validates_without_proxy() -> None: + validate_config(MINIMAL_PARROT) + + +def test_minimal_parrot_has_no_reports_or_aliases() -> None: + assert "REPORTS" not in MINIMAL_PARROT + assert "ALIASES" not in MINIMAL_PARROT + assert "PROXY" not in MINIMAL_PARROT