From 4b14c1f0025dfb5dedd491c46f780bd2392fa14b Mon Sep 17 00:00:00 2001 From: zakhy <=> Date: Mon, 21 Apr 2025 17:56:22 +0700 Subject: [PATCH] rollback --- apps/workerslocation/commands/radiusip.py | 152 ++++++++-------------- 1 file changed, 55 insertions(+), 97 deletions(-) diff --git a/apps/workerslocation/commands/radiusip.py b/apps/workerslocation/commands/radiusip.py index 7cc8426..5b8b860 100644 --- a/apps/workerslocation/commands/radiusip.py +++ b/apps/workerslocation/commands/radiusip.py @@ -74,102 +74,6 @@ async def send_messages(websocket, message): await websocket.close() -async def receive_messages(websocket, auth_dict): - try: - promise_id = 2 - ssrc = SSRC - voip_port = API_PORT - call_mapi_initialized = False - source_id = auth_dict.get("client_id") - waiting_for_grant = False - current_voice_call = None - promise_granted = False - retry_attempts = 0 - current_channel = None - - async for message in websocket: - message_from_json = json.loads(message) - for message_item in message_from_json: - identifier = message_item.get("identifier") - if identifier != "location:0/position_broadcast": - log(f"<<< Ответ получен: {message_item}") - - if identifier == "core/connection_response": - log("Соединение установлено. Инициализация модулей...") - source_id = message_item["payload"].get("client_id") - auth_dict["client_id"] = source_id - await send_messages(websocket, get_call_initialize_command()) - await send_messages(websocket, get_location_initialize_command()) - - elif identifier == "call:1/initialization_response": - call_mapi_initialized = True - ssrc = message_item["payload"].get("voip_ssrc", SSRC) - voip_port = message_item["payload"].get("voip_port", API_PORT) - - elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"): - await save_location(message_item["payload"]) - - elif identifier == "core/promise_response" and waiting_for_grant: - payload = message_item["payload"] - log(f"Статус promise_id={payload.get('promise_id')} → {payload.get('state')}") - if payload["state"] == "granted" and current_voice_call: - promise_granted = True - elif payload["state"] == "faulted": - log("[ОШИБКА] Передача отклонена сервером. Повторная попытка...") - retry_attempts += 1 - if retry_attempts <= MAX_RETRY_ATTEMPTS: - await asyncio.sleep(RETRY_DELAY_SECONDS) - await send_messages( - websocket, - get_transmit_command(promise_id, ssrc, current_channel, source_id) - ) - else: - log("[ОШИБКА] Достигнуто максимальное число попыток.") - waiting_for_grant = False - current_voice_call = None - retry_attempts = 0 - - elif identifier == 'call:1/participant_state_broadcast' and promise_granted: - payload = message_item["payload"] - log(f"Состояние участника вызова: composite_call_id={payload.get('composite_call_id')}, " - f"participant_call_id={payload.get('participant_call_id')}, state={payload.get('state')}") - - if payload['state'] == 'own_tx': - log("Разрешение получено. Начинаем трансляцию...") - await set_voice_call_sent(current_voice_call) - await start_audio_stream( - current_voice_call.alarm_file.audio_file.path, - auth_dict["radiusip_host_ws"], - voip_port, - ssrc - ) - await send_messages(websocket, get_promise_cancel_command(promise_id)) - log("Трансляция завершена и вызов остановлен.") - promise_id += 1 - waiting_for_grant = False - current_voice_call = None - promise_granted = False - retry_attempts = 0 - - elif call_mapi_initialized and auth_dict.get("plasystem") and not waiting_for_grant: - voice_call = await get_voice_calls() - if voice_call: - for ch in voice_call.channels.all(): - channel = ch.uid - log(f"Запрос на отправку аудио по каналу: {channel}") - await send_messages( - websocket, - get_transmit_command(promise_id, ssrc, channel, source_id) - ) - current_voice_call = voice_call - current_channel = channel - waiting_for_grant = True - promise_granted = False - retry_attempts = 0 - except Exception: - logging.error(traceback.format_exc()) - - @sync_to_async def get_voice_calls(): return VoiceCall.objects.filter(sent=False).prefetch_related("alarm_file", "channels").first() @@ -247,6 +151,50 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc): log("Передача аудиофайла завершена.") +async def handle_voice_transmission(websocket, promise_id, ssrc, voip_port, auth_dict, voice_call, channel): + retry_attempts = 0 + source_id = auth_dict.get("client_id") + + while retry_attempts < MAX_RETRY_ATTEMPTS: + log(f"Запрос на отправку аудио по каналу: {channel}") + await send_messages(websocket, get_transmit_command(promise_id, ssrc, channel, source_id)) + + while True: + try: + response = await asyncio.wait_for(websocket.recv(), timeout=5) + for item in json.loads(response): + identifier = item.get("identifier") + if identifier == "core/promise_response": + state = item["payload"].get("state") + log(f"Статус promise_id={promise_id} → {state}") + if state == "granted": + log("Разрешение получено. Начинаем трансляцию...") + await set_voice_call_sent(voice_call) + await start_audio_stream( + voice_call.alarm_file.audio_file.path, + auth_dict["radiusip_host_ws"], + voip_port, + ssrc + ) + await send_messages(websocket, get_promise_cancel_command(promise_id)) + log("Трансляция завершена и вызов остановлен.") + return + elif state == "faulted": + retry_attempts += 1 + log(f"[ОШИБКА] Передача отклонена. Попытка {retry_attempts} из {MAX_RETRY_ATTEMPTS}...") + await asyncio.sleep(RETRY_DELAY_SECONDS) + break + elif identifier == "call:1/participant_state_broadcast": + log(f"Состояние участника вызова: {item['payload']}") + except asyncio.TimeoutError: + log("[ОШИБКА] Таймаут при ожидании ответа. Повтор попытки...") + retry_attempts += 1 + await asyncio.sleep(RETRY_DELAY_SECONDS) + break + + log("[ОШИБКА] Достигнуто максимальное число попыток передачи.") + + @sync_to_async def get_settings_from_db(): prefix = "" @@ -285,7 +233,17 @@ async def main(): try: async with websockets.connect(uri, ping_interval=20, ping_timeout=10) as websocket: await send_messages(websocket, connection_request) - await receive_messages(websocket, auth_dict) + promise_id = 2 + + while True: + voice_call = await get_voice_calls() + if voice_call: + ssrc = SSRC + voip_port = API_PORT + for channel in voice_call.channels.values_list('channel_id', flat=True): + await handle_voice_transmission(websocket, promise_id, ssrc, voip_port, auth_dict, voice_call, channel) + promise_id += 1 + await asyncio.sleep(1) except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError): log("Соединение не удалось или разорвано. Повтор через 5 секунд...") await asyncio.sleep(5)