diff --git a/apps/pla/commands/radiusip.py b/apps/pla/commands/radiusip.py deleted file mode 100644 index 6288039..0000000 --- a/apps/pla/commands/radiusip.py +++ /dev/null @@ -1,322 +0,0 @@ -import asyncio -import datetime -import json -import os -import socket -import struct -import subprocess -import sys -import traceback - -import django -import websockets -from asgiref.sync import sync_to_async -from dateutil import parser - -API_PORT = 18500 -SSRC = 269484035 -RTP_PAYLOAD_TYPE = 8 -PACKET_DURATION_MS = 20 -MAX_RETRY_ATTEMPTS = 3 -RETRY_DELAY_SECONDS = 2 - - -def log(msg): - print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}") - - -def get_call_initialize_command(): - 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_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}} - ] - - -async def send_messages(websocket, message): - try: - log(f">>> Отправка сообщения: {json.dumps(message, indent=4)}") - await websocket.send(json.dumps(message)) - except Exception: - logging.error(traceback.format_exc()) - await websocket.close() - - -async def handle_channel_transmission( - channel, voice_call, websocket, auth_dict, promise_id_start -): - ssrc = SSRC - source_id = auth_dict["client_id"] - retry_attempts = 0 - promise_id = promise_id_start - - while retry_attempts < MAX_RETRY_ATTEMPTS: - log(f"[{channel}] Попытка #{retry_attempts + 1} для отправки") - await send_messages( - websocket, get_transmit_command(promise_id, ssrc, channel, source_id) - ) - - promise_granted = False - own_tx_received = False - retry_due_to_timeout = False - - try: - while True: - raw = await asyncio.wait_for(websocket.recv(), timeout=10) - message_items = json.loads(raw) - - for item in message_items: - identifier = item.get("identifier") - payload = item.get("payload") - if identifier != "location:0/position_broadcast": - log(f"<<< Ответ получен: {item}") - - if ( - identifier == "core/promise_response" - and payload.get("promise_id") == promise_id - ): - state = payload.get("state") - if state == "granted": - promise_granted = True - log(f"[{channel}] Promise granted.") - elif state == "queued": - log(f"[{channel}] Promise queued...") - elif state == "faulted": - log(f"[{channel}] Promise faulted. Ретрай...") - break - - elif identifier == "call:1/participant_state_broadcast": - if payload.get("state") == "own_tx" and "65280" in payload.get( - "source", "" - ): - own_tx_received = True - - if promise_granted and own_tx_received: - log(f"[{channel}] Условия выполнены. Стартуем трансляцию") - await start_audio_stream( - voice_call.alarm_file.audio_file.path, - auth_dict["radiusip_host_ws"], - API_PORT, - ssrc, - ) - await send_messages( - websocket, get_promise_cancel_command(promise_id) - ) - return True - - except asyncio.TimeoutError: - log(f"[{channel}] Timeout ожидания. Ретрай...") - retry_due_to_timeout = True - - retry_attempts += 1 - promise_id += 1 - if retry_attempts < MAX_RETRY_ATTEMPTS: - await asyncio.sleep(RETRY_DELAY_SECONDS) - - log(f"[{channel}] Не удалось отправить после {MAX_RETRY_ATTEMPTS} попыток.") - return False - - -async def receive_messages(websocket, auth_dict): - try: - promise_id = 2 - ssrc = SSRC - call_mapi_initialized = False - - async for message in websocket: - message_from_json = json.loads(message) - for item in message_from_json: - identifier = item.get("identifier") - log(f"<<< Ответ получен: {item}") - - if identifier == "core/connection_response": - log("Соединение установлено. Инициализация модулей...") - auth_dict["client_id"] = item["payload"].get("client_id") - await send_messages(websocket, get_call_initialize_command()) - - elif identifier == "call:1/initialization_response": - call_mapi_initialized = True - ssrc = item["payload"].get("voip_ssrc", SSRC) - - elif call_mapi_initialized and auth_dict.get("plasystem"): - voice_call = await get_voice_calls() - if voice_call: - for ch in voice_call.channels.all(): - channel = ch.uid - success = await handle_channel_transmission( - channel, voice_call, websocket, auth_dict, promise_id - ) - promise_id += 1 - await set_voice_call_sent(voice_call) - - 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() - ) - - -@sync_to_async -def set_voice_call_sent(voice_call): - voice_call.sent = True - voice_call.save() - - -def convert_audio_to_g711a(input_file): - output_file = "converted_audio.g711a" - command = [ - "ffmpeg", - "-y", - "-i", - input_file, - "-ar", - "8000", - "-ac", - "1", - "-f", - "alaw", - output_file, - ] - subprocess.run(command, check=True) - 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): - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sequence_number = 0 - timestamp = 0 - packet_size = 160 - timestamp_increment = packet_size - audio_data = convert_audio_to_g711a(audio_path) - - duration_sec = len(audio_data) / 8000 - log( - f"Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки." - ) - log("Начинаем отправку аудио по RTP...") - - for i in range(0, len(audio_data), packet_size): - frame_data = audio_data[i : i + packet_size] - if not frame_data: - break - - rtp_header = struct.pack( - "!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc - ) - rtp_packet = rtp_header + frame_data - sock.sendto(rtp_packet, (dest_ip, dest_port)) - sequence_number = (sequence_number + 1) % 65536 - timestamp = (timestamp + timestamp_increment) % (2**32) - await asyncio.sleep(PACKET_DURATION_MS / 1000) - - sock.close() - log("Передача аудиофайла завершена.") - - -@sync_to_async -def get_settings_from_db(): - prefix = "" - wlocationsystem = get_settings("wlocationsystem", "") - plasystem = get_settings("plasystem", "") - if wlocationsystem == "Radiusip": - prefix = "w" - elif plasystem == "Radiusip": - prefix = "pla" - return { - "radiusip_host_ws": get_settings(prefix + "adress", ""), - "radiusip_port_ws": get_settings(prefix + "port", "8191"), - "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": 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, - }, - } - ] - - while True: - 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) - except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError): - log("Соединение не удалось или разорвано. Повтор через 5 секунд...") - await asyncio.sleep(5) - except Exception as e: - log(f"Ошибка: {e}") - await asyncio.sleep(10) - - -if __name__ == "__main__": - 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 sabron.util import logging - - asyncio.run(main()) diff --git a/apps/workerslocation/commands/radiusip.py b/apps/workerslocation/commands/radiusip.py index e67b06b..42c2bce 100644 --- a/apps/workerslocation/commands/radiusip.py +++ b/apps/workerslocation/commands/radiusip.py @@ -2,6 +2,9 @@ import asyncio import datetime import json import os +import socket +import struct +import subprocess import sys import traceback @@ -22,11 +25,38 @@ def log(msg): print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}") +def get_call_initialize_command(): + 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, 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 [{ @@ -44,6 +74,70 @@ async def send_messages(websocket, message): await websocket.close() +async def handle_channel_transmission(channel, voice_call, websocket, auth_dict, promise_id_start): + ssrc = SSRC + source_id = auth_dict["client_id"] + retry_attempts = 0 + promise_id = promise_id_start + + while retry_attempts < MAX_RETRY_ATTEMPTS: + log(f"[{channel}] Попытка #{retry_attempts + 1} для отправки") + await send_messages(websocket, get_transmit_command(promise_id, ssrc, channel, source_id)) + + promise_granted = False + own_tx_received = False + retry_due_to_timeout = False + + try: + while True: + raw = await asyncio.wait_for(websocket.recv(), timeout=10) + message_items = json.loads(raw) + + for item in message_items: + identifier = item.get("identifier") + payload = item.get("payload") + if identifier != "location:0/position_broadcast": + log(f"<<< Ответ получен: {item}") + + if identifier == "core/promise_response" and payload.get("promise_id") == promise_id: + state = payload.get("state") + if state == "granted": + promise_granted = True + log(f"[{channel}] Promise granted.") + elif state == "queued": + log(f"[{channel}] Promise queued...") + elif state == "faulted": + log(f"[{channel}] Promise faulted. Ретрай...") + break + + elif identifier == "call:1/participant_state_broadcast": + if payload.get("state") == "own_tx" and "65280" in payload.get("source", ""): + own_tx_received = True + + if promise_granted and own_tx_received: + log(f"[{channel}] Условия выполнены. Стартуем трансляцию") + await start_audio_stream( + voice_call.alarm_file.audio_file.path, + auth_dict["radiusip_host_ws"], + API_PORT, + ssrc + ) + await send_messages(websocket, get_promise_cancel_command(promise_id)) + return True + + except asyncio.TimeoutError: + log(f"[{channel}] Timeout ожидания. Ретрай...") + retry_due_to_timeout = True + + retry_attempts += 1 + promise_id += 1 + if retry_attempts < MAX_RETRY_ATTEMPTS: + await asyncio.sleep(RETRY_DELAY_SECONDS) + + log(f"[{channel}] Не удалось отправить после {MAX_RETRY_ATTEMPTS} попыток.") + return False + + async def receive_messages(websocket, auth_dict): try: promise_id = 2 @@ -54,20 +148,52 @@ async def receive_messages(websocket, auth_dict): message_from_json = json.loads(message) for item in message_from_json: identifier = item.get("identifier") - log(f"<<< Ответ получен: {item}") + if identifier != "location:0/position_broadcast": + log(f"<<< Ответ получен: {item}") if identifier == "core/connection_response": log("Соединение установлено. Инициализация модулей...") auth_dict["client_id"] = item["payload"].get("client_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 = item["payload"].get("voip_ssrc", SSRC) + elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"): await save_location(item["payload"]) + elif call_mapi_initialized and auth_dict.get("plasystem"): + voice_call = await get_voice_calls() + if voice_call: + for ch in voice_call.channels.all(): + channel = ch.uid + success = await handle_channel_transmission( + channel, + voice_call, + websocket, + auth_dict, + promise_id + ) + promise_id += 1 + await set_voice_call_sent(voice_call) + 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() + + +@sync_to_async +def set_voice_call_sent(voice_call): + voice_call.sent = True + voice_call.save() + + async def save_location(payload): await create_or_update_location(payload) @@ -86,6 +212,46 @@ def create_or_update_location(data): ) +def convert_audio_to_g711a(input_file): + output_file = "converted_audio.g711a" + command = [ + "ffmpeg", "-y", "-i", input_file, "-ar", "8000", "-ac", "1", "-f", "alaw", output_file + ] + subprocess.run(command, check=True) + 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): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sequence_number = 0 + timestamp = 0 + packet_size = 160 + timestamp_increment = packet_size + audio_data = convert_audio_to_g711a(audio_path) + + duration_sec = len(audio_data) / 8000 + log(f"Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки.") + log("Начинаем отправку аудио по RTP...") + + for i in range(0, len(audio_data), packet_size): + frame_data = audio_data[i:i+packet_size] + if not frame_data: + break + + rtp_header = struct.pack("!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc) + rtp_packet = rtp_header + frame_data + sock.sendto(rtp_packet, (dest_ip, dest_port)) + sequence_number = (sequence_number + 1) % 65536 + timestamp = (timestamp + timestamp_increment) % (2**32) + await asyncio.sleep(PACKET_DURATION_MS / 1000) + + sock.close() + log("Передача аудиофайла завершена.") + + @sync_to_async def get_settings_from_db(): prefix = "" @@ -141,6 +307,7 @@ if __name__ == "__main__": 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 from sabron.util import logging