Повтороная отправка при неудачной отправке

This commit is contained in:
zakhy 2025-04-21 10:06:05 +07:00
parent c7a7c3edc4
commit 5cd2a3f7c7

View File

@ -18,6 +18,8 @@ API_PORT = 18500
SSRC = 269484035
RTP_PAYLOAD_TYPE = 8
PACKET_DURATION_MS = 20
MAX_RETRY_ATTEMPTS = 3
RETRY_DELAY_SECONDS = 2
def log(msg):
@ -83,6 +85,8 @@ async def receive_messages(websocket, auth_dict):
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:
@ -104,22 +108,26 @@ async def receive_messages(websocket, auth_dict):
elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"):
await save_location(message_item["payload"])
a = {'identifier': 'call:1/participant_state_broadcast',
'payload': {'composite_call_id': 79333,
'participant_call_id': 79335,
'state': 'own_tx', 'channel_id': 18874592,
'source': 'dmr:65280@subscribers.global',
'target': 'dmr:1@groups.18874592.global',
'modifier': 'not',
'state_change_reason': 'none'}}
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("[ОШИБКА] Передача отклонена сервером.")
waiting_for_grant = False
current_voice_call = None
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':
@ -131,12 +139,14 @@ 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))
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:
@ -147,6 +157,8 @@ async def receive_messages(websocket, auth_dict):
)
current_voice_call = voice_call
waiting_for_grant = True
promise_granted = False
retry_attempts = 0
except Exception:
logging.error(traceback.format_exc())
@ -196,12 +208,11 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sequence_number = 0
timestamp = 0
packet_size = 160 # 20 мс аудио @ 8000 Гц = 160 байт
timestamp_increment = packet_size # 160 семплов при 20 мс, 8000 Гц
packet_size = 160
timestamp_increment = packet_size
audio_data = convert_audio_to_g711a(audio_path)
duration_sec = len(audio_data) / 8000 # 8000 байт/сек при G.711A
duration_sec = len(audio_data) / 8000
log(f"Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки.")
log("Начинаем отправку аудио по RTP...")
@ -212,8 +223,8 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
break
rtp_header = struct.pack("!BBHII",
0x80, # Version(2), Padding(0), Extension(0), CSRC count(0)
RTP_PAYLOAD_TYPE, # Marker(0), Payload Type (8 — G.711A)
0x80,
RTP_PAYLOAD_TYPE,
sequence_number,
timestamp,
ssrc)
@ -224,7 +235,7 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
sequence_number = (sequence_number + 1) % 65536
timestamp = (timestamp + timestamp_increment) % (2**32)
await asyncio.sleep(PACKET_DURATION_MS / 1000) # 20 мс
await asyncio.sleep(PACKET_DURATION_MS / 1000)
sock.close()
log("Передача аудиофайла завершена.")