From 13edeec48149332fa371ac1856fdefb42fd0dbb4 Mon Sep 17 00:00:00 2001 From: zakhy Date: Wed, 30 Oct 2024 15:56:13 +0700 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=B5?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/transmit_file_to_radio.py | 298 ++++++++++++++++++ 1 file changed, 298 insertions(+) create mode 100644 apps/workerslocation/commands/transmit_file_to_radio.py diff --git a/apps/workerslocation/commands/transmit_file_to_radio.py b/apps/workerslocation/commands/transmit_file_to_radio.py new file mode 100644 index 0000000..c57b5c5 --- /dev/null +++ b/apps/workerslocation/commands/transmit_file_to_radio.py @@ -0,0 +1,298 @@ +import asyncio +import json +import socket +import struct +import subprocess +import time +import os + +import django +import websockets +import datetime + +from asgiref.sync import sync_to_async +from pydub import AudioSegment + +# Настройки для WebSocket и RTP + +API_HOST = '192.168.51.163' +API_PORT = 18500 +SSRC = 269484035 # SSRC, полученный из ответа +RTP_PAYLOAD_TYPE = 8 # G.711A, как указано в ответе +PACKET_DURATION_MS = 20 # Длительность пакета 20 мс + + +class FileConverter: + """ + Конвертирует аудиофайлы под кодек + """ + + @classmethod + def convert_audio_to_g711a(cls, input_file): + """Конвертирует аудиофайл в формат G.711A (PCMA) с частотой 8000 Гц, используя ffmpeg.""" + output_file = "converted_audio.g711a" + command = [ + "C:\\ffmpeg\\bin\\ffmpeg.exe", "-y", "-i", input_file, + "-ar", "8000", "-ac", "1", "-f", "alaw", output_file # G.711A — это a-law + ] + + # Выполнение команды 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 + + +class FileTransmitter: + """ + Отправляет файл на сервер по RTP + """ + # G.711A, как указано в ответе + RTP_PAYLOAD_TYPE = 8 + # Длительность пакета 20 мс + PACKET_DURATION_MS = 20 + + def __init__(self, api_host, audio_path, rtp_port=18500, ssrc=269484035): + self.api_host = api_host + self.RTP_port = rtp_port + self.ssrc = ssrc + self.audio_path = audio_path + + async def start_audio_stream(self): + """Отправка аудио по RTP с правильным заголовком и G.711A кодеком.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sequence_number = 0 + timestamp = 0 + + print("Начинаем отправку аудио по RTP...") + # Конвертируем аудио в G.711A + audio_data = FileConverter.convert_audio_to_g711a(self.audio_path) + + # 160 байт для 20 мс при 8000 Гц с G.711A (8 бит на сэмпл) + 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] + if not frame_data: + print("Достигнут конец файла аудио.") + break + + # Создаем RTP пакет с заголовком + rtp_packet = struct.pack("!BBHII", 0x80, self.RTP_PAYLOAD_TYPE, sequence_number, + timestamp, self.ssrc) + frame_data + sock.sendto(rtp_packet, (self.api_host, self.RTP_port)) + + sequence_number += 1 + # Обновить таймстамп на количество байт (160 байт для 20 мс при G.711A) + timestamp += packet_size + + # Расчет времени для отправки следующего пакета + next_packet_time = start_time + (sequence_number * self.PACKET_DURATION_MS / 1000) + delay = max(0, next_packet_time - time.time()) + time.sleep(delay) + + sock.close() + print("Передача аудиофайла завершена.") + + @classmethod + def get_transmit_command(cls, promise_id, ssrc): + return [{ + "identifier": "call:1/transmit_request", + "payload": { + "promise_id": promise_id, + "target": "dmr:1@groups.17826016.global", + "modifier": "not", + "voip_ssrc": ssrc + } + }] + + @classmethod + def get_promise_cancel_command(cls, promise_id): + return [{ + "identifier": "core/promise_cancel", + "payload": { + "promise_id": promise_id + } + }] + + def transmit(self): + self.start_audio_stream() + + +def get_initialize_command(): + return [{ + "identifier": "call:1/initialization_request", + "payload": { + "voip_port": 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): + return [{ + "identifier": "call:1/transmit_request", + "payload": { + "promise_id": promise_id, + "target": "dmr:1@groups.17826016.global", + "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): + print(f"{datetime.datetime.now().time()} >>> Отправка сообщения: {json.dumps(message, indent=4)}") + await websocket.send(json.dumps(message)) + await asyncio.sleep(0) + + +async def receive_messages(websocket, audio_path): + promise_id = 4 + ssrc = SSRC + voip_port = API_PORT + async for message in websocket: + print(f"{datetime.datetime.now().time()} <<< Ответ получен: {message}") + data = json.loads(message) + identifier = data[0].get('identifier') + + if identifier == 'core/connection_response': + print("Соединение установлено. Инициализация вызова...") + await send_messages(websocket, get_initialize_command()) + + elif len(data) > 1: + if data[1]['identifier'] == 'call:1/initialization_response': + ssrc = data[1]['payload'].get('voip_ssrc', SSRC) + voip_port = data[1]['payload'].get('voip_port', API_PORT) + # elif "object unsent": + print("Запрос на отправку аудио. Запрос на трансляцию...") + await send_messages(websocket, get_transmit_command(promise_id, ssrc)) + elif identifier == 'call:1/composite_state_broadcast': + ssrc = data[0]['payload']['active_ssrc'] + await start_audio_stream(audio_path, API_HOST, voip_port, ssrc) + await send_messages(websocket, get_promise_cancel_command(promise_id)) + print("Трансляция завершена и вызов остановлен.") + break + + +def convert_audio_to_g711a(input_file): + """Конвертирует аудиофайл в формат G.711A (PCMA) с частотой 8000 Гц, используя ffmpeg.""" + output_file = "converted_audio.g711a" + command = [ + "C:\\ffmpeg\\bin\\ffmpeg.exe", "-y", "-i", input_file, + "-ar", "8000", "-ac", "1", "-f", "alaw", output_file # G.711A — это a-law + ] + + # Выполнение команды 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() # время начала потока для синхронизации + + for i in range(0, len(audio_data), 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 + 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) + + sock.close() + print("Передача аудиофайла завершена.") + + +@sync_to_async +def get_settings_from_db(): + return { + 'radiusip_host_ws': get_settings('radiusip_host_ws', ''), + 'radiusip_port_ws': get_settings('radiusip_port_ws', ''), + 'radiusip_api_key': get_settings('radiusip_api_key', ''), + 'radiusip_login': get_settings('radiusip_login', ''), + 'radiusip_password': get_settings('radiusip_password', '') + } + + +async def main(): + auth_dict = await get_settings_from_db() + uri = "ws://192.168.51.163:8191/" + 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 + } + }] + + async with websockets.connect(uri) as websocket: + await send_messages(websocket, connection_request) + await receive_messages(websocket, os.path.join(settings.MEDIA_ROOT + 'sound/sound.wav')) + + +if __name__ == '__main__': + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mfssogr.settings') + + django.setup() + from django.conf import settings + from apps.general.views.settingsmodule import get_settings + + asyncio.run(main())