This commit is contained in:
zakhy 2025-04-22 14:31:42 +07:00
parent 5f249a28c6
commit 45f63b8c95

View File

@ -1,7 +1,6 @@
import asyncio
import datetime
import json
import multiprocessing
import os
import socket
import struct
@ -27,23 +26,19 @@ def log(msg):
def get_call_initialize_command():
return [
{
"identifier": "call:1/initialization_request",
"payload": {
"voip_port": str(API_PORT),
"supported_codecs": [
{
"codec_id": RTP_PAYLOAD_TYPE,
"name": "G711A",
"packet_duration": PACKET_DURATION_MS,
"sampling_rate": 8000,
}
],
"is_supported_webrtc": False,
},
return [{
"identifier": "call:1/initialization_request",
"payload": {
"voip_port": str(API_PORT),
"supported_codecs": [{
"codec_id": RTP_PAYLOAD_TYPE,
"name": "G711A",
"packet_duration": PACKET_DURATION_MS,
"sampling_rate": 8000
}],
"is_supported_webrtc": False
}
]
}]
def get_location_initialize_command():
@ -51,24 +46,23 @@ def get_location_initialize_command():
def get_transmit_command(promise_id, ssrc, target, source):
return [
{
"identifier": "call:1/transmit_request",
"payload": {
"promise_id": promise_id,
"source": source,
"target": target,
"modifier": "not",
"voip_ssrc": ssrc,
},
return [{
"identifier": "call:1/transmit_request",
"payload": {
"promise_id": promise_id,
"source": source,
"target": target,
"modifier": "not",
"voip_ssrc": ssrc
}
]
}]
def get_promise_cancel_command(promise_id):
return [
{"identifier": "core/promise_cancel", "payload": {"promise_id": promise_id}}
]
return [{
"identifier": "core/promise_cancel",
"payload": {"promise_id": promise_id}
}]
async def send_messages(websocket, message):
@ -80,21 +74,19 @@ async def send_messages(websocket, message):
await websocket.close()
async def handle_channel_transmission(
channel, voice_call, websocket, auth_dict, promise_id_start, ssrc
):
async def handle_channel_transmission(channel, voice_call, websocket, auth_dict, promise_id_start):
ssrc = SSRC
source_id = auth_dict["client_id"]
retry_attempts = 0
promise_id = promise_id_start
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)
)
await send_messages(websocket, get_transmit_command(promise_id, ssrc, channel, source_id))
promise_granted = False
own_tx_received = False
retry_due_to_timeout = False
try:
while True:
@ -104,14 +96,10 @@ async def handle_channel_transmission(
for item in message_items:
identifier = item.get("identifier")
payload = item.get("payload")
if identifier != "location:0/position_broadcast":
log(f"<<< Ответ получен: {item}")
if (
identifier == "core/promise_response"
and payload.get("promise_id") == promise_id
):
if identifier == "core/promise_response" and payload.get("promise_id") == promise_id:
state = payload.get("state")
if state == "granted":
promise_granted = True
@ -123,32 +111,23 @@ async def handle_channel_transmission(
break
elif identifier == "call:1/participant_state_broadcast":
if payload.get("state") == "own_tx" and "65280" in payload.get(
"source", ""
):
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}] Условия выполнены. Стартуем трансляцию")
process = multiprocessing.Process(
target=subprocess.run,
args=(
[
sys.executable, # путь к Python
"apps/workerslocation/commands/audio_sender.py", # путь к файлу
voice_call.alarm_file.audio_file.path,
auth_dict["radiusip_host_ws"],
str(API_PORT),
str(ssrc),
str(channel),
],
),
await start_audio_stream(
voice_call.alarm_file.audio_file.path,
auth_dict["radiusip_host_ws"],
API_PORT,
ssrc
)
process.start()
await send_messages(websocket, get_promise_cancel_command(promise_id))
return True
except asyncio.TimeoutError:
log(f"[{channel}] Timeout ожидания. Ретрай...")
retry_due_to_timeout = True
retry_attempts += 1
promise_id += 1
@ -176,16 +155,14 @@ async def receive_messages(websocket, auth_dict):
if call_mapi_initialized and auth_dict.get("plasystem"):
voice_call = await get_voice_calls()
if voice_call:
for index, ch in enumerate(voice_call.channels.all()):
for ch in voice_call.channels.all():
channel = ch.uid
ssrc = SSRC + index # генерируем уникальный SSRC
success = await handle_channel_transmission(
channel,
voice_call,
websocket,
auth_dict,
promise_id,
ssrc,
promise_id
)
promise_id += 1
await set_voice_call_sent(voice_call)
@ -200,9 +177,7 @@ async def receive_messages(websocket, auth_dict):
call_mapi_initialized = True
ssrc = item["payload"].get("voip_ssrc", SSRC)
elif identifier == "location:0/position_broadcast" and auth_dict.get(
"wlocationsystem"
):
elif identifier == "location:0/position_broadcast" and auth_dict.get("wlocationsystem"):
await save_location(item["payload"])
except Exception:
@ -211,11 +186,7 @@ async def receive_messages(websocket, auth_dict):
@sync_to_async
def get_voice_calls():
return (
VoiceCall.objects.filter(sent=False)
.prefetch_related("alarm_file", "channels")
.first()
)
return VoiceCall.objects.filter(sent=False).prefetch_related("alarm_file", "channels").first()
@sync_to_async
@ -245,17 +216,7 @@ def create_or_update_location(data):
def convert_audio_to_g711a(input_file):
output_file = "converted_audio.g711a"
command = [
"ffmpeg",
"-y",
"-i",
input_file,
"-ar",
"8000",
"-ac",
"1",
"-f",
"alaw",
output_file,
"ffmpeg", "-y", "-i", input_file, "-ar", "8000", "-ac", "1", "-f", "alaw", output_file
]
subprocess.run(command, check=True)
with open(output_file, "rb") as f:
@ -273,19 +234,15 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
audio_data = convert_audio_to_g711a(audio_path)
duration_sec = len(audio_data) / 8000
log(
f"Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки."
)
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]
frame_data = audio_data[i:i+packet_size]
if not frame_data:
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
@ -311,9 +268,7 @@ def get_settings_from_db():
"radiusip_api_key": get_settings(prefix + "token", ""),
"radiusip_login": get_settings(prefix + "login", ""),
"radiusip_password": get_settings(prefix + "pass", ""),
"raduisip_group": get_settings(
prefix + "group", "dmr:1@groups.17826016.global"
),
"raduisip_group": get_settings(prefix + "group", "dmr:1@groups.17826016.global"),
"wlocationsystem": wlocationsystem == "Radiusip",
"plasystem": plasystem == "Radiusip",
}
@ -322,23 +277,19 @@ def get_settings_from_db():
async def main():
auth_dict = await get_settings_from_db()
uri = f"ws://{auth_dict['radiusip_host_ws']}:{auth_dict['radiusip_port_ws']}/"
connection_request = [
{
"identifier": "core/connection_request",
"payload": {
"login": auth_dict["radiusip_login"],
"password": auth_dict["radiusip_password"],
"api_key": auth_dict["radiusip_api_key"],
"token": None,
},
connection_request = [{
"identifier": "core/connection_request",
"payload": {
"login": auth_dict["radiusip_login"],
"password": auth_dict["radiusip_password"],
"api_key": auth_dict["radiusip_api_key"],
"token": None
}
]
}]
while True:
try:
async with websockets.connect(
uri, ping_interval=20, ping_timeout=10
) as websocket:
async with websockets.connect(uri, ping_interval=20, ping_timeout=10) as websocket:
await send_messages(websocket, connection_request)
await receive_messages(websocket, auth_dict)
except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedError):
@ -350,7 +301,7 @@ async def main():
if __name__ == "__main__":
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))
sys.path.append(project_root)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mfssogr.settings")