Добавил запись в базу с WS

This commit is contained in:
zakhy 2024-10-22 17:14:48 +07:00
parent 397d6ce161
commit d9f813d262
8 changed files with 243 additions and 11 deletions

View File

@ -1 +1,8 @@
from django.contrib import admin
from apps.workerslocation.models.workers_locations import WorkersLocation
@admin.register(WorkersLocation)
class WorkersLocationAdmin(admin.ModelAdmin):
list_display = ('abonent_id', 'latitude', 'longitude', 'velocity', 'radius', 'update_time',)

View File

@ -0,0 +1,139 @@
import asyncio
import datetime
import os
import django
import websockets
import json
from asgiref.sync import sync_to_async
from django.db import transaction
# hello()
def all_comand():
mcomand = []
mcomand.append('[{"identifier": "attachment:0/initialization_request","payload": {}}]')
mcomand.append(
'[{"identifier": "call:1/initialization_request","payload": {"voip_port": 54595,"supported_codecs": [{"codec_id": 8,"name": "pcma/8000","packet_duration": 20,"sampling_rate": 8000}],"is_supported_webrtc": false}}]')
mcomand.append('[{"identifier": "dgna:0/initialization_request","payload": {}}]')
mcomand.append('[{"identifier": "server_objects:0/initialization_request","payload": {}}]')
mcomand.append('[{"identifier": "location:0/initialization_request","payload": {}}]')
mcomand.append('[{"identifier": "text:1/initialization_request","payload": {}}]')
mcomand.append('[{"identifier": "command:0/initialization_request","payload": {}}]')
return mcomand
async def receive_messages(websocket):
while True:
try:
message = await websocket.recv()
data = json.loads(message)
identifier = data[0]['identifier']
fin = identifier.find('monitoring_frame')
if data[0]['identifier'] == 'core/connection_response':
mcomand = all_comand()
for command in mcomand:
send_task = asyncio.create_task(send_messages(websocket, command))
print(f"<<< {command}")
if identifier.find('monitoring_frame') == -1:
print(">", data[0])
if 'location:0/position_broadcast' in identifier:
await save_or_update_location(data[0]['payload'])
print(datetime.datetime.now())
print("*********************************************************************************")
except websockets.exceptions.ConnectionClosed:
break
async def send_messages(websocket, user_input):
# while True:
await websocket.send(user_input)
await asyncio.sleep(0) # передача управления циклу event
def send_mess(websocket, user_input):
websocket.send(user_input)
async def save_or_update_location(payload):
# Асинхронный вызов синхронного метода ORM через sync_to_async
await create_or_update_location(payload)
@sync_to_async
def create_or_update_location(data):
abonent_id = data['abonent_id']
latitude = data['latitude']
longitude = data['longitude']
velocity = data['velocity']
radius = data['radius']
update_time = data['update_time']
# Используем транзакцию для безопасности
with transaction.atomic():
# Получаем существующую запись, если она есть
try:
location = WorkersLocation.objects.get(abonent_id=abonent_id)
# Проверяем, нужно ли обновлять поля
if (location.latitude != latitude or
location.longitude != longitude or
location.velocity != velocity or
location.radius != radius):
# Обновляем только изменившиеся поля
location.latitude = latitude
location.longitude = longitude
location.velocity = velocity
location.radius = radius
location.update_time = update_time
location.save()
return True
else:
location.update_time = update_time
location.save()
except WorkersLocation.DoesNotExist:
WorkersLocation.objects.create(
abonent_id=abonent_id,
latitude=latitude,
longitude=longitude,
velocity=velocity,
radius=radius,
update_time=update_time
)
return True
async def main():
uri = "ws://192.168.51.163:8191/"
m = []
data = dict()
data.update(identifier='core/connection_request')
datapay = dict()
datapay.update(login='TestAPI')
datapay.update(password='123456A!')
datapay.update(
api_key="ООО ЦТВС «КузбассТехноСпорт»:ewAiAEsAZQB5AEkAZAAiADoAMQAsACIAQwBsAGkAZQBuAHQAVAB5AHAAZQAiADoAIgBBAHAAaQAiACwAIgBTAHUAcABwAG8AcgB0AGUAZABBAHAAaQBlAHMAIgA6AFsAIgBzAGUAcgB2AGUAcgBfAG8AYgBqAGUAYwB0AHMAIgAsACIAcwBlAHIAdgBlAHIAXwBvAGIAagBlAGMAdABzADoAcgBvACIALAAiAGMAYQBsAGwAIgAsACIAYwBhAGwAbAA6AHIAbwAiACwAIgBjAGEAbABsADoAdAByAGEAbgBzAG0AaQB0ACIALAAiAGMAbwBtAG0AYQBuAGQAIgAsACIAYwBvAG0AbQBhAG4AZAA6AHIAbwAiACwAIgB0AGUAeAB0ACIALAAiAHQAZQB4AHQAOgByAG8AIgAsACIAbABvAGMAYQB0AGkAbwBuACIALAAiAGwAbwBjAGEAdABpAG8AbgA6AHIAbwAiACwAIgBsAG8AYwBhAHQAaQBvAG4AOgB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70duzvnPviINdoZK2m30fg5tCUDV2KwM2j/wxNz9POQY4h+adA7UsFVD3FkoCaavhVaHYJRovpwsKR9g+pc50M/npt4SbGL6JUPYQ2kgL873Qfiq+1GIDtjo4Sfrl80="
)
datapay.update(token=None)
data.update(payload=datapay)
m.append(data)
mlocation = []
datalocation = dict()
datalocation.update(identifier='"location:0/initialization_request')
datapaylocation = dict()
datalocation.update(payload=datapaylocation)
mlocation.append(data)
async with websockets.connect(uri) as websocket:
receive_task = asyncio.create_task(receive_messages(websocket))
asyncio.create_task(send_messages(websocket, json.dumps(m)))
await asyncio.gather(receive_task)
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mfssogr.settings')
django.setup()
from apps.workerslocation.models.workers_locations import WorkersLocation
asyncio.run(main())

