365 lines
16 KiB
Python
365 lines
16 KiB
Python
import traceback
|
||
import calendar
|
||
import uuid
|
||
import json
|
||
import datetime
|
||
import requests
|
||
import math
|
||
import requests.exceptions as rex
|
||
|
||
from django.db.models import Sum
|
||
from django.core.cache import cache
|
||
from django.db.models import Q
|
||
|
||
from requests.auth import HTTPBasicAuth
|
||
|
||
from datetime import datetime, timedelta, timezone,date
|
||
|
||
|
||
from apps.seismicproc.models.model_earthquake import Earthquake
|
||
from apps.gto.models.model_equipment import Equipment
|
||
from apps.gto.models.model_type_sensor import TypeSensor
|
||
from apps.gto.models.model_sensors import Sensors
|
||
from apps.gto.models.model_indicators import Indicators
|
||
|
||
from mfssogr.celery import app
|
||
|
||
from sabron.util import logging
|
||
|
||
from apps.general.views import settingsmodule
|
||
|
||
from bs4 import BeautifulSoup
|
||
import io
|
||
#https://www.emsc-csem.org/Earthquake_information/earthquake_map.php?id=1609312
|
||
|
||
def geo(latitude,longitude):
|
||
try:
|
||
dist = int(settingsmodule.get_settings('seism_km',1000))
|
||
mylon = float(settingsmodule.get_settings('longitude','86.10111978605353')) # долгота центра
|
||
mylat = float(settingsmodule.get_settings('latitude','55.344251210827814')) # широта
|
||
lon1 = mylon-dist/abs(math.cos(math.radians(mylat))*111.0) # 1 градус широты = 111 км
|
||
lon2 = mylon+dist/abs(math.cos(math.radians(mylat))*111.0)
|
||
lat1 = mylat-(dist/111.0)
|
||
lat2 = mylat+(dist/111.0)
|
||
|
||
if (float(latitude) >= float(lat1) and float(latitude) <= float(lat2)) and (float(longitude) >=float(lon1) and float(longitude)<=float(lon2)):
|
||
return True
|
||
return False
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
return False
|
||
|
||
def get_month(current_month):
|
||
list_mont =['January','February','March','April','May','June','July','August','September','October','November','December']
|
||
return list_mont[current_month-1]
|
||
|
||
def load_usgs(**kwargs):
|
||
try:
|
||
current_year = kwargs['current_year']
|
||
lat = kwargs['lat']
|
||
lon = kwargs['lon']
|
||
dist = kwargs['dist']
|
||
response = requests.get(f'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime={current_year}-01-01&endtime={current_year}-12-31&latitude={lat}&longitude={lon}&maxradiuskm={dist}')
|
||
json_string = response.text
|
||
json_string = json_string.replace("'",'"')
|
||
js = json.loads(json_string)
|
||
rows = js['features']
|
||
for row in rows:
|
||
coordinates = row['geometry']['coordinates']
|
||
longitude = coordinates[0]
|
||
latitude = coordinates[1]
|
||
depth = coordinates[2]
|
||
magnitude = row['properties']['mag']
|
||
region = row['properties']['place']
|
||
date_time = datetime.fromtimestamp(row['properties']['time'] / 1e3)
|
||
v = geo(latitude,longitude)
|
||
if v:
|
||
myfileter = Q(date_time = date_time)
|
||
myfileter &= Q(latitude = latitude)
|
||
myfileter &= Q(longitude = longitude)
|
||
earthquake = Earthquake.objects.filter(myfileter).first()
|
||
if earthquake is None:
|
||
Earthquake.objects.create(date_time = date_time,
|
||
latitude = latitude,
|
||
longitude = longitude,
|
||
depth = depth,
|
||
magnitude = magnitude,
|
||
region = region,
|
||
source = "usgs")
|
||
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
|
||
def load_seishub(**kwargs):
|
||
try:
|
||
current_year = kwargs['current_year']
|
||
current_month = get_month(kwargs['current_month'])
|
||
form_data={'username':'r.melnikov@cybercode.pro','password':'ceckbr673878*as'}
|
||
Headers = { "accept" : "application/json","Content-type":"application/json" }
|
||
response = requests.post(f'http://seishub.ru/cgi-bin/mailman/private/seismic-report/{current_year}-{current_month}.txt',data=form_data)
|
||
str_var = response.text
|
||
start = 0
|
||
start_region =0
|
||
with io.StringIO(str_var) as file:
|
||
for my_var in map(str.rstrip, file):
|
||
if my_var =='Agency: ASBauto':
|
||
start =0
|
||
date_time_str = date_time_str.replace('ВРЕМЯ В ОЧАГЕ (НОВОСИБИРСК):','')
|
||
date_time_str = date_time_str.strip()
|
||
date_time = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
|
||
latitude_str = latitude_str.replace('ШИРОТА:','')
|
||
latitude_str = latitude_str.strip()
|
||
latitude = latitude_str
|
||
longitude_str = longitude_str.replace('ДОЛГОТА:','')
|
||
longitude_str = longitude_str.strip()
|
||
longitude = longitude_str
|
||
depth_str = depth_str.replace('ГЛУБИНА:','')
|
||
depth_str = depth_str.strip()
|
||
depth = depth_str
|
||
magnitude_str = magnitude_str.replace('МАГНИТУДА:','')
|
||
magnitude_str = magnitude_str.strip()
|
||
magnitude = magnitude_str
|
||
region_str = region_str.replace('Регион события:','')
|
||
region_str = region_str.replace(' ',' ')
|
||
region_str = region_str.replace(' ',' ')
|
||
region_str = region_str.strip()
|
||
region = region_str
|
||
v = geo(latitude,longitude)
|
||
if v:
|
||
myfileter = Q(date_time = date_time)
|
||
myfileter &= Q(latitude = latitude)
|
||
myfileter &= Q(longitude = longitude)
|
||
earthquake = Earthquake.objects.filter(myfileter).first()
|
||
if earthquake is None:
|
||
Earthquake.objects.create(date_time = date_time,
|
||
latitude = latitude,
|
||
longitude = longitude,
|
||
depth = depth,
|
||
magnitude = magnitude,
|
||
region = region,
|
||
source = "АСФ ГС СО РАН")
|
||
|
||
continue
|
||
if my_var =='ОПЕРАТИВНОЕ СООБЩЕНИЕ О СЕЙСМИЧЕСКОМ СОБЫТИИ':
|
||
start =1
|
||
continue
|
||
if start == 1:
|
||
result = my_var.find('ВРЕМЯ В ОЧАГЕ (НО')
|
||
if result!=-1:
|
||
date_time_str = my_var
|
||
result = my_var.find('ШИРОТА')
|
||
if result!=-1:
|
||
latitude_str = my_var
|
||
result = my_var.find('ДОЛГОТА')
|
||
if result!=-1:
|
||
longitude_str = my_var
|
||
result = my_var.find('ГЛУБИНА')
|
||
if result!=-1:
|
||
depth_str = my_var
|
||
result = my_var.find('МАГНИТУДА')
|
||
if result!=-1:
|
||
magnitude_str = my_var
|
||
result = my_var.find('Регион события')
|
||
if result!=-1:
|
||
start_region = 1
|
||
region_str = my_var
|
||
continue
|
||
if start_region == 1:
|
||
result = my_var.find('http://www.openstreetmap')
|
||
if result!=-1:
|
||
start_region =0
|
||
continue
|
||
result = my_var.find('________')
|
||
if result!=-1:
|
||
start_region =0
|
||
continue
|
||
region_str = region_str+my_var
|
||
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
|
||
def load_gsras(**kwargs):
|
||
try:
|
||
lat = kwargs['lat']
|
||
lon = kwargs['lon']
|
||
dist = kwargs['dist']
|
||
response = requests.get(f'http://www.gsras.ru/cgi-bin/new/mapCustom.pl?l=0&lat={lat}&lon={lon}&num=50&rad={dist}')
|
||
bs = BeautifulSoup(response.text,"lxml")
|
||
table = bs.find(id="tableQuakes")
|
||
table_body = table.find('tbody')
|
||
rows = table_body.find_all('tr')
|
||
data = []
|
||
for row in rows:
|
||
cols = row.find_all('td')
|
||
myfileter = Q(date_time = cols[1].text.strip())
|
||
myfileter &= Q(latitude = cols[2].text.strip())
|
||
myfileter &= Q(longitude = cols[3].text.strip())
|
||
earthquake = Earthquake.objects.filter(myfileter).first()
|
||
if earthquake is None:
|
||
v = geo(cols[2].text.strip(),cols[3].text.strip())
|
||
if v:
|
||
Earthquake.objects.create(date_time = cols[1].text.strip(),
|
||
latitude = cols[2].text.strip(),
|
||
longitude = cols[3].text.strip(),
|
||
depth = cols[4].text.strip() ,
|
||
magnitude = cols[7].text.strip(),
|
||
region = cols[9].text.strip(),
|
||
source = "gsras")
|
||
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
|
||
def load_sigi(**kwargs):
|
||
try:
|
||
server_sigi = settingsmodule.get_settings('seism_server_sigi','')
|
||
organization = settingsmodule.get_settings('organization','')
|
||
if len(server_sigi)==0:
|
||
return
|
||
lat = kwargs['lat']
|
||
lon = kwargs['lon']
|
||
dist = kwargs['dist']
|
||
data=dict()
|
||
data.update(cmd='get_events')
|
||
Headers = { "accept" : "application/json","Content-type":"application/json" }
|
||
|
||
response = requests.post(f'{server_sigi}/',data=json.dumps(data),headers = Headers, verify=False)
|
||
if response.status_code != 200:
|
||
return
|
||
response_data = response.json()
|
||
for data in response_data:
|
||
if data['mag'] is not None:
|
||
myfileter = Q(date_time = data['d_event'])
|
||
myfileter &= Q(latitude =data['x_bang'])
|
||
myfileter &= Q(longitude = data['y_bang'])
|
||
earthquake = Earthquake.objects.filter(myfileter).first()
|
||
v = geo(data['x_bang'],data['y_bang'])
|
||
if v:
|
||
Earthquake.objects.create(date_time = data['d_event'],
|
||
latitude = data['x_bang'],
|
||
longitude = data['y_bang'],
|
||
magnitude = data['mag'],
|
||
region = organization,
|
||
source = "SIGI")
|
||
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
|
||
@app.task()
|
||
def load_earthquake():
|
||
try:
|
||
dist = int(settingsmodule.get_settings('seism_km',1000))
|
||
lon = float(settingsmodule.get_settings('longitude','86.10111978605353')) # долгота центра
|
||
lat = float(settingsmodule.get_settings('latitude','55.344251210827814')) # широта
|
||
current_day = datetime.now().day
|
||
current_month = datetime.now().month
|
||
current_year = datetime.now().year
|
||
|
||
load_gsras(dist = dist,
|
||
lon = lon,
|
||
lat = lat,
|
||
current_day = current_day,
|
||
current_month = current_month,
|
||
current_year = current_year)
|
||
load_seishub(dist = dist,
|
||
lon = lon,
|
||
lat = lat,
|
||
current_day = current_day,
|
||
current_month = current_month-1,
|
||
current_year = current_year)
|
||
load_seishub(dist = dist,
|
||
lon = lon,
|
||
lat = lat,
|
||
current_day = current_day,
|
||
current_month = current_month,
|
||
current_year = current_year)
|
||
load_usgs(dist = dist,
|
||
lon = lon,
|
||
lat = lat,
|
||
current_day = current_day,
|
||
current_month = current_month,
|
||
current_year = current_year)
|
||
load_sigi(dist = dist,
|
||
lon = lon,
|
||
lat = lat,
|
||
current_day = current_day,
|
||
current_month = current_month,
|
||
current_year = current_year)
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
|
||
def load_asc(): #
|
||
try:
|
||
gtoadress = settingsmodule.get_settings('gtoadress','')
|
||
gtologin= settingsmodule.get_settings('gtologin','')
|
||
gtopass= settingsmodule.get_settings('gtopass','')
|
||
response = requests.get(f'{gtoadress}main?func=state&&auth_login={gtologin}&auth_pass={gtopass}&sensors&out=json', verify=False)
|
||
json_data = json.loads(response.text)
|
||
catalog_list=[]
|
||
if json_data['result']=='OK':
|
||
for data in json_data['objects']:
|
||
element = Equipment.objects.filter(uid=data['id']).first()
|
||
if element is None:
|
||
element = Equipment.objects.create(uid=data['id'],
|
||
name=data['name'],
|
||
model=data['model'],
|
||
model_type=data['model_type'],
|
||
garagenum=data['garagenum'],
|
||
statenum=data['statenum'],
|
||
time=data['time'],
|
||
lat=data['lat'],
|
||
lon=data['lon'],
|
||
speed=data['speed'])
|
||
else:
|
||
element.time=data['time']
|
||
element.lat=data['lat']
|
||
element.lon=data['lon']
|
||
element.speed=data['speed']
|
||
element.save()
|
||
for sensor in data['sensors']:
|
||
if sensor['converted']=='true':
|
||
converted=True
|
||
else:
|
||
converted=False
|
||
type = TypeSensor.objects.filter(code=sensor['type_code']).first()
|
||
if type is None:
|
||
type = TypeSensor.objects.create(code=sensor['type_code'],
|
||
name=sensor['type_name'])
|
||
sensor_link =Sensors.objects.filter(equipment=element).filter(uid=sensor['id']).first()
|
||
if sensor_link is None:
|
||
sensor_link = Sensors.objects.create(uid=sensor['id'],
|
||
name=sensor['name'],
|
||
type =type,
|
||
equipment=element,
|
||
converted=converted,
|
||
time=sensor['time'],
|
||
value=sensor['value'])
|
||
else:
|
||
sensor_link.converted=converted
|
||
sensor_link.time=sensor['time']
|
||
sensor_link.value=sensor['value']
|
||
sensor_link.save()
|
||
indicator_link = Indicators.objects.filter(sensor=sensor_link).order_by('time').first()
|
||
if indicator_link is None:
|
||
indicator_link = Indicators.objects.create(sensor=sensor_link,
|
||
time=sensor['time'],
|
||
value=sensor['value'])
|
||
else:
|
||
if indicator_link.value != float(sensor['value']):
|
||
indicator_link = Indicators.objects.create(sensor=sensor_link,
|
||
time=sensor['time'],
|
||
value=sensor['value'])
|
||
|
||
|
||
|
||
|
||
|
||
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc())
|
||
|
||
@app.task()
|
||
def load_navigation(): #
|
||
try:
|
||
load_asc()
|
||
except Exception as err:
|
||
logging.error(traceback.format_exc()) |