запись истории перемещения сотрудников
(cherry picked from commit 21482176b11f1c6ec1ec9df4106a028e369e67c8)
This commit is contained in:
parent
0770f4bb96
commit
71da692a42
@ -1,9 +1,15 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from apps.workerslocation.models.workers_locations import WorkersLocation
|
||||
from apps.workerslocation.models.workers_tracking import WorkersTracking
|
||||
|
||||
|
||||
@admin.register(WorkersLocation)
|
||||
class WorkersLocationAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "uid", "icon")
|
||||
list_editable = ("icon",)
|
||||
|
||||
|
||||
@admin.register(WorkersTracking)
|
||||
class WorkersTrackingAdmin(admin.ModelAdmin):
|
||||
list_display = ("worker", "time")
|
||||
|
||||
@ -15,6 +15,8 @@ import websockets
|
||||
from asgiref.sync import sync_to_async
|
||||
from dateutil import parser
|
||||
|
||||
from apps.workerslocation.models.workers_tracking import WorkersTracking
|
||||
|
||||
API_PORT = 18500
|
||||
SSRC = 269484035
|
||||
RTP_PAYLOAD_TYPE = 8
|
||||
@ -68,7 +70,8 @@ def get_transmit_command(promise_id, ssrc, target, source):
|
||||
|
||||
def get_promise_cancel_command(promise_id):
|
||||
return [
|
||||
{"identifier": "core/promise_cancel", "payload": {"promise_id": promise_id}}
|
||||
{"identifier": "core/promise_cancel",
|
||||
"payload": {"promise_id": promise_id}}
|
||||
]
|
||||
|
||||
|
||||
@ -117,7 +120,7 @@ def start_audio_stream_sync(audio_path, dest_ip, dest_port, ssrc):
|
||||
)
|
||||
|
||||
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(
|
||||
@ -126,13 +129,14 @@ def start_audio_stream_sync(audio_path, dest_ip, dest_port, 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)
|
||||
timestamp = (timestamp + timestamp_increment) % (2 ** 32)
|
||||
time.sleep(PACKET_DURATION_MS / 1000) # native sleep here
|
||||
sock.close()
|
||||
print(f"[AUDIO-PROC] Отправка завершена.")
|
||||
|
||||
|
||||
async def handle_channel_transmission(channel, voice_call, websocket, auth_dict, promise_id_start, channel_id):
|
||||
async def handle_channel_transmission(channel, voice_call, websocket,
|
||||
auth_dict, promise_id_start, channel_id):
|
||||
ssrc = SSRC + channel_id # Например, добавим `uid` канала для уникальности
|
||||
source_id = auth_dict["client_id"]
|
||||
retry_attempts = 0
|
||||
@ -140,7 +144,9 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
|
||||
|
||||
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
|
||||
@ -154,10 +160,10 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
|
||||
identifier = item.get("identifier")
|
||||
payload = item.get("payload")
|
||||
|
||||
if identifier != "location:0/position_broadcast":
|
||||
log(f"<<< Ответ получен: {item}")
|
||||
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
|
||||
@ -167,7 +173,9 @@ 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:
|
||||
@ -181,7 +189,9 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
|
||||
# Запуск в отдельном процессе
|
||||
proc = Process(
|
||||
target=start_audio_stream_sync,
|
||||
args=(audio_path, auth_dict["radiusip_host_ws"], API_PORT, ssrc)
|
||||
args=(
|
||||
audio_path, auth_dict["radiusip_host_ws"], API_PORT,
|
||||
ssrc)
|
||||
)
|
||||
proc.start()
|
||||
|
||||
@ -189,7 +199,8 @@ async def handle_channel_transmission(channel, voice_call, websocket, auth_dict,
|
||||
await asyncio.sleep(duration_sec + 1)
|
||||
|
||||
# Завершаем promise
|
||||
await send_messages(websocket, get_promise_cancel_command(promise_id))
|
||||
await send_messages(websocket,
|
||||
get_promise_cancel_command(promise_id))
|
||||
return True
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
@ -214,8 +225,7 @@ async def receive_messages(websocket, auth_dict):
|
||||
message_from_json = json.loads(message)
|
||||
for item in message_from_json:
|
||||
identifier = item.get("identifier")
|
||||
if identifier != "location:0/position_broadcast":
|
||||
log(f"<<< Ответ получен: {item}")
|
||||
log(f"<<< Ответ получен: {item}")
|
||||
|
||||
# Проверяем вызовы
|
||||
if call_mapi_initialized and auth_dict.get("plasystem"):
|
||||
@ -224,7 +234,8 @@ async def receive_messages(websocket, auth_dict):
|
||||
for ch in voice_call.channels.all():
|
||||
channel = ch.uid
|
||||
success = await handle_channel_transmission(
|
||||
channel, voice_call, websocket, auth_dict, promise_id, ch.id
|
||||
channel, voice_call, websocket, auth_dict,
|
||||
promise_id, ch.id
|
||||
)
|
||||
promise_id += 1
|
||||
await set_voice_call_sent(voice_call)
|
||||
@ -232,15 +243,17 @@ async def receive_messages(websocket, auth_dict):
|
||||
if identifier == "core/connection_response":
|
||||
log("Соединение установлено. Инициализация модулей...")
|
||||
auth_dict["client_id"] = item["payload"].get("client_id")
|
||||
await send_messages(websocket, get_call_initialize_command())
|
||||
await send_messages(websocket, get_location_initialize_command())
|
||||
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)
|
||||
|
||||
elif identifier == "location:0/position_broadcast" and auth_dict.get(
|
||||
"wlocationsystem"
|
||||
"wlocationsystem"
|
||||
):
|
||||
await save_location(item["payload"])
|
||||
|
||||
@ -264,11 +277,23 @@ def set_voice_call_sent(voice_call):
|
||||
|
||||
|
||||
async def save_location(payload):
|
||||
await create_or_update_location(payload)
|
||||
await create_or_update_worker(payload)
|
||||
await create_worker_history(payload)
|
||||
|
||||
|
||||
@sync_to_async
|
||||
def create_or_update_location(data):
|
||||
def create_worker_history(data):
|
||||
worker = WorkersLocation.objects.get(uid=data["abonent_id"])
|
||||
WorkersTracking.objects.create(worker=worker,
|
||||
latitude=data["latitude"],
|
||||
longitude=data["longitude"],
|
||||
velocity=data["velocity"],
|
||||
radius=data["radius"],
|
||||
time=parser.isoparse(data["update_time"]))
|
||||
|
||||
|
||||
@sync_to_async
|
||||
def create_or_update_worker(data):
|
||||
WorkersLocation.objects.update_or_create(
|
||||
uid=data["abonent_id"],
|
||||
defaults={
|
||||
@ -281,28 +306,6 @@ 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,
|
||||
]
|
||||
subprocess.run(command, check=True)
|
||||
with open(output_file, "rb") as f:
|
||||
audio_data = f.read()
|
||||
os.remove(output_file)
|
||||
return audio_data
|
||||
|
||||
|
||||
async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sequence_number = 0
|
||||
@ -318,7 +321,7 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, ssrc):
|
||||
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
|
||||
|
||||
@ -328,7 +331,7 @@ async def start_audio_stream(audio_path, dest_ip, dest_port, 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)
|
||||
timestamp = (timestamp + timestamp_increment) % (2 ** 32)
|
||||
await asyncio.sleep(PACKET_DURATION_MS / 1000)
|
||||
|
||||
sock.close()
|
||||
@ -376,11 +379,12 @@ async def main():
|
||||
while True:
|
||||
try:
|
||||
async with websockets.connect(
|
||||
uri, ping_interval=20, ping_timeout=10
|
||||
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):
|
||||
except (
|
||||
ConnectionRefusedError, websockets.exceptions.ConnectionClosedError):
|
||||
log("Соединение не удалось или разорвано. Повтор через 5 секунд...")
|
||||
await asyncio.sleep(5)
|
||||
except Exception as e:
|
||||
@ -389,7 +393,8 @@ 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")
|
||||
|
||||
39
apps/workerslocation/migrations/0010_auto_20250530_1041.py
Normal file
39
apps/workerslocation/migrations/0010_auto_20250530_1041.py
Normal file
@ -0,0 +1,39 @@
|
||||
# Generated by Django 3.2.25 on 2025-05-30 10:41
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('workerslocation', '0009_workerslocation_icon'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='WorkersTracking',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('latitude', models.FloatField(default=0.0, verbose_name='Широта')),
|
||||
('longitude', models.FloatField(default=0.0, verbose_name='Долгота')),
|
||||
('time', models.DateTimeField(blank=True, verbose_name='Время отметки')),
|
||||
('velocity', models.DecimalField(decimal_places=6, default=0.0, max_digits=9, verbose_name='Скорость')),
|
||||
('radius', models.DecimalField(decimal_places=6, default=0.0, max_digits=9, verbose_name='Радиус')),
|
||||
('worker', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='workerslocation.workerslocation', verbose_name='Объект')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Передвижение сотрудника',
|
||||
'verbose_name_plural': 'Передвижения сотрудников',
|
||||
'ordering': ('worker',),
|
||||
},
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='workerstracking',
|
||||
index=models.Index(fields=['worker'], name='workersloca_worker__d7aec1_idx'),
|
||||
),
|
||||
migrations.AddIndex(
|
||||
model_name='workerstracking',
|
||||
index=models.Index(fields=['time'], name='workersloca_time_9a1c92_idx'),
|
||||
),
|
||||
]
|
||||
46
apps/workerslocation/models/workers_tracking.py
Normal file
46
apps/workerslocation/models/workers_tracking.py
Normal file
@ -0,0 +1,46 @@
|
||||
from django.db import models
|
||||
|
||||
from apps.workerslocation.models.workers_locations import WorkersLocation
|
||||
|
||||
|
||||
class WorkersTracking(models.Model): # Передвижение персонала
|
||||
worker = models.ForeignKey(
|
||||
WorkersLocation, on_delete=models.SET_NULL, null=True, verbose_name="Объект"
|
||||
)
|
||||
latitude = models.FloatField(default=0.0, help_text="", verbose_name="Широта")
|
||||
longitude = models.FloatField(default=0.0, help_text="", verbose_name="Долгота")
|
||||
time = models.DateTimeField(
|
||||
auto_now=False, auto_now_add=False, blank=True, verbose_name="Время отметки"
|
||||
)
|
||||
velocity = models.DecimalField(
|
||||
default=0.0, max_digits=9, decimal_places=6, verbose_name="Скорость"
|
||||
)
|
||||
radius = models.DecimalField(
|
||||
default=0.0, max_digits=9, decimal_places=6, verbose_name="Радиус"
|
||||
)
|
||||
|
||||
def getLat(self):
|
||||
return str(self.latitude).replace(",", ".")
|
||||
|
||||
def getLon(self):
|
||||
return str(self.longitude).replace(",", ".")
|
||||
|
||||
def __str__(self):
|
||||
return str(self.worker)
|
||||
|
||||
class Meta: # отображение в админики
|
||||
ordering = ("worker",)
|
||||
verbose_name = "Передвижение сотрудника"
|
||||
verbose_name_plural = "Передвижения сотрудников"
|
||||
indexes = [
|
||||
models.Index(
|
||||
fields=[
|
||||
"worker",
|
||||
]
|
||||
),
|
||||
models.Index(
|
||||
fields=[
|
||||
"time",
|
||||
]
|
||||
),
|
||||
]
|
||||
@ -42,7 +42,7 @@ INSTALLED_APPS = [
|
||||
"""Информация о приложении """
|
||||
SITE_TITLE = "Многофункциональная система безопасности ОГР"
|
||||
SITE_TITLE_S = "МФСБ ОГР"
|
||||
APP_VER = "1.0.16.0"
|
||||
APP_VER = "1.0.16.1"
|
||||
APP_VEK = "2023 - 2025гг"
|
||||
APP_COPPIRIGHT = "Многофункциональная система безопасности ОГР"
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user