View File

@ -0,0 +1,39 @@
# Generated by Django 3.2.16 on 2024-10-22 06:37
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='WorkersLocation',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('abonent_id', models.CharField(max_length=128, verbose_name='ID рации')),
('latitude', models.DecimalField(decimal_places=6, default=0.0, max_digits=9, verbose_name='Широта')),
('longitude', models.DecimalField(decimal_places=6, default=0.0, max_digits=9, 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='Радиус')),
('update_time', models.DateTimeField(auto_now=True, verbose_name='Время связи')),
],
options={
'verbose_name': 'объект',
'verbose_name_plural': 'объекты',
'ordering': ('abonent_id',),
},
),
migrations.AddIndex(
model_name='workerslocation',
index=models.Index(fields=['abonent_id'], name='workersloca_abonent_54a8c5_idx'),
),
migrations.AddIndex(
model_name='workerslocation',
index=models.Index(fields=['update_time'], name='workersloca_update__0a4688_idx'),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.2.16 on 2024-10-22 09:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workerslocation', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='workerslocation',
name='active',
field=models.BooleanField(default=True),
),
]

View File

@ -0,0 +1,23 @@
from django.db import models
class WorkersLocation(models.Model):
abonent_id = models.CharField(max_length=128, verbose_name="ID рации")
latitude = models.DecimalField(default=0.0, max_digits=9, decimal_places=6, verbose_name="Широта")
longitude = models.DecimalField(default=0.0, max_digits=9, decimal_places=6, 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="Радиус")
update_time = models.DateTimeField(auto_now=True, verbose_name="Время связи")
active = models.BooleanField(default=True)
def __str__(self):
return self.abonent_id
class Meta: # отображение в админики
ordering = ('abonent_id',)
verbose_name = u'объект'
verbose_name_plural = u'объекты'
indexes = [
models.Index(fields=['abonent_id', ]),
models.Index(fields=['update_time', ])
]

View File

@ -21,6 +21,7 @@ from django.db.models import Q
from django.shortcuts import render
from django.shortcuts import redirect
from apps.workerslocation.models.workers_locations import WorkersLocation
from sabron.util import logging
from apps.util import generalmodule
@ -36,7 +37,7 @@ from apps.workerslocation.views import views_radiusapi
@login_required(login_url='/accounts/login/?next=')
@never_cache
def sensor_ajax(request):
def sensor_ajax(request):
try:
if request.method == "POST":
sensor_dict = dict()
@ -48,8 +49,8 @@ def sensor_ajax(request):
time = sensor.time
value = sensor.value
end_date=sensor.time+timedelta(seconds=15)
value_old = 0
value_old = 0
if param['sensor_type'] == 'sec':
strftime = "%d.%m.%Y %H:%M:%S"
start_date = end_date - timedelta(seconds=30)
@ -90,7 +91,7 @@ def sensor_ajax(request):
strftimeend = "%d.%m.%Y %H:%M:%S"
time = start_date + timedelta(seconds=i)
start_date_day = time
end_date_day = time+ timedelta(milliseconds=1000)
elif param['sensor_type'] == 'min':
strftimeend = "%d.%m.%Y %H:%M"
@ -183,11 +184,11 @@ def object_block(request):
@never_cache
def map_index(request):
try:
mylon = str(float(settingsmodule.get_settings('longitude','86.10111978605353'))) # долгота центра
mylat = str(float(settingsmodule.get_settings('latitude','55.344251210827814'))) # широта
mylat = str(float(settingsmodule.get_settings('latitude','55.344251210827814'))) # широта
gtoadress = settingsmodule.get_settings('gtoadress','')
gtouid = settingsmodule.get_settings('gtouid','')
@ -217,13 +218,16 @@ def map_index(request):
@login_required(login_url='/')
@never_cache
def main_index(request):
WorkersLocation.objects.all()
try:
radiusapi = settingsmodule.get_settings('radiusapi','False')
if radiusapi:
return views_radiusapi.map_index(request)
lon = str(float(settingsmodule.get_settings('longitude', '86.10111978605353'))) # долгота центра
lat = str(float(settingsmodule.get_settings('latitude', '55.344251210827814'))) # широта
param=request.GET.dict()
clients=Equipment.objects.filter(block=False).order_by("-time",'name').all()
clients_count = clients.count()
@ -266,7 +270,9 @@ def main_index(request):
'end_page_list':end_page_list,
'start_page_list':start_page_list,
'clients_count':clients_count,
})
'lon': lon,
'lat': lat
})
if request.user.profile.role==1:
context.update(main_index_block(page_number_block))