Поддержка отправления по нескольким каналам
This commit is contained in:
parent
b0750c0966
commit
7d1b0d33c0
@ -6,7 +6,6 @@ import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import django
|
||||
@ -75,97 +74,109 @@ 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"]
|
||||
promise_id = promise_id_start
|
||||
retry_attempts = 0
|
||||
|
||||
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
|
||||
|
||||
try:
|
||||
while True:
|
||||
raw = await asyncio.wait_for(websocket.recv(), timeout=5)
|
||||
message_items = json.loads(raw)
|
||||
|
||||
for item in message_items:
|
||||
identifier = item.get("identifier")
|
||||
payload = item.get("payload")
|
||||
|
||||
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 == "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_attempts += 1
|
||||
promise_id += 1
|
||||
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
|
||||
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
|
||||
|
||||
async for message in websocket:
|
||||
message_from_json = json.loads(message)
|
||||
for message_item in message_from_json:
|
||||
identifier = message_item.get("identifier")
|
||||
for item in message_from_json:
|
||||
identifier = item.get("identifier")
|
||||
if identifier != "location:0/position_broadcast":
|
||||
log(f"<<< Ответ получен: {message_item}")
|
||||
log(f"<<< Ответ получен: {item}")
|
||||
|
||||
if identifier == "core/connection_response":
|
||||
log("Соединение установлено. Инициализация модулей...")
|
||||
source_id = message_item["payload"].get("client_id")
|
||||
auth_dict["client_id"] = source_id
|
||||
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 = message_item["payload"].get("voip_ssrc", SSRC)
|
||||
voip_port = message_item["payload"].get("voip_port", API_PORT)
|
||||
ssrc = item["payload"].get("voip_ssrc", SSRC)
|
||||
|
||||
elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"):
|
||||
await save_location(message_item["payload"])
|
||||
await save_location(item["payload"])
|
||||
|
||||
elif identifier == "core/promise_response" and waiting_for_grant:
|
||||
payload = message_item["payload"]
|
||||
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, auth_dict["raduisip_group"], 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"]
|
||||
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:
|
||||
elif call_mapi_initialized and auth_dict.get("plasystem"):
|
||||
voice_call = await get_voice_calls()
|
||||
if voice_call:
|
||||
log("Запрос на отправку аудио...")
|
||||
await send_messages(
|
||||
websocket,
|
||||
get_transmit_command(promise_id, ssrc, auth_dict["raduisip_group"], source_id)
|
||||
)
|
||||
current_voice_call = voice_call
|
||||
waiting_for_grant = True
|
||||
promise_granted = False
|
||||
retry_attempts = 0
|
||||
for channel in voice_call.channels.all():
|
||||
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").first()
|
||||
return VoiceCall.objects.filter(sent=False).prefetch_related("alarm_file", "channels").first()
|
||||
|
||||
|
||||
@sync_to_async
|
||||
@ -214,28 +225,20 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
|
||||
|
||||
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:
|
||||
log("Достигнут конец файла аудио.")
|
||||
break
|
||||
|
||||
rtp_header = struct.pack("!BBHII",
|
||||
0x80,
|
||||
RTP_PAYLOAD_TYPE,
|
||||
sequence_number,
|
||||
timestamp,
|
||||
ssrc)
|
||||
|
||||
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("Передача аудиофайла завершена.")
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user