ogn-python/ogn/utils.py

65 wiersze
1.8 KiB
Python
Czysty Zwykły widok Historia

2015-11-11 07:03:42 +00:00
import requests
import csv
from io import StringIO
2015-11-15 07:51:40 +00:00
from math import sin, cos, asin, atan2, sqrt, pi
2015-11-06 21:34:19 +00:00
2015-11-16 19:04:54 +00:00
from .model import Device, AddressOrigin
2015-11-06 21:34:19 +00:00
from geopy.geocoders import Nominatim
2015-11-11 07:03:42 +00:00
DDB_URL = "http://ddb.glidernet.org/download"
2015-11-06 21:34:19 +00:00
2015-11-15 07:51:40 +00:00
deg2rad = pi/180
rad2deg = 1/deg2rad
2015-11-06 21:34:19 +00:00
2015-11-11 07:03:42 +00:00
def get_ddb(csvfile=None):
if csvfile is None:
r = requests.get(DDB_URL)
rows = '\n'.join(i for i in r.text.splitlines() if i[0] != '#')
address_origin = AddressOrigin.ogn_ddb
else:
r = open(csvfile, 'r')
rows = ''.join(i for i in r.readlines() if i[0] != '#')
address_origin = AddressOrigin.userdefined
data = csv.reader(StringIO(rows), quotechar="'", quoting=csv.QUOTE_ALL)
2015-11-06 21:34:19 +00:00
2015-11-11 07:03:42 +00:00
devices = list()
for row in data:
2015-11-16 19:04:54 +00:00
flarm = Device()
2015-11-11 07:03:42 +00:00
flarm.address_type = row[0]
flarm.address = row[1]
flarm.aircraft = row[2]
flarm.registration = row[3]
flarm.competition = row[4]
flarm.tracked = row[5] == 'Y'
flarm.identified = row[6] == 'Y'
flarm.address_origin = address_origin
2015-11-06 21:34:19 +00:00
devices.append(flarm)
return devices
def get_country_code(latitude, longitude):
geolocator = Nominatim()
location = geolocator.reverse("%f, %f" % (latitude, longitude))
2015-11-12 07:38:43 +00:00
try:
country_code = location.raw["address"]["country_code"]
except KeyError:
country_code = None
2015-11-06 21:34:19 +00:00
return country_code
2015-11-15 07:51:40 +00:00
def wgs84_to_sphere(lat1, lat2, lon1, lon2, alt1, alt2):
lat1 = lat1*deg2rad
lat2 = lat2*deg2rad
lon1 = lon1*deg2rad
lon2 = lon2*deg2rad
radius = 6366000*2*asin(sqrt((sin((lat1-lat2)/2))**2 + cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))**2))
theta = atan2(alt2-alt1, radius)*rad2deg
phi = atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1))*rad2deg
return radius, theta, phi