diff --git a/docs/en/server/user-guide/configuration.md b/docs/en/server/user-guide/configuration.md index ac109a4..5dae48e 100644 --- a/docs/en/server/user-guide/configuration.md +++ b/docs/en/server/user-guide/configuration.md @@ -106,7 +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). | +| **TG4000_VOICE** | Default `false`. With `true`, a hotspot keying **TG / ID 4000** on this MASTER hears back the link status ("linked to" + the statics it still has on that slot, else "not linked") on that slot, and only that hotspot hears it; a private call to 4000 is answered with a private call from ID 4000. 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 a243721..721164c 100644 --- a/docs/en/server/user-guide/special-numbers.md +++ b/docs/en/server/user-guide/special-numbers.md @@ -75,7 +75,14 @@ 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. +**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`: "linked to" and the static TGs the hotspot still has on that slot (its OPTIONS and the MASTER's `TS1_STATIC` / `TS2_STATIC`, up to four), else "linked to *N*" with a `DEFAULT_REFLECTOR`, else "not linked". + +- A **group** call to TG 4000 is answered with a group call from the server voice ID to **TG 4000** on that slot: the radio hears it on the contact it just used. +- A **private** call to ID 4000 is answered with a private call **from ID 4000** to the caller, which hotspot configurations map back to the private contact (e.g. `PCRewrite …,84000,…,4000,…`). + +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. It is paced on the reactor, one frame every 58 ms. One reply per over; none if the terminator is lost. + +**Shared MASTER, legs:** a dynamic leg the sender was the only one using (no other connected hotspot holds that TG on that slot as a dynamic session, an OPTIONS static or a YAML static) is set IDLE right away instead of waiting for its timer. ### `SINGLE_MODE` impact on in-band deactivation diff --git a/docs/es/server/user-guide/configuration.md b/docs/es/server/user-guide/configuration.md index b3fdfea..d7d87b6 100644 --- a/docs/es/server/user-guide/configuration.md +++ b/docs/es/server/user-guide/configuration.md @@ -106,7 +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). | +| **TG4000_VOICE** | Por defecto `false`. Con `true`, el hotspot que pulsa **TG / ID 4000** en este MASTER oye de vuelta el estado de enlace («enlazado a» + los estáticos que conserva en ese slot; si no, «no enlazado») por ese slot, y solo lo oye ese hotspot; una llamada privada al 4000 se responde con una privada desde el ID 4000. 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 f444d92..65490a7 100644 --- a/docs/es/server/user-guide/special-numbers.md +++ b/docs/es/server/user-guide/special-numbers.md @@ -75,7 +75,14 @@ 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. +**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: «enlazado a» y los TG estáticos que el hotspot conserva en ese slot (sus OPTIONS y los `TS1_STATIC` / `TS2_STATIC` del MASTER, hasta cuatro); si no tiene, «enlazado a *N*» si hay `DEFAULT_REFLECTOR`; si no, «no enlazado». + +- Una llamada de **grupo** al TG 4000 se responde con una llamada de grupo del ID de voz del servidor al **TG 4000** por ese slot: la radio la oye en el contacto que acaba de usar. +- Una llamada **privada** al ID 4000 se responde con una llamada privada **desde el ID 4000** a quien llamó, que las configuraciones de los hotspots devuelven al contacto privado (p. ej. `PCRewrite …,84000,…,4000,…`). + +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. Se reproduce en el reactor, una trama cada 58 ms. Una respuesta por pasada; ninguna si se pierde el terminador. + +**MASTER compartido, patas:** una pata dinámica que solo usaba el que hace el 4000 (ningún otro hotspot conectado tiene ese TG en ese slot como sesión dinámica, estático de OPTIONS o estático del YAML) pasa a IDLE en el momento, sin esperar a su temporizador. ### Impacto de `SINGLE_MODE` en la lógica de desactivación diff --git a/src/adn_server/application/ports.py b/src/adn_server/application/ports.py index b741026..c6f483d 100644 --- a/src/adn_server/application/ports.py +++ b/src/adn_server/application/ports.py @@ -192,8 +192,10 @@ class VoiceProvider(ABC): ... @abstractmethod - def pkt_gen(self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any]) -> Any: - """Generate HBP voice packets for a phrase (generator). Legacy mk_voice.pkt_gen.""" + def pkt_gen( + self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any], *, private: bool = False + ) -> Any: + """Generate HBP voice packets for a phrase (generator). Legacy mk_voice.pkt_gen; ``private``: unit call.""" ... def read_single_file(self, audio_path: str, lang: str, file_number: str) -> list: diff --git a/src/adn_server/application/routing/subscription_table.py b/src/adn_server/application/routing/subscription_table.py index 56a554c..373cade 100644 --- a/src/adn_server/application/routing/subscription_table.py +++ b/src/adn_server/application/routing/subscription_table.py @@ -178,6 +178,11 @@ class SubscriptionTableMixin: from ..subscription.subscription_table_ops import deactivate_all_dynamic_relays_store deactivate_all_dynamic_relays_store(self._subscription_store, system_name) + def release_dynamic_leg(self, system_name: str, tgid: int, slot: int) -> bool: + """Set one dynamic leg of a system IDLE (TG/ID 4000 on a shared MASTER, last holder gone).""" + from ..subscription.subscription_table_ops import release_dynamic_leg_store + + return release_dynamic_leg_store(self._subscription_store, system_name, tgid, slot) def apply_startup_subscriptions(self) -> None: """Legacy startup: set default reflectors and static TGs for each MASTER system.""" prohibited_tgs = (0, 1, 2, 3, 4, 5, 9, 9990, 9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999) diff --git a/src/adn_server/application/subscription/subscription_table_ops.py b/src/adn_server/application/subscription/subscription_table_ops.py index 6f5cd05..3396b10 100644 --- a/src/adn_server/application/subscription/subscription_table_ops.py +++ b/src/adn_server/application/subscription/subscription_table_ops.py @@ -570,6 +570,37 @@ def deactivate_all_dynamic_relays_store( ) +def release_dynamic_leg_store( + store: SubscriptionStore, + system_name: str, + tgid: int, + slot: int, +) -> bool: + """Set one dynamic leg (``tgid`` on ``slot``) of a system IDLE; False when there is none active. + + Used on a shared MASTER when the hotspot that keyed TG/ID 4000 was the only one holding it. + Reflector and static legs are never touched. + """ + released = False + for sub in list(store.list_by_system(SystemId(system_name))): + if int(sub.target_tgid) != int(tgid) or int(sub.channel.slot) != int(slot): + continue + if sub.table_key().startswith("#") or _legacy_to_type(sub) == "STAT" or not sub.is_active(): + continue + sub.state.phase = SubscriptionPhase.IDLE + store.upsert(sub) + released = True + logger.info( + "(ROUTER) Released dynamic bridge after TG/ID 4000, no other hotspot holds it: " + "System: %s, Bridge: %s, TS: %s, TGID: %s", + system_name, + sub.table_key(), + slot, + int(tgid), + ) + return released + + def readd_system_after_ua_timer_change_store( store: SubscriptionStore, system: str, diff --git a/src/adn_server/application/voice_use_cases.py b/src/adn_server/application/voice_use_cases.py index f69515a..ddbbee1 100644 --- a/src/adn_server/application/voice_use_cases.py +++ b/src/adn_server/application/voice_use_cases.py @@ -39,6 +39,10 @@ from .server_voice import server_voice_rf_src_bytes logger = logging.getLogger(__name__) _FRAME_INTERVAL = 0.058 +# The TG/ID 4000 reply starts this long after the over ends, so the radio is back in receive. +_TG4000_REPLY_DELAY = 1.0 +# At most this many statics are named in "linked to ..." (each TG is a few digits of speech). +_MAX_LINKED_SPOKEN = 4 @dataclass @@ -66,12 +70,14 @@ class VoiceUseCases: get_protocols: Callable[[], dict[str, Any]] | None = None, call_from_reactor: Callable[..., None] | None = None, audio_path: str | None = None, + call_later: Callable[..., Any] | None = None, ) -> None: self._voice = voice_provider self._config = config self._get_protocols = get_protocols self._call_from_reactor = call_from_reactor self._audio_path = audio_path or "" + self._call_later = call_later # reactor.callLater: paces replies on the reactor, no thread held def _server_source_id(self) -> bytes: return server_voice_rf_src_bytes(self._config) @@ -80,8 +86,12 @@ class VoiceUseCases: """Load AMBE words for given languages (legacy readAMBE.readfiles).""" return self._voice.get_ambe_words(languages, audio_path) - def pkt_gen(self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any]) -> Any: - """Generate HBP voice packets for phrase (legacy mk_voice.pkt_gen).""" + def pkt_gen( + self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any], *, private: bool = False + ) -> Any: + """Generate HBP voice packets for phrase (legacy mk_voice.pkt_gen); ``private``: unit call.""" + if private: + return self._voice.pkt_gen(rf_src, dst_id, peer, slot, phrase, private=True) return self._voice.pkt_gen(rf_src, dst_id, peer, slot, phrase) def read_single_file(self, audio_path: str, lang: str, file_number: str) -> list: @@ -167,8 +177,12 @@ 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 _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.""" + def _link_status_words(self, sys_cfg: dict[str, Any], linked: tuple[int, ...] = ()) -> list[Any] | None: + """The link status in the system's language; None without audio. + + "linked to" and the TGs in ``linked`` (statics still on the slot, at most + ``_MAX_LINKED_SPOKEN``), else "linked to ", else "not linked". + """ _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: @@ -179,7 +193,13 @@ class VoiceUseCases: return None _say = [silence, silence] default_refl = int(sys_cfg.get("DEFAULT_REFLECTOR", 0)) - if default_refl > 0: + if linked: + _say.append(words.get("linkedto") or silence) + for tg in linked[:_MAX_LINKED_SPOKEN]: + _say.append(silence) + for digit in str(tg): + _say.append(words.get(digit) or silence) + elif default_refl > 0: _say.append(silence) _say.append(words.get("linkedto") or silence) _say.append(silence) @@ -213,46 +233,59 @@ class VoiceUseCases: 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. + def tg4000_voice( + self, + system: str, + peer_id: bytes, + slot: int, + *, + rf_src: bytes = b"", + private: bool = False, + linked: tuple[int, ...] = (), + ) -> int: + """Answer a hotspot's TG/ID 4000 with the link status, to that hotspot only. - 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. + Runs from a worker thread only to load the words and build the frames; playback is + paced on the reactor with ``call_later`` (``_TG4000_REPLY_DELAY`` after the over, then + one frame per ``_FRAME_INTERVAL``) through ``send_prompt_to_peer``, so it stops if the + hotspot gets busy on that slot or leaves. A group 4000 is answered on TG 4000 from the + server voice ID (the radio is still on that contact); a private 4000 (``private``) with + a private call from ID 4000 to ``rf_src``. Returns the frames queued. """ - if not self._get_protocols or not self._call_from_reactor or not self._audio_path: + if not self._get_protocols or not self._call_from_reactor or not self._audio_path or not self._call_later: 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, {})) + _say = self._link_status_words(self._config.get("SYSTEMS", {}).get(system, {}), tuple(linked)) 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) + ts = 1 if int(slot) == 2 else 0 + if private and rf_src: + frames = list(self.pkt_gen(bytes_3(4000), rf_src, bytes_4(9), ts, _say, private=True)) + else: + frames = list(self.pkt_gen(self._server_source_id(), bytes_3(4000), bytes_4(9), ts, _say)) + if frames: + self._call_from_reactor(self._start_peer_prompt, protocol, system, peer_id, int(slot), frames) + return len(frames) + + def _start_peer_prompt(self, protocol: Any, system: str, peer_id: bytes, slot: int, frames: list[bytes]) -> None: + """Reactor: schedule the reply's first frame ``_TG4000_REPLY_DELAY`` from now.""" 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 + start = time.time() + _TG4000_REPLY_DELAY + self._call_later(_TG4000_REPLY_DELAY, self._peer_prompt_step, protocol, system, peer_id, slot, frames, 0, start, run) - @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): + def _peer_prompt_step( + self, protocol: Any, system: str, peer_id: bytes, slot: int, + frames: list[bytes], index: int, start: float, run: _PromptRun, + ) -> None: + """Reactor: one frame of the reply, then the next one on time; stops at the first refusal.""" + if index < len(frames) and protocol.send_prompt_to_peer(peer_id, frames[index]): run.sent += 1 - else: - run.stopped = True + due = start + (index + 1) * _FRAME_INTERVAL + self._call_later( + max(0.0, due - time.time()), self._peer_prompt_step, + protocol, system, peer_id, slot, frames, index + 1, start, run, + ) + return + logger.info("(%s) TG 4000 voice reply to peer %s on TS %s: %d frames", system, int_id(peer_id), slot, run.sent) diff --git a/src/adn_server/infrastructure/bootstrap/peer_server.py b/src/adn_server/infrastructure/bootstrap/peer_server.py index d56802a..0b95bbc 100644 --- a/src/adn_server/infrastructure/bootstrap/peer_server.py +++ b/src/adn_server/infrastructure/bootstrap/peer_server.py @@ -431,6 +431,7 @@ def run_peer_server( get_protocols=lambda: protocols, call_from_reactor=reactor.callFromThread, audio_path=audio_path, + call_later=reactor.callLater, ) ident_use_cases = IdentUseCases( config, @@ -703,6 +704,7 @@ def run_peer_server( on_in_band_signalling=routing_use_cases.apply_in_band_signalling, on_options_received=routing_use_cases.options_config_for_system, on_deactivate_dynamic_relays=routing_use_cases.deactivate_all_dynamic_relays, + on_release_dynamic_leg=routing_use_cases.release_dynamic_leg, on_obp_bcsq_received=routing_use_cases.on_obp_bcsq_received, on_talker_alias_repeat_prepare=routing_use_cases.prepare_talker_alias_local_repeat, on_talker_alias_repeat_burst=routing_use_cases.rewrite_repeat_voice_burst, diff --git a/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py b/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py index 4b91851..5931be6 100644 --- a/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py +++ b/src/adn_server/infrastructure/twisted_adapters/udp_hbp.py @@ -58,8 +58,10 @@ from ...application.routing.helpers import ( is_server_originated_voice, is_special_tg, is_unit_data_ingress, + master_dynamic_tg_slots, parse_dmrd_route_fields, peer_downlink_voice_slot, + peer_is_simplex, peer_matches_rf_source, peer_should_receive_group_voice, peer_single_exclusive_tgid, @@ -73,6 +75,7 @@ from ...application.routing.helpers import ( ) from ...application.routing.peer_downlink_index import ( build_peer_downlink_index, + cached_peer_static_tgs, count_connected_peers, invalidate_peer_options_cache, ) @@ -231,11 +234,12 @@ 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_tg4000_voice: Callable[..., 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, on_deactivate_dynamic_relays: Callable[[str], None] | None = None, + on_release_dynamic_leg: Callable[[str, int, int], bool] | None = None, on_obp_bcsq_received: Callable[[str, bytes, bytes], None] | None = None, on_talker_alias_local_repeat: Callable[[str, bytes, bytes, bytes], None] | None = None, on_talker_alias_repeat_prepare: Callable[[str, bytes, bytes, bytes, int, bytes, str], None] | None = None, @@ -262,6 +266,7 @@ class HBPProtocol(DatagramProtocol): self._on_in_band_signalling = on_in_band_signalling self._on_options_received = on_options_received self._on_deactivate_dynamic_relays = on_deactivate_dynamic_relays + self._on_release_dynamic_leg = on_release_dynamic_leg self._on_obp_bcsq_received = on_obp_bcsq_received self._on_talker_alias_local_repeat = on_talker_alias_local_repeat self._on_talker_alias_repeat_prepare = on_talker_alias_repeat_prepare @@ -644,6 +649,7 @@ class HBPProtocol(DatagramProtocol): hotspot on it. """ peer = self._peers.get(peer_id, {}) + held_by_sender = self._peer_dynamic_tg_slots(peer_id) clear_peer_ua_sessions(peer, self._config, peer_id) clear_peer_rx_status_slots(self.STATUS, peer_id) if self._dynamic_tg_uc is not None: @@ -653,7 +659,8 @@ class HBPProtocol(DatagramProtocol): if self._inject_multi_peer_options_filter(): # The MASTER's legs are shared by every hotspot on it: in-band 4000 signalling would # set all of them IDLE on this slot (dynamics and OPTIONS statics of the others). - # This peer's own dynamics are what was cleared above. + # This peer's own dynamics are what was cleared above; a leg only it held goes too. + self._release_legs_nobody_else_holds(peer_id, held_by_sender) self._mark_downlink_index_dirty() self._push_config_to_monitor() logger.info( @@ -670,6 +677,46 @@ class HBPProtocol(DatagramProtocol): ) self._on_deactivate_dynamic_relays(self._system) + def _peer_dynamic_tg_slots(self, peer_id: bytes) -> set[tuple[int, int]]: + """(TG, slot) pairs this hotspot holds as dynamic UA sessions (SINGLE=1 and SINGLE=0).""" + pk = bytes_4(int_id(peer_id)) + held: set[tuple[int, int]] = set() + single = (self._config.get("_PEER_UA_SESSIONS") or {}).get(pk) + if isinstance(single, dict): + for slot, entry in single.items(): + if isinstance(entry, dict) and int(entry.get("tgid", 0) or 0): + held.add((int(entry["tgid"]), int(slot))) + multi = (self._config.get("_PEER_UA_MULTI_TGS") or {}).get(pk) + if isinstance(multi, dict): + for slot, tgs in multi.items(): + for tg in tgs or (): + held.add((int(tg), int(slot))) + return held + + def _peer_static_tgs_on_slot(self, peer: dict[str, Any], slot: int) -> tuple[int, ...]: + """A hotspot's static TGs on ``slot``: its MASTER's TS1/TS2_STATIC and its OPTIONS (both lists if simplex).""" + ts1, ts2 = cached_peer_static_tgs(peer) + listed = (*ts1, *ts2) if peer_is_simplex(peer) else (ts1 if int(slot) == 1 else ts2) + return tuple(dict.fromkeys(int(tg) for tg in listed if str(tg).isdigit() and int(tg) > 0)) + + def _release_legs_nobody_else_holds(self, peer_id: bytes, held_by_sender: set[tuple[int, int]]) -> None: + """After a 4000 on a shared MASTER, set IDLE the dynamic legs only the sender was using. + + A 4000 clears dynamics, never a static: a leg stays while any connected hotspot, the + sender included, has that TG on that slot as a static (OPTIONS or YAML), or another one + holds it as a dynamic session (the sender's were cleared before this runs). + """ + if not held_by_sender or self._on_release_dynamic_leg is None: + return + now = time.time() + connected = [p for p in self._peers.values() if isinstance(p, dict) and p.get("CONNECTION") == "YES"] + for tgid, slot in sorted(held_by_sender): + if slot in master_dynamic_tg_slots(self._config, tgid, now=now): + continue + if any(tgid in self._peer_static_tgs_on_slot(p, slot) for p in connected): + continue + self._on_release_dynamic_leg(self._system, tgid, slot) + def _handle_tg4000_packet( self, peer_id: bytes, @@ -685,7 +732,8 @@ class HBPProtocol(DatagramProtocol): """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``). + hotspot (``VoiceUseCases.tg4000_voice``): a group 4000 on TG 4000, a private 4000 as a + private call from ID 4000 to the caller, naming the statics it still has on that slot. """ if int_dst_id != 4000: return False @@ -704,7 +752,12 @@ class HBPProtocol(DatagramProtocol): 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) + reactor.callInThread( + self._on_tg4000_voice, self._system, peer_id, slot, + rf_src=rf_src, + private=call_type == "unit", + linked=self._peer_static_tgs_on_slot(self._peers.get(peer_id, {}), slot), + ) return True def purge_peer_dynamic_tgs(self, peer_id: bytes) -> bool: @@ -915,7 +968,7 @@ 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). + """One frame of a server prompt for one hotspot only (the TG/ID 4000 voice reply, group or private). 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 @@ -926,11 +979,17 @@ class HBPProtocol(DatagramProtocol): if not isinstance(peer, dict) or peer.get("CONNECTION") != "YES": return False packet = b"".join([packet[:11], peer_id, packet[15:]]) + bits = packet[15] + slot = 2 if bits & 0x80 else 1 + # The slot gate and tracking are per TG: a private reply (from ID 4000) is checked and + # tracked as TG 4000 on its slot, so routed group voice does not start under it. + gate = packet if not bits & 0x40 else synthetic_group_dmrd_burst_packet( + slot, 4000, packet[16:20], frame_type=(bits >> 4) & 0x3, dtype_vseq=bits & 0xF, + ) ctx = self._downlink_ctx() - if not peer_accepts_group_dmrd_packet(ctx, peer_id, peer, packet, routed=True): + if not peer_accepts_group_dmrd_packet(ctx, peer_id, peer, gate, 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) + track_peer_group_dmrd(ctx, peer_id, gate, peer, from_ingress=False, voice_slot=slot) self.transport.write(packet, peer["SOCKADDR"]) return True @@ -2605,11 +2664,12 @@ 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_tg4000_voice: Callable[..., 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, on_deactivate_dynamic_relays: Callable[[str], None] | None = None, + on_release_dynamic_leg: Callable[[str, int, int], bool] | None = None, on_obp_bcsq_received: Callable[[str, bytes, bytes], None] | None = None, on_talker_alias_local_repeat: Callable[[str, bytes, bytes, bytes], None] | None = None, on_talker_alias_repeat_prepare: Callable[[str, bytes, bytes, bytes, int, bytes, str], None] | None = None, @@ -2635,6 +2695,7 @@ def HBPProtocolFactory( on_in_band_signalling=on_in_band_signalling, on_options_received=on_options_received, on_deactivate_dynamic_relays=on_deactivate_dynamic_relays, + on_release_dynamic_leg=on_release_dynamic_leg, on_obp_bcsq_received=on_obp_bcsq_received, on_talker_alias_local_repeat=on_talker_alias_local_repeat, on_talker_alias_repeat_prepare=on_talker_alias_repeat_prepare, diff --git a/src/adn_server/infrastructure/voice/ambe_reader.py b/src/adn_server/infrastructure/voice/ambe_reader.py index 827b4f9..e2e9fa0 100644 --- a/src/adn_server/infrastructure/voice/ambe_reader.py +++ b/src/adn_server/infrastructure/voice/ambe_reader.py @@ -173,10 +173,10 @@ class DefaultVoiceProvider(VoiceProvider): return reader.readSingleFile(rel) def pkt_gen( - self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any] + self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any], *, private: bool = False ) -> Iterator[bytes]: """Generate HBP voice packets for phrase. Legacy mk_voice.pkt_gen.""" - return _pkt_gen(rf_src, dst_id, peer, slot, phrase) + return _pkt_gen(rf_src, dst_id, peer, slot, phrase, private=private) class StubVoiceProvider(VoiceProvider): @@ -186,7 +186,7 @@ class StubVoiceProvider(VoiceProvider): return {} def pkt_gen( - self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any] + self, rf_src: bytes, dst_id: bytes, peer: bytes, slot: int, phrase: list[Any], *, private: bool = False ) -> Iterator[bytes]: return iter([]) diff --git a/src/adn_server/infrastructure/voice/pkt_gen.py b/src/adn_server/infrastructure/voice/pkt_gen.py index e201019..309ccb7 100644 --- a/src/adn_server/infrastructure/voice/pkt_gen.py +++ b/src/adn_server/infrastructure/voice/pkt_gen.py @@ -33,7 +33,7 @@ from bitarray import bitarray from ...domain import bytes_4 from ...domain.dmr import bptc from ...domain.dmr.bptc import encode_emblc -from ...domain.dmr.const import BS_DATA_SYNC, BS_VOICE_SYNC, EMB, LC_OPT, SLOT_TYPE +from ...domain.dmr.const import BS_DATA_SYNC, BS_VOICE_SYNC, EMB, LC_OPT, LC_OPT_U, SLOT_TYPE # Precalculated DMRD byte 15 (slot << 7 | this) HEADBITS = 0b00100001 @@ -52,11 +52,16 @@ def pkt_gen( peer: bytes, slot: int, phrase: list[Any], + *, + private: bool = False, ) -> Iterator[bytes]: - """Generate DMRD voice packets for phrase. Each word in phrase is list of [b0, b1] burst pairs (bitarray).""" + """Generate DMRD voice packets for phrase. Each word in phrase is list of [b0, b1] burst pairs (bitarray). + + ``private``: a unit-to-unit call (LC FLCO 3, DMRD call type bit) instead of a group call. + """ stream_id = bytes_4(randint(0x00, 0xFFFFFFFF)) sdp = rf_src + dst_id + peer - lc = LC_OPT + dst_id + rf_src + lc = (LC_OPT_U if private else LC_OPT) + dst_id + rf_src head_lc = bptc.encode_header_lc(lc) head_lc = [head_lc[:98], head_lc[-98:]] @@ -75,7 +80,7 @@ def pkt_gen( ] seq = 0 - slot_byte = (slot << 7) & 0xFF + slot_byte = ((slot << 7) & 0xFF) | (0x40 if private else 0) for _ in range(3): pkt = ( diff --git a/tests/harness/voice_helpers.py b/tests/harness/voice_helpers.py index 3e9ba5e..3491c7c 100644 --- a/tests/harness/voice_helpers.py +++ b/tests/harness/voice_helpers.py @@ -39,9 +39,11 @@ class FakeVoiceProvider: peer: bytes, slot: int, phrase: list[Any], + *, + private: bool = False, ) -> Iterator[bytes]: del phrase - ts_bit = 0x80 if slot else 0 + ts_bit = (0x80 if slot else 0) | (0x40 if private else 0) stream_id = bytes_4(0xA0A0A0A0) for seq in range(3): yield b"DMRD" + bytes([seq]) + rf_src[:3] + dst_id[:3] + peer[:4] + bytes([ts_bit | 0x10]) + stream_id + b"\x00" * 33 + b"\x00\x00" diff --git a/tests/voice/test_tg4000_voice_reply.py b/tests/voice/test_tg4000_voice_reply.py index bbc8b91..adad817 100644 --- a/tests/voice/test_tg4000_voice_reply.py +++ b/tests/voice/test_tg4000_voice_reply.py @@ -18,7 +18,12 @@ # 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.""" +"""TG4000_VOICE: a hotspot's TG/ID 4000 is answered with the link status, to that hotspot only. + +Group 4000 → group call on TG 4000 from the server voice ID; private 4000 → private call from +ID 4000 to the caller. "linked to" + the statics still on that slot, else "not linked". Paced on +the reactor with callLater. On a shared MASTER a dynamic leg only the sender held is released. +""" from __future__ import annotations @@ -26,21 +31,26 @@ from dataclasses import replace from typing import Any from unittest.mock import MagicMock, patch +import pytest + 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 +from adn_server.domain.subscription import SystemId _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" +_CALLER = 2130035 -def _stack(*, voice: bool | None = True) -> tuple[HbpRepeatStack, MagicMock]: +def _stack(*, voice: bool | None = True, options_a: str | None = None, options_b: str | None = None, + release: bool = False) -> 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: @@ -48,13 +58,16 @@ def _stack(*, voice: bool | None = True) -> tuple[HbpRepeatStack, MagicMock]: 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) + stack.hbp._on_in_band_signalling = stack.bridge.apply_in_band_signalling + if release: + stack.hbp._on_release_dynamic_leg = stack.bridge.release_dynamic_leg + stack.register_peer(_A, _ADDR_A, options=options_a) + stack.register_peer(_B, _ADDR_B, options=options_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: + src: int = _CALLER, 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), @@ -64,22 +77,30 @@ def _frame(dtype_vseq: int, *, slot: int = 2, stream: int = 0x40004000, dst: int 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)): + side_effect=lambda fn, *a, **k: fn(*a, **k)): 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 +# --- the protocol queues one reply, with what the reply needs --------------------------------- + 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) + reply.assert_called_once_with(_SYSTEM, _A, 1, rf_src=bytes_3(_CALLER), private=False, linked=()) -def test_a_private_call_to_4000_is_answered_too() -> None: +def test_a_private_call_to_4000_asks_for_a_private_reply() -> None: stack, reply = _stack() _over_4000(stack, call_type="unit") - reply.assert_called_once_with(_SYSTEM, _A, 2) + reply.assert_called_once_with(_SYSTEM, _A, 2, rf_src=bytes_3(_CALLER), private=True, linked=()) + + +def test_the_statics_left_on_that_slot_are_passed_on() -> None: + stack, reply = _stack(options_a="TS1=91;TS2=214,21472;") + _over_4000(stack) + assert reply.call_args.kwargs["linked"] == (214, 21472) def test_no_reply_unless_the_system_asks_for_it() -> None: @@ -89,6 +110,55 @@ def test_no_reply_unless_the_system_asks_for_it() -> None: reply.assert_not_called() +# --- releasing the legs only the sender held (shared MASTER) ---------------------------------- + +def _hold_dynamic(stack: HbpRepeatStack, peer: bytes, tgid: int, slot: int = 2) -> None: + pk = bytes_4(int.from_bytes(peer, "big")) + stack.hbp._config.setdefault("_PEER_UA_SESSIONS", {}).setdefault(pk, {})[slot] = { + "tgid": tgid, "expires": 0.0, "source": "local", + } + stack.bridge.ensure_dynamic_relay(bytes_3(tgid), _SYSTEM, slot, 900.0) + + +def _leg_active(stack: HbpRepeatStack, tgid: int, slot: int = 2) -> bool: + return any( + sub.is_active() for sub in stack.bridge._subscription_store.list_by_system(SystemId(_SYSTEM)) + if int(sub.target_tgid) == tgid and int(sub.channel.slot) == slot + ) + + +def test_a_leg_only_the_sender_held_is_released() -> None: + stack, _ = _stack(release=True) + _hold_dynamic(stack, _A, 3340) + _over_4000(stack) + assert not _leg_active(stack, 3340) + + +def test_a_leg_another_hotspot_holds_as_dynamic_stays() -> None: + stack, _ = _stack(release=True) + _hold_dynamic(stack, _A, 3340) + _hold_dynamic(stack, _B, 3340) + _over_4000(stack) + assert _leg_active(stack, 3340) + + +def test_a_leg_the_sender_also_has_as_static_stays() -> None: + """A 4000 clears dynamics, never a static, the sender's own included.""" + stack, _ = _stack(release=True, options_a="TS2=3340;") + _hold_dynamic(stack, _A, 3340) + _over_4000(stack) + assert _leg_active(stack, 3340) + + +def test_a_leg_another_hotspot_has_as_static_stays() -> None: + stack, _ = _stack(release=True, options_b="TS2=3340;") + _hold_dynamic(stack, _A, 3340) + _over_4000(stack) + assert _leg_active(stack, 3340) + + +# --- one frame, one hotspot --------------------------------------------------------------------- + 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) @@ -105,6 +175,14 @@ def test_a_prompt_frame_is_refused_while_the_hotspot_hears_another_stream() -> N assert stack.hbp.send_prompt_to_peer(_B, _frame(1, dst=4000, src=1000001, stream=0x0A0A0A0A)) # B is free +def test_a_private_reply_holds_the_hotspots_slot_while_it_plays() -> None: + stack, _ = _stack() + private = _frame(1, dst=_CALLER, src=4000, peer=bytes_4(9), stream=0x0B0B0B0B, call_type="unit") + assert stack.hbp.send_prompt_to_peer(_A, private) + assert stack.transport.sent[0][0][15] & 0x40 # still a private call on the wire + assert not stack.hbp.send_prompt_to_peer(_A, _frame(1, dst=3340, src=3340062, stream=0x01010101)) + + def test_a_prompt_frame_for_a_hotspot_that_left_is_refused() -> None: stack, _ = _stack() stack.hbp._peers[_A]["CONNECTION"] = "RPTL-RECEIVED" @@ -112,6 +190,8 @@ def test_a_prompt_frame_for_a_hotspot_that_left_is_refused() -> None: assert stack.transport.sent == [] +# --- VoiceUseCases: words, form, pacing --------------------------------------------------------- + class _Master: """Accepts the first ``accept`` frames, then refuses, then would accept again (hotspot free).""" @@ -128,31 +208,87 @@ class _Master: return True -def _voice(master: _Master) -> VoiceUseCases: +class _Reactor: + """callFromThread / callLater on a fake clock: each callLater moves time on by its delay.""" + + def __init__(self) -> None: + self.queue: list[tuple[float, Any, tuple]] = [] + self.delays: list[float] = [] + self.now = 1000.0 + + def call_from_reactor(self, fn: Any, *a: Any) -> None: + self.queue.append((0.0, fn, a)) + + def call_later(self, delay: float, fn: Any, *a: Any) -> None: + self.delays.append(delay) + self.queue.append((delay, fn, a)) + + def run(self, work: float = 0.0) -> None: + """``work``: time each callback takes, so a schedule that drifts shows in the delays.""" + with patch("adn_server.application.voice_use_cases.time.time", side_effect=lambda: self.now): + while self.queue: + delay, fn, a = self.queue.pop(0) + self.now += delay + fn(*a) + self.now += work + + +def _voice(master: _Master, reactor: _Reactor) -> 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", + call_from_reactor=reactor.call_from_reactor, audio_path="/tmp/audio", call_later=reactor.call_later, ) -def test_the_reply_is_a_group_call_from_the_server_to_tg_4000_on_the_same_slot() -> None: +def test_a_group_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 + master, reactor = _Master(), _Reactor() + assert _voice(master, reactor).tg4000_voice(_SYSTEM, _A, slot, rf_src=bytes_3(_CALLER)) == 3 + assert master.frames == [] # nothing sent from the worker thread + reactor.run() + assert 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 + assert (pkt[5:8], pkt[8:11]) == (bytes_3(1000001), bytes_3(4000)) + assert pkt[15] & 0xC0 == ts_bit # group call on the slot of the 4000 + + +def test_a_private_reply_comes_from_id_4000_to_the_caller() -> None: + master, reactor = _Master(), _Reactor() + _voice(master, reactor).tg4000_voice(_SYSTEM, _A, 2, rf_src=bytes_3(_CALLER), private=True) + reactor.run() + assert master.frames + for _peer, pkt in master.frames: + assert (pkt[5:8], pkt[8:11]) == (bytes_3(4000), bytes_3(_CALLER)) + assert pkt[15] & 0xC0 == 0xC0 # TS2, private call + + +def test_the_reply_is_paced_on_the_reactor_after_a_second() -> None: + master, reactor = _Master(), _Reactor() + _voice(master, reactor).tg4000_voice(_SYSTEM, _A, 2, rf_src=bytes_3(_CALLER)) + reactor.run(work=0.005) # each frame takes 5 ms to send + assert reactor.delays[0] == 1.0 # after the over, the radio is back in receive + # frames keep a fixed 58 ms grid from the start: the 5 ms of work comes off each wait + assert reactor.delays[1:] == pytest.approx([0.053] * 3) 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 + master, reactor = _Master(accept=1), _Reactor() + _voice(master, reactor).tg4000_voice(_SYSTEM, _A, 2, rf_src=bytes_3(_CALLER)) + reactor.run() + assert len(master.frames) == 1 assert master.attempts == 2 # the accepted frame and the refused one, nothing after + + +def test_linked_to_names_the_statics_left_else_not_linked() -> None: + words = {"silence": "_", "linkedto": "LINKED", "notlinked": "NOT", "2": "2", "1": "1", "4": "4", "9": "9", "0": "0"} + voice = _voice(_Master(), _Reactor()) + voice.get_ambe_words = lambda lang, path: {lang: words} # type: ignore[method-assign] + sys_cfg = {"ANNOUNCEMENT_LANGUAGE": "es_ES"} + assert voice._link_status_words(sys_cfg) == ["_", "_", "NOT", "_"] + assert voice._link_status_words(sys_cfg, (214, 91)) == ["_", "_", "LINKED", "_", "2", "1", "4", "_", "9", "1", "_"] + many = voice._link_status_words(sys_cfg, (1, 2, 4, 9, 10)) + assert many.count("_") == 2 + 4 + 1 # at most four TGs are named