Фикс uid

This commit is contained in:
zakhy 2025-04-21 17:45:19 +07:00
parent fe545d3517
commit c725be3afc

View File

@ -74,102 +74,98 @@ 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
current_channel = None
async for message in websocket:
message_from_json = json.loads(message)
for item in message_from_json:
identifier = item.get("identifier")
for message_item in message_from_json:
identifier = message_item.get("identifier")
if identifier != "location:0/position_broadcast":
log(f"<<< Ответ получен: {item}")
log(f"<<< Ответ получен: {message_item}")
if identifier == "core/connection_response":
log("Соединение установлено. Инициализация модулей...")
auth_dict["client_id"] = item["payload"].get("client_id")
source_id = message_item["payload"].get("client_id")
auth_dict["client_id"] = source_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)
ssrc = message_item["payload"].get("voip_ssrc", SSRC)
voip_port = message_item["payload"].get("voip_port", API_PORT)
elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"):
await save_location(item["payload"])
await save_location(message_item["payload"])
elif call_mapi_initialized and auth_dict.get("plasystem"):
elif identifier == "core/promise_response" and waiting_for_grant:
payload = message_item["payload"]
log(f"Статус promise_id={payload.get('promise_id')} → {payload.get('state')}")
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, current_channel, 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"]
log(f"Состояние участника вызова: composite_call_id={payload.get('composite_call_id')}, "
f"participant_call_id={payload.get('participant_call_id')}, state={payload.get('state')}")
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:
voice_call = await get_voice_calls()
if voice_call:
for channel in voice_call.channels.all():
success = await handle_channel_transmission(
channel.uid,
voice_call,
for ch in voice_call.channels.all():
channel = ch.uid
log(f"Запрос на отправку аудио по каналу: {channel}")
await send_messages(
websocket,
auth_dict,
promise_id
get_transmit_command(promise_id, ssrc, channel, source_id)
)
promise_id += 1
await set_voice_call_sent(voice_call)
current_voice_call = voice_call
current_channel = channel
waiting_for_grant = True
promise_granted = False
retry_attempts = 0
except Exception:
logging.error(traceback.format_exc())
@ -225,20 +221,28 @@ 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...")
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)
await asyncio.sleep(PACKET_DURATION_MS / 1000)
sock.close()
log("Передача аудиофайла завершена.")