From 0b0f3af7899acd5bf91aa459937010bdcb9a1318 Mon Sep 17 00:00:00 2001 From: zakhy <=> Date: Thu, 17 Apr 2025 15:51:23 +0700 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=BE=D1=81=D0=BB=D0=B5=D0=B4=D0=BD?= =?UTF-8?q?=D1=8F=D1=8F=20=D0=BF=D0=BE=D0=BF=D1=8B=D1=82=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/workerslocation/commands/radiusip.py | 251 +++++++++------------- 1 file changed, 98 insertions(+), 153 deletions(-) diff --git a/apps/workerslocation/commands/radiusip.py b/apps/workerslocation/commands/radiusip.py index fafd76e..5b9231e 100644 --- a/apps/workerslocation/commands/radiusip.py +++ b/apps/workerslocation/commands/radiusip.py @@ -1,3 +1,5 @@ +# Обновленный основной WebSocket и RTP клиент для Radiusip + import asyncio import datetime import json @@ -14,134 +16,128 @@ import websockets from asgiref.sync import sync_to_async from dateutil import parser -# Настройки для WebSocket и RTP - API_PORT = 18500 SSRC = 269484035 -RTP_PAYLOAD_TYPE = 8 # G.711A -PACKET_DURATION_MS = 20 # Длительность пакета 20 мс +RTP_PAYLOAD_TYPE = 8 +PACKET_DURATION_MS = 20 def get_call_initialize_command(): - return [ - { - "identifier": "call:1/initialization_request", - "payload": { - "voip_port": "11111", # Порт для приема RTP - "supported_codecs": [ - { - "codec_id": RTP_PAYLOAD_TYPE, - "name": "G711A", - "packet_duration": PACKET_DURATION_MS, - "sampling_rate": 8000, - } - ], - "is_supported_webrtc": False, - }, + return [{ + "identifier": "call:1/initialization_request", + "payload": { + "voip_port": str(API_PORT), + "supported_codecs": [{ + "codec_id": RTP_PAYLOAD_TYPE, + "name": "G711A", + "packet_duration": PACKET_DURATION_MS, + "sampling_rate": 8000 + }], + "is_supported_webrtc": False } - ] + }] def get_location_initialize_command(): return [{"identifier": "location:0/initialization_request", "payload": {}}] -def get_transmit_command(promise_id, ssrc, target): - return [ - { - "identifier": "call:1/transmit_request", - "payload": { - "promise_id": promise_id, - "target": target, - "modifier": "not", - "voip_ssrc": ssrc, - }, +def get_transmit_command(promise_id, ssrc, target, source): + return [{ + "identifier": "call:1/transmit_request", + "payload": { + "promise_id": promise_id, + "source": source, + "target": target, + "modifier": "not", + "voip_ssrc": ssrc } - ] + }] def get_promise_cancel_command(promise_id): - return [ - {"identifier": "core/promise_cancel", - "payload": {"promise_id": promise_id}} - ] + return [{ + "identifier": "core/promise_cancel", + "payload": {"promise_id": promise_id} + }] async def send_messages(websocket, message): try: print(f">>> Отправка сообщения: {json.dumps(message, indent=4)}") await websocket.send(json.dumps(message)) - await asyncio.sleep(0) except Exception: logging.error(traceback.format_exc()) + await websocket.close() async def receive_messages(websocket, auth_dict): try: - promise_id = 2 # id для идентификации вызовов + promise_id = 2 ssrc = SSRC - call_mapi_initialized = False voip_port = API_PORT + call_mapi_initialized = False + source_id = auth_dict.get("client_id") + async for message in websocket: message_from_json = json.loads(message) for message_item in message_from_json: - voice_call = await get_voice_calls() print(f"<<< Ответ получен: {message_item}") identifier = message_item.get("identifier") if identifier == "core/connection_response": - print(f"Соединение установлено. Инициализация модулей...") - await send_messages(websocket, - get_call_initialize_command()) - await send_messages(websocket, - get_location_initialize_command()) + print("Соединение установлено. Инициализация модулей...") + 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()) - if identifier == "call:1/initialization_response": + 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) + voip_port = message_item["payload"].get("voip_port", API_PORT) - elif ( - identifier == "location:0/position_broadcast" - and auth_dict["wlocationsystem"] - ): - print(message_item["payload"]) + elif identifier == "core/promise_response" and message_item["payload"]["identifier"] == "call:1/transmit_response": + payload = message_item["payload"] + if payload["state"] == "granted": + voice_call = await get_voice_calls() + if not voice_call: + print("Нет доступных вызовов.") + continue + 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)) + promise_id += 1 + print("Трансляция завершена.") + elif payload["state"] == "faulted": + print(f"[ОШИБКА] Передача отклонена: {payload.get('payload', {}).get('message')}") + + elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"): await save_location(message_item["payload"]) - elif call_mapi_initialized and voice_call and auth_dict[ - "plasystem"]: - print( - "Запрос на отправку аудио. Инициализация трансляции трансляцию..." - ) - await set_voice_call_sent(voice_call) - await send_messages( - websocket, - get_transmit_command(promise_id, ssrc, - auth_dict["raduisip_group"]), - ) - print("Начало трансляции файла.") - 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)) - promise_id += 1 - print("Трансляция завершена и вызов остановлен.") + elif call_mapi_initialized and auth_dict.get("plasystem"): + voice_call = await get_voice_calls() + if voice_call: + print("Запрос на отправку аудио...") + await send_messages( + websocket, + get_transmit_command(promise_id, ssrc, auth_dict["raduisip_group"], source_id) + ) except Exception: logging.error(traceback.format_exc()) @sync_to_async def get_voice_calls(): - return VoiceCall.objects.filter(sent=False).prefetch_related( - "alarm_file").first() + return VoiceCall.objects.filter(sent=False).prefetch_related("alarm_file").first() -@sync_to_async() +@sync_to_async def set_voice_call_sent(voice_call): voice_call.sent = True voice_call.save() @@ -166,77 +162,35 @@ def create_or_update_location(data): def convert_audio_to_g711a(input_file): - """Конвертирует аудиофайл в формат G.711A (PCMA) с частотой 8000 Гц, используя ffmpeg.""" output_file = "converted_audio.g711a" command = [ - # Путь до ffmpeg если windows - "ffmpeg", - "-y", - "-i", - input_file, - "-ar", - "8000", - "-ac", - "1", - "-f", - "alaw", - output_file, - # G.711A — это a-law + "ffmpeg", "-y", "-i", input_file, "-ar", "8000", "-ac", "1", "-f", "alaw", output_file ] - - # Выполнение команды ffmpeg для конвертации subprocess.run(command, check=True) - - # Чтение G.711A данных для передачи with open(output_file, "rb") as f: audio_data = f.read() - - # Удаление временного файла os.remove(output_file) - return audio_data async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc): - """Отправка аудио по RTP с правильным заголовком и G.711A кодеком.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sequence_number = 0 timestamp = 0 - - print("Начинаем отправку аудио по RTP...") - # Конвертируем аудио в G.711A audio_data = convert_audio_to_g711a(audio_path) - - # Отправляем пакеты с размером для 20 мс - packet_size = 160 # 160 байт для 20 мс при 8000 Гц с G.711A (8 бит на сэмпл) - - start_time = time.time() # время начала потока для синхронизации + packet_size = 160 + start_time = time.time() for i in range(0, len(audio_data), packet_size): - frame_data = audio_data[i: i + packet_size] + frame_data = audio_data[i:i+packet_size] if not frame_data: - print("Достигнут конец файла аудио.") break - - # Создаем RTP пакет с заголовком - rtp_packet = ( - struct.pack( - "!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, - timestamp, ssrc - ) - + frame_data - ) + rtp_packet = struct.pack("!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc) + frame_data sock.sendto(rtp_packet, (dest_ip, dest_port)) - sequence_number += 1 timestamp += packet_size - # Обновляем таймстамп на количество байт (160 байт для 20 мс при G.711A) - - # Расчет времени для отправки следующего пакета - next_packet_time = start_time + ( - sequence_number * PACKET_DURATION_MS / 1000) - delay = max(0, next_packet_time - time.time()) - time.sleep(delay) + delay = max(0, start_time + (sequence_number * PACKET_DURATION_MS / 1000) - time.time()) + await asyncio.sleep(delay) sock.close() print("Передача аудиофайла завершена.") @@ -257,54 +211,45 @@ def get_settings_from_db(): "radiusip_api_key": get_settings(prefix + "token", ""), "radiusip_login": get_settings(prefix + "login", ""), "radiusip_password": get_settings(prefix + "pass", ""), - "raduisip_group": get_settings( - prefix + "group", "dmr:1@groups.17826016.global" - ), - "wlocationsystem": True if wlocationsystem == "Radiusip" else False, - "plasystem": True if plasystem == "Radiusip" else False, + "raduisip_group": get_settings(prefix + "group", "dmr:1@groups.17826016.global"), + "wlocationsystem": wlocationsystem == "Radiusip", + "plasystem": plasystem == "Radiusip", } async def main(): auth_dict = await get_settings_from_db() uri = f"ws://{auth_dict['radiusip_host_ws']}:{auth_dict['radiusip_port_ws']}/" - connection_request = [ - { - "identifier": "core/connection_request", - "payload": { - "login": auth_dict["radiusip_login"], - "password": auth_dict["radiusip_password"], - "api_key": auth_dict["radiusip_api_key"], - "token": None, - }, + connection_request = [{ + "identifier": "core/connection_request", + "payload": { + "login": auth_dict["radiusip_login"], + "password": auth_dict["radiusip_password"], + "api_key": auth_dict["radiusip_api_key"], + "token": None } - ] + }] + while True: try: - async with websockets.connect(uri) as websocket: + 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) - except ( - ConnectionRefusedError, - websockets.exceptions.ConnectionClosedError - ): - print("Соединение не удалось или разорвано. " - "Повторная попытка через 5 секунд...") + except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError): + print("Соединение не удалось или разорвано. Повтор через 5 секунд...") await asyncio.sleep(5) except Exception as e: print(f"Ошибка: {e}") - await asyncio.sleep( - 10) # Большее время ожидания при неизвестной ошибке + await asyncio.sleep(10) if __name__ == "__main__": - project_root = os.path.abspath( - os.path.join(os.path.dirname(__file__), '../../../')) + project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')) sys.path.append(project_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mfssogr.settings") - django.setup() + from apps.general.views.settingsmodule import get_settings from apps.pla.models.model_voice_call import VoiceCall from apps.workerslocation.models.workers_locations import WorkersLocation