Лог с секундами

This commit is contained in:
zakhy 2025-04-18 08:42:56 +07:00
parent 1308de7123
commit 4504d28cc4

View File

@ -20,6 +20,10 @@ RTP_PAYLOAD_TYPE = 8
PACKET_DURATION_MS = 20
def log(msg):
print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}")
def get_call_initialize_command():
return [{
"identifier": "call:1/initialization_request",
@ -62,7 +66,7 @@ def get_promise_cancel_command(promise_id):
async def send_messages(websocket, message):
try:
print(f">>> Отправка сообщения: {json.dumps(message, indent=4)}")
log(f">>> Отправка сообщения: {json.dumps(message, indent=4)}")
await websocket.send(json.dumps(message))
except Exception:
logging.error(traceback.format_exc())
@ -82,11 +86,11 @@ async def receive_messages(websocket, auth_dict):
async for message in websocket:
message_from_json = json.loads(message)
for message_item in message_from_json:
print(f"<<< Ответ получен: {message_item}")
log(f"<<< Ответ получен: {message_item}")
identifier = message_item.get("identifier")
if identifier == "core/connection_response":
print("Соединение установлено. Инициализация модулей...")
log("Соединение установлено. Инициализация модулей...")
source_id = message_item["payload"].get("client_id")
auth_dict["client_id"] = source_id
await send_messages(websocket, get_call_initialize_command())
@ -103,7 +107,7 @@ async def receive_messages(websocket, auth_dict):
elif identifier == "core/promise_response" and message_item["payload"].get("identifier") == "call:1/transmit_response":
payload = message_item["payload"]
if payload["state"] == "granted" and current_voice_call:
print("Разрешение получено. Начинаем трансляцию...")
log("Разрешение получено. Начинаем трансляцию...")
await set_voice_call_sent(current_voice_call)
await start_audio_stream(
current_voice_call.alarm_file.audio_file.path,
@ -112,19 +116,19 @@ async def receive_messages(websocket, auth_dict):
ssrc
)
await send_messages(websocket, get_promise_cancel_command(promise_id))
print("Трансляция завершена и вызов остановлен.")
log("Трансляция завершена и вызов остановлен.")
promise_id += 1
waiting_for_grant = False
current_voice_call = None
elif payload["state"] == "faulted":
print("[ОШИБКА] Передача отклонена сервером.")
log("[ОШИБКА] Передача отклонена сервером.")
waiting_for_grant = False
current_voice_call = None
elif call_mapi_initialized and auth_dict.get("plasystem") and not waiting_for_grant:
voice_call = await get_voice_calls()
if voice_call:
print("Запрос на отправку аудио...")
log("Запрос на отправку аудио...")
await send_messages(
websocket,
get_transmit_command(promise_id, ssrc, auth_dict["raduisip_group"], source_id)
@ -184,9 +188,11 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
packet_size = 160
start_time = time.time()
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_packet = struct.pack("!BBHII", 0x80, RTP_PAYLOAD_TYPE, sequence_number, timestamp, ssrc) + frame_data
sock.sendto(rtp_packet, (dest_ip, dest_port))
@ -196,7 +202,7 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
await asyncio.sleep(delay)
sock.close()
print("Передача аудиофайла завершена.")
log("Передача аудиофайла завершена.")
@sync_to_async
@ -239,10 +245,10 @@ async def main():
await send_messages(websocket, connection_request)
await receive_messages(websocket, auth_dict)
except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError):
print("Соединение не удалось или разорвано. Повтор через 5 секунд...")
log("Соединение не удалось или разорвано. Повтор через 5 секунд...")
await asyncio.sleep(5)
except Exception as e:
print(f"Ошибка: {e}")
log(f"Ошибка: {e}")
await asyncio.sleep(10)