multiproccess заход
This commit is contained in:
parent
4c6145661f
commit
4fe2474252
79
apps/workerslocation/commands/audio_sender.py
Normal file
79
apps/workerslocation/commands/audio_sender.py
Normal file
@ -0,0 +1,79 @@
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import os
|
||||
import sys
|
||||
import datetime
|
||||
import time
|
||||
|
||||
RTP_PAYLOAD_TYPE = 8
|
||||
PACKET_DURATION_MS = 20
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(
|
||||
f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}", flush=True
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
]
|
||||
subprocess.run(command, check=True)
|
||||
with open(output_file, "rb") as f:
|
||||
audio_data = f.read()
|
||||
os.remove(output_file)
|
||||
return audio_data
|
||||
|
||||
|
||||
def start_audio_stream(audio_path, dest_ip, dest_port, ssrc, channel):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sequence_number = 0
|
||||
timestamp = 0
|
||||
packet_size = 160
|
||||
timestamp_increment = packet_size
|
||||
audio_data = convert_audio_to_g711a(audio_path)
|
||||
|
||||
duration_sec = len(audio_data) / 8000
|
||||
log(
|
||||
f"[{channel}] Подготовлено {len(audio_data)} байт аудио (~{duration_sec:.2f} сек) для отправки."
|
||||
)
|
||||
log(f"[{channel}] Начинаем отправку аудио по RTP...")
|
||||
|
||||
for i in range(0, len(audio_data), 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_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)
|
||||
time.sleep(PACKET_DURATION_MS / 1000)
|
||||
|
||||
sock.close()
|
||||
log(f"[{channel}] Передача аудиофайла завершена.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
audio_path = sys.argv[1]
|
||||
dest_ip = sys.argv[2]
|
||||
dest_port = int(sys.argv[3])
|
||||
ssrc = int(sys.argv[4])
|
||||
channel = sys.argv[5]
|
||||
start_audio_stream(audio_path, dest_ip, dest_port, ssrc, channel)
|
||||
@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
import json
|
||||
import multiprocessing
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
@ -26,19 +27,23 @@ 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():
|
||||
@ -46,23 +51,24 @@ 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):
|
||||
@ -74,19 +80,21 @@ 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
|
||||
async def handle_channel_transmission(
|
||||
channel, voice_call, websocket, auth_dict, promise_id_start, 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:
|
||||
@ -96,10 +104,14 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
|
||||
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
|
||||
@ -111,23 +123,33 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
|
||||
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}] Условия выполнены. Стартуем трансляцию")
|
||||
await start_audio_stream(
|
||||
voice_call.alarm_file.audio_file.path,
|
||||
auth_dict["radiusip_host_ws"],
|
||||
API_PORT,
|
||||
ssrc
|
||||
|
||||
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 send_messages(websocket, get_promise_cancel_command(promise_id))
|
||||
return True
|
||||
process.start()
|
||||
process.join()
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
log(f"[{channel}] Timeout ожидания. Ретрай...")
|
||||
retry_due_to_timeout = True
|
||||
|
||||
retry_attempts += 1
|
||||
promise_id += 1
|
||||
@ -155,14 +177,16 @@ 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 ch in voice_call.channels.all():
|
||||
for index, ch in enumerate(voice_call.channels.all()):
|
||||
channel = ch.uid
|
||||
ssrc = SSRC + index # генерируем уникальный SSRC
|
||||
success = await handle_channel_transmission(
|
||||
channel,
|
||||
voice_call,
|
||||
websocket,
|
||||
auth_dict,
|
||||
promise_id
|
||||
promise_id,
|
||||
ssrc,
|
||||
)
|
||||
promise_id += 1
|
||||
await set_voice_call_sent(voice_call)
|
||||
@ -177,7 +201,9 @@ 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:
|
||||
@ -186,7 +212,11 @@ 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
|
||||
@ -216,7 +246,17 @@ 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:
|
||||
@ -234,15 +274,19 @@ 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
|
||||
@ -268,7 +312,9 @@ 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",
|
||||
}
|
||||
@ -277,19 +323,23 @@ 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):
|
||||
@ -301,7 +351,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")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user