diff --git a/adn-server.example.yaml b/adn-server.example.yaml index 18f7c79..6c3fc39 100644 --- a/adn-server.example.yaml +++ b/adn-server.example.yaml @@ -143,6 +143,8 @@ SYSTEMS: OVERRIDE_IDENT_TG: "" # Bridge loop echoes entering here: log (default) only logs them, true drops them, false skips the check LOOP_GUARD: log + # Answer a hotspot's TG / ID 4000 with "not linked" (to that hotspot only) + TG4000_VOICE: false D-APRS: MODE: MASTER diff --git a/docs/en/server/user-guide/configuration.md b/docs/en/server/user-guide/configuration.md index 447108b..ac109a4 100644 --- a/docs/en/server/user-guide/configuration.md +++ b/docs/en/server/user-guide/configuration.md @@ -106,6 +106,7 @@ These appear mainly on **MASTER** (and often on **PEER**). OpenBridge uses a dif | **ANNOUNCEMENT_LANGUAGE** | Default language folder under `Audio//` for prompts on this system. | | **ALLOW_UNREG_ID** | Whether unregistered subscriber IDs are allowed (MASTER). | | **SUB_MAP_LEARN** | Default `true`. With `false`, traffic entering through this system never updates **SUB_MAP**, so it never becomes where a subscriber is reached for private calls and unit data. For service systems that transmit with someone else's ID or a shared service ID: beacons, ASL / EchoLink / DVSwitch bridges, the **ECHO** parrot. MASTER and PEER only; rejected on OPENBRIDGE. See [Private calls](private-calls.md#service-systems-sub_map_learn). | +| **TG4000_VOICE** | Default `false`. With `true`, a hotspot keying **TG / ID 4000** on this MASTER hears back the link status ("not linked", or "linked to *N*" with a `DEFAULT_REFLECTOR`) on that slot, and only that hotspot hears it. MASTER only. See [Special numbers](special-numbers.md#tg--id-4000--deactivate-dynamic-bridges). | | **LOOP_GUARD** | `log` (default), `true` or `false`. Loop guard for voice that comes back through a transcoding bridge (YSF2DMR, DVSwitch, ASL/EchoLink gateways): the same caller on the same TG from another ingress, while the original over is active or within `GLOBAL.LOOP_GUARD_HOLD`. `log` writes one `*LoopGuard*` line per echo and lets it through; `true` drops it; `false` neither checks nor records streams entering this system. The **ECHO** parrot replays each over with the caller's ID 2.0 s after it ends, beyond the hold, so it is never matched; `false` is an extra option for it. Applies to OPENBRIDGE too, where all links count as one ingress (the mesh). See [Loop guard](../development/behaviour-and-timers.md#loop-guard). | --- diff --git a/docs/en/server/user-guide/special-numbers.md b/docs/en/server/user-guide/special-numbers.md index 5d9725c..a243721 100644 --- a/docs/en/server/user-guide/special-numbers.md +++ b/docs/en/server/user-guide/special-numbers.md @@ -75,6 +75,8 @@ In-band bridge activation/deactivation is applied on **voice terminator (VTERM)* **TG 4000 must never appear** as a dynamic UA chip on the monitor or in `peer_dynamic_tgs`. +**Voice reply (`TG4000_VOICE: true` on the MASTER):** when the 4000 over ends (its terminator), the server answers **that hotspot only** about a second later with the link status in the system's `ANNOUNCEMENT_LANGUAGE`: "not linked", or "linked to *N*" with a `DEFAULT_REFLECTOR`. It is a group call from the server voice ID to **TG 4000** on the slot the 4000 came in on, so the radio hears it on the contact it just used. Other hotspots on a shared MASTER do not hear it, it never goes to OpenBridge, and it stops if that hotspot starts receiving another stream on the slot. One reply per over; none if the terminator is lost. + ### `SINGLE_MODE` impact on in-band deactivation When in-band rules evaluate deactivation on a MASTER slot: diff --git a/docs/es/server/user-guide/configuration.md b/docs/es/server/user-guide/configuration.md index 236c87d..b3fdfea 100644 --- a/docs/es/server/user-guide/configuration.md +++ b/docs/es/server/user-guide/configuration.md @@ -106,6 +106,7 @@ Aparecen principalmente en **MASTER** (y a menudo en **PEER**). OpenBridge usa u | **ANNOUNCEMENT_LANGUAGE** | Carpeta de idioma por defecto bajo `Audio//` para mensajes en este sistema. | | **ALLOW_UNREG_ID** | Si se permiten IDs de suscriptor no registrados (MASTER). | | **SUB_MAP_LEARN** | Por defecto `true`. Con `false`, el tráfico que entra por este sistema nunca actualiza **SUB_MAP**, así que nunca pasa a ser donde se localiza a un suscriptor para llamadas privadas y datos unitarios. Para sistemas de servicio que transmiten con el ID de otra persona o con un ID de servicio compartido: balizas, puentes ASL / EchoLink / DVSwitch, el loro **ECHO**. Solo MASTER y PEER; en OPENBRIDGE se rechaza. Ver [Llamadas privadas](private-calls.md#service-systems-sub_map_learn). | +| **TG4000_VOICE** | Por defecto `false`. Con `true`, el hotspot que pulsa **TG / ID 4000** en este MASTER oye de vuelta el estado de enlace («no enlazado», o «enlazado a *N*» si hay `DEFAULT_REFLECTOR`) por ese slot, y solo lo oye ese hotspot. Solo MASTER. Ver [Números especiales](special-numbers.md#tg--id-4000--desactivar-bridges-dinamicos). | | **LOOP_GUARD** | `log` (por defecto), `true` o `false`. Protección contra bucles de la voz que vuelve por un puente que transcodifica (YSF2DMR, DVSwitch, pasarelas ASL/EchoLink): la misma persona en el mismo TG desde otra entrada mientras su pasada original sigue activa o dentro de `GLOBAL.LOOP_GUARD_HOLD`. `log` escribe una línea `*LoopGuard*` por eco y lo deja pasar; `true` lo descarta; `false` ni comprueba ni registra los streams que entran por este sistema. El loro **ECHO** repite cada pasada con el ID de quien llama 2,0 s después, fuera de la ventana, así que nunca se detecta; `false` es una opción extra para él. También se aplica a OPENBRIDGE, donde todos los enlaces cuentan como una sola entrada (la malla). Ver [Loop guard](../development/behaviour-and-timers.md#loop-guard). | --- diff --git a/docs/es/server/user-guide/special-numbers.md b/docs/es/server/user-guide/special-numbers.md index 632dd11..f444d92 100644 --- a/docs/es/server/user-guide/special-numbers.md +++ b/docs/es/server/user-guide/special-numbers.md @@ -75,6 +75,8 @@ La activación/desactivación in-band de bridges se aplica sobre **voice termina **TG 4000 no debe aparecer** como chip UA dinámico en el monitor ni en `peer_dynamic_tgs`. +**Respuesta de voz (`TG4000_VOICE: true` en el MASTER):** al terminar la pasada al 4000 (su terminador), el servidor responde **solo a ese hotspot**, alrededor de un segundo después, con el estado de enlace en el `ANNOUNCEMENT_LANGUAGE` del sistema: «no enlazado», o «enlazado a *N*» si hay `DEFAULT_REFLECTOR`. Es una llamada de grupo del ID de voz del servidor al **TG 4000** por el mismo slot del 4000, así que la radio la oye en el contacto que acaba de usar. Los demás hotspots de un MASTER compartido no la oyen, nunca sale por OpenBridge y se corta si ese hotspot empieza a recibir otro stream por ese slot. Una respuesta por pasada; ninguna si se pierde el terminador. + ### Impacto de `SINGLE_MODE` en la lógica de desactivación Cuando las reglas in-band evalúan desactivación en un slot MASTER: diff --git a/src/adn_server/application/voice_use_cases.py b/src/adn_server/application/voice_use_cases.py index 9866f52..f69515a 100644 --- a/src/adn_server/application/voice_use_cases.py +++ b/src/adn_server/application/voice_use_cases.py @@ -31,7 +31,7 @@ import time from dataclasses import dataclass from typing import Any, Callable -from ..domain import HBPF_SLT_VHEAD, HBPF_SLT_VTERM, bytes_3, bytes_4 +from ..domain import HBPF_SLT_VHEAD, HBPF_SLT_VTERM, bytes_3, bytes_4, int_id from .ports import VoiceProvider from .routing.helpers import slot_voice_held_by_other_stream from .server_voice import server_voice_rf_src_bytes @@ -167,22 +167,16 @@ class VoiceUseCases: _pkt_count = self.play_on_slot(protocol, system, speech, _source_id, bytes_3(9)) logger.info("(%s) On-demand playback complete: %s (%d packets)", system, file_number, _pkt_count) - def disconnected_voice(self, system: str) -> None: - """Send 'disconnected' / 'linked to reflector' voice (legacy disconnectedVoice). Run from thread.""" - if not self._get_protocols or not self._call_from_reactor or not self._audio_path: - return - protocol = self._get_protocols().get(system) - if not protocol or not getattr(protocol, "STATUS", None): - return - sys_cfg = self._config.get("SYSTEMS", {}).get(system, {}) + def _link_status_words(self, sys_cfg: dict[str, Any]) -> list[Any] | None: + """"not linked", or "linked to ", in the system's language; None without audio.""" _lang = sys_cfg.get("ANNOUNCEMENT_LANGUAGE", "en_GB") words_by_lang = self.get_ambe_words(_lang, self._audio_path) if _lang not in words_by_lang: - return + return None words = words_by_lang[_lang] silence = words.get("silence") if not silence: - return + return None _say = [silence, silence] default_refl = int(sys_cfg.get("DEFAULT_REFLECTOR", 0)) if default_refl > 0: @@ -198,6 +192,18 @@ class VoiceUseCases: else: _say.append(words.get("notlinked") or silence) _say.append(silence) + return _say + + def disconnected_voice(self, system: str) -> None: + """Send 'disconnected' / 'linked to reflector' voice (legacy disconnectedVoice). Run from thread.""" + if not self._get_protocols or not self._call_from_reactor or not self._audio_path: + return + protocol = self._get_protocols().get(system) + if not protocol or not getattr(protocol, "STATUS", None): + return + _say = self._link_status_words(self._config.get("SYSTEMS", {}).get(system, {})) + if _say is None: + return _source_id = self._server_source_id() speech = self.pkt_gen(_source_id, bytes_3(9), bytes_4(9), 1, _say) time.sleep(1) @@ -206,3 +212,47 @@ class VoiceUseCases: logger.debug("(%s) Sending disconnected voice", system) self.play_on_slot(protocol, system, speech, _source_id, bytes_3(9)) logger.debug("(%s) disconnected voice thread end", system) + + def tg4000_voice(self, system: str, peer_id: bytes, slot: int) -> int: + """Answer a hotspot's TG/ID 4000 with the link status, to that hotspot only. Run from thread. + + A group call from the server voice ID to TG 4000 on the slot the 4000 came in on: the + radio is still on that contact. Sent a second after the over ends, frame by frame on + the reactor through ``send_prompt_to_peer``, so it stops if the hotspot gets busy on + that slot or leaves. Returns the frames sent. + """ + if not self._get_protocols or not self._call_from_reactor or not self._audio_path: + return 0 + protocol = self._get_protocols().get(system) + if protocol is None or not hasattr(protocol, "send_prompt_to_peer"): + return 0 + _say = self._link_status_words(self._config.get("SYSTEMS", {}).get(system, {})) + if _say is None: + return 0 + _source_id = self._server_source_id() + speech = self.pkt_gen(_source_id, bytes_3(4000), bytes_4(9), 1 if int(slot) == 2 else 0, _say) + time.sleep(1) + run = _PromptRun() + _next_time = time.time() + for pkt in speech: + if run.stopped: + break + _next_time += _FRAME_INTERVAL + delay = _next_time - time.time() + if delay > 0.001: + time.sleep(delay) + self._call_from_reactor(self._peer_prompt_frame, protocol, peer_id, pkt, run) + logger.info( + "(%s) TG 4000 voice reply to peer %s on TS %s: %d frames", system, int_id(peer_id), slot, run.sent, + ) + return run.sent + + @staticmethod + def _peer_prompt_frame(protocol: Any, peer_id: bytes, pkt: bytes, run: _PromptRun) -> None: + """Reactor side of ``tg4000_voice``: one frame, or stop when the hotspot refuses it.""" + if run.stopped: + return + if protocol.send_prompt_to_peer(peer_id, pkt): + run.sent += 1 + else: + run.stopped = True diff --git a/src/adn_server/infrastructure/bootstrap/peer_server.py b/src/adn_server/infrastructure/bootstrap/peer_server.py index c2389a7..d56802a 100644 --- a/src/adn_server/infrastructure/bootstrap/peer_server.py +++ b/src/adn_server/infrastructure/bootstrap/peer_server.py @@ -698,6 +698,7 @@ def run_peer_server( dmrd_received=routing_use_cases.dmrd_received, get_user_password_callback=user_passwords_loader.get_user_password, on_play_file_request=voice_use_cases.play_file_on_request, + on_tg4000_voice=voice_use_cases.tg4000_voice, on_handle_recording=recording_handler.handle_recording, on_in_band_signalling=routing_use_cases.apply_in_band_signalling, on_options_received=routing_use_cases.options_config_for_system, diff --git a/src/adn_server/infrastructure/config_validator.py b/src/adn_server/infrastructure/config_validator.py index a5c929a..435a9ec 100644 --- a/src/adn_server/infrastructure/config_validator.py +++ b/src/adn_server/infrastructure/config_validator.py @@ -381,7 +381,7 @@ def _validate_system(name: str, sys_cfg: dict[str, Any], errors: list[str]) -> N mode = sys_cfg.get("MODE") if mode is not None and not _is_empty(mode) and not isinstance(mode, str): errors.append(f"{prefix}.MODE: expected string, got {type(mode).__name__} ({mode!r}).") - for key in ("ENABLED", "REPEAT", "USE_ACL", "SINGLE_MODE", "VOICE_IDENT", "ALLOW_UNREG_ID", "PROXY_CONTROL", "EXPORT_AMBE", "LOOSE", "RELAX_CHECKS", "ENHANCED_OBP", "BOTH_SLOTS", "SUB_MAP_LEARN"): + for key in ("ENABLED", "REPEAT", "USE_ACL", "SINGLE_MODE", "VOICE_IDENT", "ALLOW_UNREG_ID", "PROXY_CONTROL", "EXPORT_AMBE", "LOOSE", "RELAX_CHECKS", "ENHANCED_OBP", "BOTH_SLOTS", "SUB_MAP_LEARN", "TG4000_VOICE"): if key in sys_cfg: _expect_bool(f"{prefix}.{key}", sys_cfg[key], errors) # OpenBridge always learns SUB_MAP: whoever is behind the link must stay reachable. @@ -390,6 +390,8 @@ def _validate_system(name: str, sys_cfg: dict[str, Any], errors: list[str]) -> N f"{prefix}.SUB_MAP_LEARN: not supported on OPENBRIDGE (an OpenBridge link always " "updates SUB_MAP); remove it." ) + if mode not in (None, "MASTER") and "TG4000_VOICE" in sys_cfg: + errors.append(f"{prefix}.TG4000_VOICE: only on MASTER (it answers its hotspots); remove it.") if "LOOP_GUARD" in sys_cfg and not ( isinstance(sys_cfg["LOOP_GUARD"], bool) or sys_cfg["LOOP_GUARD"] == "log" ): diff --git a/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py b/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py index a0b11ce..4b91851 100644 --- a/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py +++ b/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py @@ -231,6 +231,7 @@ class HBPProtocol(DatagramProtocol): dmrd_received: Callable[..., None] | None = None, get_user_password_callback: Callable[[int], bytes | None] | None = None, on_play_file_request: Callable[[str, str], None] | None = None, + on_tg4000_voice: Callable[[str, bytes, int], None] | None = None, on_handle_recording: Callable[..., None] | None = None, on_in_band_signalling: Callable[[str, int, bytes, float], None] | None = None, on_options_received: Callable[..., None] | None = None, @@ -255,6 +256,8 @@ class HBPProtocol(DatagramProtocol): self._dmrd_received = dmrd_received self._get_user_password = get_user_password_callback if get_user_password_callback is not None else get_user_password self._on_play_file_request = on_play_file_request + self._on_tg4000_voice = on_tg4000_voice + self._tg4000_answered: dict[bytes, float] = {} # stream ID -> time: one voice reply per over self._on_handle_recording = on_handle_recording self._on_in_band_signalling = on_in_band_signalling self._on_options_received = on_options_received @@ -679,13 +682,29 @@ class HBPProtocol(DatagramProtocol): rf_src: bytes, stream_id: bytes, ) -> bool: - """Legacy early return for TG/ID 4000; reset once per PTT on voice header only.""" + """Legacy early return for TG/ID 4000; reset once per PTT on voice header only. + + With ``TG4000_VOICE`` the terminator of the over also queues one voice reply to this + hotspot (``VoiceUseCases.tg4000_voice``). + """ if int_dst_id != 4000: return False if tg4000_reset_on_vhead(int_dst_id, frame_type, dtype_vseq): self._apply_tg4000_reset( peer_id, slot, call_type, rf_src=rf_src, stream_id=stream_id, ) + elif ( + frame_type == HBPF_DATA_SYNC + and dtype_vseq == HBPF_SLT_VTERM + and self._on_tg4000_voice is not None + and self._config.get("TG4000_VOICE") is True + and stream_id not in self._tg4000_answered + ): + now = time.time() + for sid in [k for k, t in self._tg4000_answered.items() if now - t > 60]: + del self._tg4000_answered[sid] + self._tg4000_answered[stream_id] = now + reactor.callInThread(self._on_tg4000_voice, self._system, peer_id, slot) return True def purge_peer_dynamic_tgs(self, peer_id: bytes) -> bool: @@ -895,6 +914,26 @@ class HBPProtocol(DatagramProtocol): ) self.transport.write(_packet, self._peers[_peer]["SOCKADDR"]) + def send_prompt_to_peer(self, peer_id: bytes, packet: bytes) -> bool: + """One frame of a server prompt for one hotspot only (the TG 4000 voice reply). + + The hotspot did not subscribe to the prompt's TG, so the OPTIONS filter does not + apply; its own slot gate does: False (frame not sent) when it is busy with another + stream on that slot or no longer connected. The MASTER slot rows are not touched, + so nobody else on a shared MASTER is held off. + """ + peer = self._peers.get(peer_id) + if not isinstance(peer, dict) or peer.get("CONNECTION") != "YES": + return False + packet = b"".join([packet[:11], peer_id, packet[15:]]) + ctx = self._downlink_ctx() + if not peer_accepts_group_dmrd_packet(ctx, peer_id, peer, packet, routed=True): + return False + route = parse_dmrd_route_fields(packet) + track_peer_group_dmrd(ctx, peer_id, packet, peer, from_ingress=False, voice_slot=route[0] if route else None) + self.transport.write(packet, peer["SOCKADDR"]) + return True + def _ta_buffer_enabled(self) -> bool: return self._config.get("MODE") in ("MASTER", "OPENBRIDGE") @@ -2566,6 +2605,7 @@ def HBPProtocolFactory( dmrd_received: Callable[..., None] | None = None, get_user_password_callback: Callable[[int], bytes | None] | None = None, on_play_file_request: Callable[[str, str], None] | None = None, + on_tg4000_voice: Callable[[str, bytes, int], None] | None = None, on_handle_recording: Callable[..., None] | None = None, on_in_band_signalling: Callable[[str, int, bytes, float], None] | None = None, on_options_received: Callable[..., None] | None = None, @@ -2590,6 +2630,7 @@ def HBPProtocolFactory( dmrd_received, get_user_password_callback=get_user_password_callback, on_play_file_request=on_play_file_request, + on_tg4000_voice=on_tg4000_voice, on_handle_recording=on_handle_recording, on_in_band_signalling=on_in_band_signalling, on_options_received=on_options_received, diff --git a/tests/infrastructure/test_config_validator.py b/tests/infrastructure/test_config_validator.py index 2417ef2..8032409 100644 --- a/tests/infrastructure/test_config_validator.py +++ b/tests/infrastructure/test_config_validator.py @@ -137,3 +137,27 @@ def test_rejects_bad_loop_guard_hold(hold) -> None: with pytest.raises(ConfigError) as exc: validate_config(_minimal_config(LOOP_GUARD_HOLD=hold)) assert "GLOBAL.LOOP_GUARD_HOLD" in str(exc.value) + + +def test_accepts_tg4000_voice_bool_on_master() -> None: + config = _minimal_config() + config["SYSTEMS"] = {"SYSTEM": {"MODE": "MASTER", "TG4000_VOICE": True}} + config["PROXY"] = {"TARGET_SYSTEM": "SYSTEM", "LISTEN_PORT": 62031} + config["DATABASE"] = {"DB_NAME": "x", "DB_USERNAME": "x"} + validate_config(config) + + +def test_rejects_non_bool_tg4000_voice() -> None: + config = _minimal_config() + config["SYSTEMS"] = {"SYSTEM": {"MODE": "MASTER", "TG4000_VOICE": "yes"}} + with pytest.raises(ConfigError) as exc: + validate_config(config) + assert "SYSTEMS.SYSTEM.TG4000_VOICE: expected boolean" in str(exc.value) + + +def test_rejects_tg4000_voice_outside_a_master() -> None: + config = _minimal_config() + config["SYSTEMS"] = {"BRIDGE": {"MODE": "PEER", "TG4000_VOICE": True}} + with pytest.raises(ConfigError) as exc: + validate_config(config) + assert "SYSTEMS.BRIDGE.TG4000_VOICE: only on MASTER" in str(exc.value) diff --git a/tests/voice/test_tg4000_voice_reply.py b/tests/voice/test_tg4000_voice_reply.py new file mode 100644 index 0000000..bbc8b91 --- /dev/null +++ b/tests/voice/test_tg4000_voice_reply.py @@ -0,0 +1,158 @@ +# ADN DMR Peer Server - tests voice TG 4000 voice reply +# +# Copyright (C) 2026 Rodrigo Pérez, CE5RPY +# +############################################################################### +# 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 +############################################################################### + +"""TG4000_VOICE: a hotspot's TG/ID 4000 is answered with the link status, to that hotspot only.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import Any +from unittest.mock import MagicMock, patch + +from tests.harness.deterministic import PacketSpec +from tests.harness.voice_helpers import FakeVoiceProvider +from tests.support.hbp_repeat_stack import HbpRepeatStack, build_hbp_repeat_stack + +from adn_server.application.voice_use_cases import VoiceUseCases +from adn_server.domain import bytes_3, bytes_4 + +_A = (213003507).to_bytes(4, "big") +_B = (213003591).to_bytes(4, "big") +_ADDR_A = ("10.0.0.7", 62031) +_ADDR_B = ("10.0.0.8", 62031) +_SYSTEM = "MASTER-A" + + +def _stack(*, voice: bool | None = True) -> tuple[HbpRepeatStack, MagicMock]: + stack = build_hbp_repeat_stack(talker_alias=False, system_name=_SYSTEM) + stack.config["PROXY"] = {"TARGET_SYSTEM": _SYSTEM} # the shared MASTER + if voice is not None: + stack.hbp._config["TG4000_VOICE"] = voice + reply = MagicMock() + stack.hbp._on_tg4000_voice = reply + stack.hbp._dynamic_tg_uc = MagicMock() + stack.register_peer(_A, _ADDR_A) + stack.register_peer(_B, _ADDR_B) + return stack, reply + + +def _frame(dtype_vseq: int, *, slot: int = 2, stream: int = 0x40004000, dst: int = 4000, + src: int = 2130035, peer: bytes = _A, call_type: str = "group") -> bytes: + return replace( + PacketSpec(dst_id=dst, slot=slot, stream_id=stream, call_type=call_type, + peer_id=int.from_bytes(peer, "big"), rf_src=src), + frame_type=2, dtype_vseq=dtype_vseq, + ).data() + + +def _over_4000(stack: HbpRepeatStack, **kw: Any) -> None: + with patch("adn_server.infrastructure.twisted_adapters.udp_hbp.reactor.callInThread", + side_effect=lambda fn, *a: fn(*a)): + stack.hbp._master_datagram_received(_frame(1, **kw), _ADDR_A) # voice header + stack.hbp._master_datagram_received(_frame(2, **kw), _ADDR_A) # terminator + stack.hbp._master_datagram_received(_frame(2, **kw), _ADDR_A) # repeated terminator + + +def test_the_terminator_of_a_4000_over_queues_one_reply_to_that_hotspot() -> None: + stack, reply = _stack() + _over_4000(stack, slot=1) + reply.assert_called_once_with(_SYSTEM, _A, 1) + + +def test_a_private_call_to_4000_is_answered_too() -> None: + stack, reply = _stack() + _over_4000(stack, call_type="unit") + reply.assert_called_once_with(_SYSTEM, _A, 2) + + +def test_no_reply_unless_the_system_asks_for_it() -> None: + for voice in (None, False): + stack, reply = _stack(voice=voice) + _over_4000(stack) + reply.assert_not_called() + + +def test_a_prompt_frame_reaches_only_its_hotspot() -> None: + stack, _ = _stack() + pkt = _frame(1, dst=4000, src=1000001, peer=bytes_4(9), stream=0x0A0A0A0A) + assert stack.hbp.send_prompt_to_peer(_A, pkt) + sent = stack.transport.sent + assert [addr for _p, addr in sent] == [_ADDR_A] + assert sent[0][0][11:15] == _A # addressed to that hotspot + + +def test_a_prompt_frame_is_refused_while_the_hotspot_hears_another_stream() -> None: + stack, _ = _stack() + assert stack.hbp.send_prompt_to_peer(_A, _frame(1, dst=3340, src=3340062, stream=0x01010101)) + assert not stack.hbp.send_prompt_to_peer(_A, _frame(1, dst=4000, src=1000001, stream=0x0A0A0A0A)) + assert stack.hbp.send_prompt_to_peer(_B, _frame(1, dst=4000, src=1000001, stream=0x0A0A0A0A)) # B is free + + +def test_a_prompt_frame_for_a_hotspot_that_left_is_refused() -> None: + stack, _ = _stack() + stack.hbp._peers[_A]["CONNECTION"] = "RPTL-RECEIVED" + assert not stack.hbp.send_prompt_to_peer(_A, _frame(1, dst=4000, src=1000001)) + assert stack.transport.sent == [] + + +class _Master: + """Accepts the first ``accept`` frames, then refuses, then would accept again (hotspot free).""" + + def __init__(self, accept: int = 99) -> None: + self.frames: list[tuple[bytes, bytes]] = [] + self.attempts = 0 + self._accept = accept + + def send_prompt_to_peer(self, peer_id: bytes, pkt: bytes) -> bool: + self.attempts += 1 + if self.attempts == self._accept + 1: + return False + self.frames.append((peer_id, pkt)) + return True + + +def _voice(master: _Master) -> VoiceUseCases: + config = {"GLOBAL": {}, "SYSTEMS": {_SYSTEM: {"MODE": "MASTER", "ANNOUNCEMENT_LANGUAGE": "es_ES"}}} + return VoiceUseCases( + FakeVoiceProvider(), config, get_protocols=lambda: {_SYSTEM: master}, + call_from_reactor=lambda fn, *a: fn(*a), audio_path="/tmp/audio", + ) + + +def test_the_reply_is_a_group_call_from_the_server_to_tg_4000_on_the_same_slot() -> None: + for slot, ts_bit in ((1, 0x00), (2, 0x80)): + master = _Master() + with patch("adn_server.application.voice_use_cases.time.sleep"): + sent = _voice(master).tg4000_voice(_SYSTEM, _A, slot) + assert sent == len(master.frames) == 3 + for peer_id, pkt in master.frames: + assert peer_id == _A + assert pkt[8:11] == bytes_3(4000) + assert pkt[5:8] == bytes_3(1000001) + assert pkt[15] & 0x80 == ts_bit + + +def test_the_reply_stops_when_the_hotspot_refuses_a_frame() -> None: + """Once refused, no later frame is even tried: the reply must not resume half-way + when the hotspot is free again.""" + master = _Master(accept=1) + with patch("adn_server.application.voice_use_cases.time.sleep"): + assert _voice(master).tg4000_voice(_SYSTEM, _A, 2) == 1 + assert master.attempts == 2 # the accepted frame and the refused one, nothing after