This commit is contained in:
zakhy 2025-04-21 18:02:02 +07:00
parent 4b14c1f002
commit 2deaa56c3a

View File

@ -74,6 +74,106 @@ 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
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")
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 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", "channels").first()
@ -125,76 +225,24 @@ 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("Передача аудиофайла завершена.")
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 = ""
@ -233,17 +281,7 @@ async def main():
try:
async with websockets.connect(uri, ping_interval=20, ping_timeout=10) as websocket:
await send_messages(websocket, connection_request)
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)
await receive_messages(websocket, auth_dict)
except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError):
log("Соединение не удалось или разорвано. Повтор через 5 секунд...")
await asyncio.sleep(5)