Обработка на разрыв соединения

This commit is contained in:
zakhy 2025-03-20 16:43:15 +07:00
parent 941a721903
commit a06fff9fe0

View File

@ -62,7 +62,8 @@ def get_transmit_command(promise_id, ssrc, target):
def get_promise_cancel_command(promise_id):
return [
{"identifier": "core/promise_cancel", "payload": {"promise_id": promise_id}}
{"identifier": "core/promise_cancel",
"payload": {"promise_id": promise_id}}
]
@ -90,29 +91,34 @@ async def receive_messages(websocket, auth_dict):
if identifier == "core/connection_response":
print(f"Соединение установлено. Инициализация модулей...")
await send_messages(websocket, get_call_initialize_command())
await send_messages(websocket, get_location_initialize_command())
await send_messages(websocket,
get_call_initialize_command())
await send_messages(websocket,
get_location_initialize_command())
if 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"]
identifier == "location:0/position_broadcast"
and auth_dict["wlocationsystem"]
):
print(message_item["payload"])
await save_location(message_item["payload"])
elif call_mapi_initialized and voice_call and auth_dict["plasystem"]:
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"]),
get_transmit_command(promise_id, ssrc,
auth_dict["raduisip_group"]),
)
print("Начало трансляции файла.")
await start_audio_stream(
@ -121,15 +127,18 @@ async def receive_messages(websocket, auth_dict):
voip_port,
ssrc,
)
await send_messages(websocket, get_promise_cancel_command(promise_id))
await send_messages(websocket,
get_promise_cancel_command(promise_id))
promise_id += 1
print("Трансляция завершена и вызов остановлен.")
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()
@ -204,17 +213,18 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
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
struct.pack(
"!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number,
timestamp, ssrc
)
+ frame_data
)
sock.sendto(rtp_packet, (dest_ip, dest_port))
@ -223,7 +233,8 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
# Обновляем таймстамп на количество байт (160 байт для 20 мс при G.711A)
# Расчет времени для отправки следующего пакета
next_packet_time = start_time + (sequence_number * PACKET_DURATION_MS / 1000)
next_packet_time = start_time + (
sequence_number * PACKET_DURATION_MS / 1000)
delay = max(0, next_packet_time - time.time())
time.sleep(delay)
@ -268,10 +279,22 @@ async def main():
},
}
]
async with websockets.connect(uri) as websocket:
await send_messages(websocket, connection_request)
await receive_messages(websocket, auth_dict)
while True:
try:
async with websockets.connect(uri) as websocket:
await send_messages(websocket, connection_request)
await receive_messages(websocket, auth_dict)
except (
ConnectionRefusedError,
websockets.exceptions.ConnectionClosedError
):
print("Соединение не удалось или разорвано. "
"Повторная попытка через 5 секунд...")
await asyncio.sleep(5)
except Exception as e:
print(f"Ошибка: {e}")
await asyncio.sleep(
10) # Большее время ожидания при неизвестной ошибке
if __name__ == "__main__":