def main(): # automatically bonus (great-circle distance) if any argument is provided bonus = True if len(sys.argv) > 1 else False # read from the API: https://opensky-network.org/api/states/all api = OpenSkyApi() states = api.get_states() home_lat = float(input().split(' ')[0]) # degrees home_long = float(input().split(' ')[0]) # degrees print("Closest plane to {}, {} at {}".format(home_lat, home_long, states.time)) print('-' * 40) # look for the closest flight to home best_state = min(states.states, key=lambda x: calc_distance( (home_lat, home_long), (x.latitude, x.longitude), bonus)) print( get_state_details( best_state, calc_distance((home_lat, home_long), (best_state.latitude, best_state.longitude), bonus))) print("More details at https://flightaware.com/live/flight/{}".format( best_state.callsign))
def findClosestPlane(givenLat, givenLon): closestPlaneDistance = 100000 poi = (givenLat, givenLon) api = OpenSkyApi() states = api.get_states() for s in states.states: currentPlane = (s.latitude, s.longitude) currentPlaneDistance = distance.geodesic(poi, currentPlane, ellipsoid='GRS-80').miles if float(currentPlaneDistance) < float(closestPlaneDistance): closestPlaneDistance = currentPlaneDistance closestPlaneNumber = s #print("Closest Distance: ", closestPlaneDistance) #print("Longitude: ", closestPlaneNumber.longitude) #print("Latitude: ", closestPlaneNumber.latitude) #print("Geometric Altitude: ", closestPlaneNumber.geo_altitude) #print("Country of Origin: ", closestPlaneNumber.origin_country) #print("Callsign: ", closestPlaneNumber.callsign) #print("ICA024 ID: ", closestPlaneNumber.icao24) return [ closestPlaneDistance, closestPlaneNumber.latitude, closestPlaneNumber.longitude, closestPlaneNumber.callsign, closestPlaneNumber.origin_country ]
def get_data(desired_icaos): api = OpenSkyApi() # bbox=(latmin,latmax,lonmin,lonmax) - selecting area over united states # time_secs=0 - time as unix time stamp or datetime in UTC # icao24=None - retrive state vectors for given ICAO24 addresses # (input array of strings) # FIXME - set time_secs and icao24 arguments once a passowrd is obtained to # run at set times (for example the time when the aircraftDatabase was last # updated) states = api.get_states(bbox=(13, 58, -144, -53)) lat = [] lon = [] icao = [] vel = [] alt = [] # print(states) for s in states.states: ''' print("(%r, %r, %r, %r, %r)" % (s.longitude, s.latitude, s.baro_altitude, s.velocity, s.icao24)) ''' lon.append(s.longitude) lat.append(s.latitude) icao.append(s.icao24) vel.append(s.velocity) alt.append(s.geo_altitude) return lon, lat, icao, vel, alt
def get_flight_radar_data(bounds): now = datetime.now() flights = Flight.objects.filter(departure_time__lt=now, arrival_time__gt=now) for f in flights: f.calculate_location() # bounds = [lamin, lamax, lomin, lomax] # poly = Polygon(((bounds[0], bounds[2]), (bounds[0], bounds[3]), (bounds[1], bounds[3]), (bounds[1], bounds[2]), (bounds[0], bounds[2]))) # # for f in flights: # print(poly.contains(f.location)) # flights = Flight.objects.filter(location__within=poly) # #departure_time__lt=now, arrival_time__gt=now, to_be_deleted = [] for f in flights: print("min_lat: " + str(bounds[0]) + 'real_lat: ' + str(f.location.x) + "max_lat: " + str(bounds[1])) print("min_lng: " + str(bounds[2]) + 'real_lng: ' + str(f.location.y) + "max_lng: " + str(bounds[3])) if f.location.x < bounds[0] or f.location.x > bounds[ 1] or f.location.y < bounds[2] or f.location.y > bounds[3]: to_be_deleted.append(f.id) # print(to_be_deleted) flights.exclude(pk__in=to_be_deleted) api = OpenSkyApi() states = api.get_states( bbox=bounds) #[48.943315, 55.060033, 13.549301, 24.686826]) geojson = to_geojson(states, flights) return geojson
def finalUpdate(mylat, mylon, radius): cursor = db.cursor() cursor.execute("USE test") #clears all database columns cursor.execute("DELETE FROM final_aircraft;") #connects to api and gets state vectors #this statement has to be done everytime we want to pull the data api = OpenSkyApi('User343', '0p3n$ky123!') states = api.get_states() x = 1 for s in states.states: if (inRange(mylat, mylon, s, radius)): #puts all the data into database row by row cursor.execute( "INSERT INTO final_aircraft(final_entry, final_lat, final_lon, final_vel, final_head, final_call, final_alt, final_icao24) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);", (x, s.latitude, s.longitude, s.velocity, s.heading, s.callsign, s.geo_altitude, s.icao24)) x += 1 else: continue db.commit()
def initialUpdate(mylat, mylon, radius): cursor = db.cursor() cursor.execute("USE test") #clears all database columns cursor.execute("DELETE FROM aircrafts;") #connects to api and gets state vectors #this statement has to be done everytime we want to pull the data api = OpenSkyApi('User343', '0p3n$ky123!') states = api.get_states() timeStamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(states.time)) x = 1 for s in states.states: if (inRange(mylat, mylon, s, radius)): #puts all the data into database row by row cursor.execute( "INSERT INTO aircrafts(entry, latitude, longitude, velocity, heading, callsign, altitude, icao24, time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);", (x, s.latitude, s.longitude, s.velocity, s.heading, s.callsign, s.geo_altitude, s.icao24, timeStamp)) x += 1 else: continue db.commit()
class OpenSkyADSB(ADSBSource): def __init__(self): ADSBSource.__init__(self) def open(self): from opensky_api import OpenSkyApi self.api = OpenSkyApi() def get_states(self): if self.bounding_box_enabled: return self.api.get_states(bbox=(self.bounding_box[0][0], self.bounding_box[0][1], self.bounding_box[1][0], self.bounding_box[1][1])) else: return self.api.get_states()
def produce_covidflights(): from opensky_api import OpenSkyApi from datetime import datetime import time api = OpenSkyApi() # states = api.get_states() # print("all flights:", len(states.states)) # df_flights = pandas.DataFrame(states.states) # flights_time = states.time # df_flights.to_csv("COVID19flights" + str(datetime.fromtimestamp(flights_time)).replace(':', '_') + ".csv", # index=True) # for s in states.states: # print("(%r, %r, %r, %r)" % (s.longitude, s.latitude, s.baro_altitude, s.velocity)) ## bbox = (min latitude, max latitude, min longitude, max longitude) print("*** READING NA flights") states_NA = api.get_states(bbox=(21.9, 69, -160, -56)) number_NA = len(states_NA.states) print("*** Done: number is:", number_NA) print("*** READING EU flights") time.sleep(15) # wait 15 secs for API to not block states_EU = api.get_states(bbox=(36, 69, -9, 37)) number_EU = len(states_EU.states) print("*** Done: number is:", number_EU) flights_time_NA = datetime.fromtimestamp(states_NA.time) dfdata = {'North America flights': number_NA, 'Europe flights': number_EU} dfindex = [flights_time_NA] df_flight_stats = pandas.DataFrame(dfdata, index=dfindex) df_flight_stats.index.names = ['timestamp MST'] df_flight_stats.to_csv("COVID19flightstats.csv", mode='a', index=True, header=False) df_flight_stats_all = pandas.read_csv("COVID19flightstats.csv") print(df_flight_stats_all) ## now to google move_stuff_to_google_sheets( df=df_flight_stats_all, spreadsheet_key='1Reb5-uZ77phwHMBUvICFyr6mLXnG_SbaHW41YLfrBYY', wks_name='COVID19flightstats', text='COVID19DATA', row_names=False)
class OpenskyService: """ Service layer around the OpenSky Network API. Data is fetched based on bounding box, a tuple (min_lat, max_lat, min_lon, max_lon) # Useful bounding boxes per country: https://gist.github.com/graydon/11198540 dict({ "world": (), "europe": (33.7, 71.9, -27.2, 44.2), "netherlands": (50.80, 53.51, 3.31, 7.09) }) """ _logger: logging.Logger _api: OpenSkyApi def __init__(self): self._logger = logging.getLogger(__name__) # Initialize API if OPENSKY_USE_AUTH: self._logger.info("Using basic authentication for Opensky") self._api = OpenSkyApi(username=OPENSKY_USERNAME, password=OPENSKY_PASSWORD) else: self._logger.info("Using Opensky anonymously") self._api = OpenSkyApi() def get_current_states(self, bounding_box: Tuple = None) -> Optional[dict]: if bounding_box is None: self._logger.warning( "No bounding box given for opensky data, defaulting to 'world'" ) bounding_box = () else: self._logger.debug("Bounding box for opensky request is: %s", bounding_box) try: s: Optional[OpenSkyStates] = self._api.get_states( bbox=bounding_box) except requests.exceptions.ReadTimeout: self._logger.warning("Call to OpenSky timed out") return None if s is not None: timestamp = datetime.fromtimestamp(s.time, timezone.utc) self._logger.debug("Retrieved %s records for timestamp %s", len(s.states), timestamp) return dict(timestamp=timestamp, states=list(map(lambda x: vars(x), s.states))) else: self._logger.warning("No records retrieved from Opensky") return None
def get_plane_data(bbox): api = OpenSkyApi() df_planes = pd.DataFrame(columns=['X', 'Y']) # bbox = (min latitude, max latitude, min longitude, max longitude) states = api.get_states(bbox=bbox) planes_coordinates = [] for s in states.states: x, y = ll2wm(s.longitude, s.latitude) df_planes = df_planes.append( pd.DataFrame([[x, y]], columns=df_planes.columns)) return df_planes
def exec_get_airplane_sound(is_call): lst2 = [] is_call_api = is_call center_location = (37.5216018, 126.837741) # 살레시오 while not is_call_api: try: api = OpenSkyApi('rxgp1', 'tla0420!@') states = api.get_states(bbox=(34.3900458847, 38.6122429469, 126.117397903, 129.468304478)) # In Korea # logger.debug(states) lst1 = [] for s in states.states: airplane_location = (s.latitude, s.longitude) to_location = haversine(center_location, airplane_location) air_plane = AirPlane(latitude=s.latitude, longitude=s.longitude, callsign=s.callsign, geo_altitude=s.geo_altitude, on_ground=s.on_ground, heading=s.heading, to_location=to_location) # logger.debug(lst2) for obj2 in lst2: if obj2.callsign == air_plane.callsign: air_plane.set_ignored(obj2.is_ignored) if not s.on_ground: if to_location < 3: # 반경 3키로 이내 lst1.append(air_plane) # logger.debug(airplane) lst1 = sorted(lst1, key=lambda x: x.to_location) for obj2 in lst2: for obj1 in lst1: if obj2.callsign == obj1.callsign: if obj1.to_location < obj2.to_location: if not obj2.is_ignored: obj1.set_ignored(True) logger.debug("Trigged :" + obj1.callsign) logger.debug("[who1 : " + str(obj1.to_location) + "]") logger.debug("[who2 : " + str(obj2.to_location) + "]") init_record("PI1", obj1.callsign.strip() + '.wav') except Exception as err: logger.error("error start ================================ ") logger.error(err) logger.error("end of error ================================ ") lst2 = lst1
def RetrievePlaneData_Full(): """ Name: RetrievePlaneData_Full Outputs: Aviation data in a Pandas Dataframe Features: Call the Opensky-network API and retrieve all possible data and return a Pandas Dataframe of the data. Note: API call has 15 second requirement between calls. This function will sleep if the API is called too quickly. """ # Call the API and full data while True: try: api = OpenSkyApi() states = api.get_states() break except: # Occasionally, the API can reject a request (15 second necessary time between requests) # If error arises, sleep the necessary time and try again sleep(15) main_array = [] for item in states.states: # Iterate through and store states object attributes (StateVector) temp_array = [0] * 17 temp_array[0] = item.icao24 temp_array[1] = item.callsign temp_array[2] = item.origin_country temp_array[3] = item.time_position temp_array[4] = item.last_contact temp_array[5] = item.longitude temp_array[6] = item.latitude temp_array[7] = item.baro_altitude temp_array[8] = item.velocity temp_array[9] = item.heading temp_array[10] = item.vertical_rate temp_array[11] = item.on_ground temp_array[12] = item.sensors temp_array[13] = item.geo_altitude temp_array[14] = item.squawk temp_array[15] = item.spi temp_array[16] = item.position_source main_array.append(temp_array) # Create and formate dataframe for use aviation_df = pd.DataFrame(main_array) aviation_df.columns = [ 'icao24', 'Callsign', 'Origin Country', 'Time Position', 'Last Contact', 'Longitude', 'Latitude', 'Baro Altitude', 'Velocity', 'Heading', 'Vertical Rate', 'On Ground', 'Sensors', 'Geo Altitude', 'Squawk', 'Spi', 'Position Source' ] return aviation_df
class AircraftList(object): def __init__(self): self._api = OpenSkyApi() self._icao24_list = active_icao_list() self._states = {} self._q = Queue.Queue(maxsize=10) self._poll_last_t = time.time() self._poll_thread = threading.Thread(target=self._poll_opensky) self._poll_thread.daemon = True # will abruptly die on main exit self._poll_thread.start() def _poll_opensky(self): while True: states = None s = self._api.get_states(icao24=self._icao24_list) if s is not None: t = time.time() dt = t - self._poll_last_t print('Update from OpenSky after %3.1fs' % dt) self._poll_last_t = t states = s.states if states is not None: self._q.put(states) time.sleep(1.0) def states(self): while self._states is None: self._states = self._q.get() try: self._states = self._q.get(block=False) except Queue.Empty: pass outp = [] for st in self._states: t = time.time() t0 = st.time_position lat0 = st.latitude lon0 = st.longitude alt0 = st.geo_altitude vhorz = st.velocity vclmb = st.vertical_rate hdg_deg = st.heading dt = t - t0 d_nmi = vhorz * dt / 1852.0 lat_deg, lon_deg = latlon(lat0, lon0, d_nmi, hdg_deg) alt_m = (alt0 + vclmb * (dt / 3600.)) outp.append({'callsign': st.callsign, 'lat_deg': lat_deg, 'lon_deg': lon_deg, 'alt_m': alt_m, 'hdg_deg': hdg_deg}) return outp
def retrieve_data(): api = OpenSkyApi() try: response = api.get_states() except Exception as e: print(e) return with open(create_output_file_name(), 'a') as file: for row in [ create_csv_row(state, response.time) for state in response.states ]: file.write(row)
def main(): api = OpenSkyApi() s = api.get_states() flights = [] for ac in s.states: status = None ac.geo_altitude = m2ft(ac.geo_altitude) if not precheck(ac): continue M503check(ac)
def coordinates(): api = OpenSkyApi() lon = [] lat = [] j = 0 # bbox = (min latitude, max latitude, min longitude, max longitude) states = api.get_states() # bbox=(8.27, 33.074, 68.4, 95.63)) for s in states.states: lon.append([]) lon[j] = s.longitude lat.append([]) lat[j] = s.latitude j += 1 return lon, lat
def generate_file(run_key): api = OpenSkyApi() states = api.get_states() record_time_unix = str(states.time).strip() record_time = datetime.utcfromtimestamp( states.time).strftime('%Y%m%d%H%M%S') file_name = 'open_sky_' + str(record_time) + '.csv' file_path = 'E:/ZeroG/opensky_files/' archived_path = "E:/ZeroG/opensky_files/Archived/" #Open file for writing file_out = open(file_path + file_name, 'w+') #Adding file header file_out.write( 'record_time,baro_altitude,callsign,geo_altitude,heading,icao24,last_contact,latitude,longitude,on_ground,origin_country,position_source,sensors,spi,squawk,time_position,velocity,vertical_rate,run_key' + '\n') for s in states.states: baro_altitude = str(s.baro_altitude).strip() callsign = str(s.callsign).strip() geo_altitude = str(s.geo_altitude).strip() heading = str(s.heading).strip() icao24 = str(s.icao24).strip() last_contact = str(s.last_contact).strip() latitude = str(s.latitude).strip() longitude = str(s.longitude).strip() on_ground = str(s.on_ground).strip() origin_country = str(s.origin_country).strip() position_source = str(s.position_source).strip() sensors = str(s.sensors).strip() spi = str(s.spi).strip() squawk = str(s.squawk).strip() time_position = str(s.time_position).strip() velocity = str(s.velocity).strip() vertical_rate = str(s.vertical_rate).strip() file_out.write(','.join([ record_time_unix, baro_altitude, callsign, geo_altitude, heading, icao24, last_contact, latitude, longitude, on_ground, origin_country, position_source, sensors, spi, squawk, time_position, velocity, vertical_rate, str(run_key) ]) + '\n') file_out.close() print('file generated') return file_name
def update(): lat = [] lon = [] api = OpenSkyApi( ) #retrieve flight data from https://opensky-network.org/apidoc/index.html states = api.get_states( bbox=(41, 49, -94, -76) ) #Create coordinate box of flights to track - min lat, max lat, min lon, max lon for s in states.states: lat.append(s.latitude) lon.append(s.longitude) dict = {'lat': lat, 'lon': lon} flight_data = pd.DataFrame(dict) wgs84_to_web_mercator(flight_data) flight_data = flight_data.fillna('No Data') n_roll = len(flight_data.index) plot_data.stream(flight_data.to_dict(orient='list'), n_roll) roundedlist = [] for x in lon: rounded = round(x) roundedlist.append(rounded) roundedlist = list(dict.fromkeys(roundedlist)) #This for loop plays notes - choose notes based on latitude or longitude coordinates you select for x in roundedlist: if x == -91: play_for( sine_wave(220, 4096), 250 ) #play_for(wave_type(hz of tone, sample rate), note length) - A3 1/8 note at 120 bpm elif x == -89: play_for(sine_wave(246.94, 4096), 250) #B3 elif x == -87: play_for(sine_wave(261.63, 4096), 250) #C4 elif x == -85: play_for(sine_wave(293.66, 4096), 250) #D4 elif x == -83: play_for(sine_wave(329.63, 4096), 250) #E4 elif x == -81: play_for(sine_wave(349.23, 4096), 250) #F4 elif x == -79: play_for(sine_wave(392.00, 4096), 250) #G4 elif x == -77: play_for(sine_wave(440, 4096), 250) #A4
def getFlights(bbox): states = [] api = OpenSkyApi() lon = [] lat = [] j = 0 # bbox = (min latitude, max latitude, min longitude, max longitude) try: states = api.get_states(bbox=bbox).states except: time.sleep(30) if (len(states) == 0): return getFlights(bbox) return states
def getData(self): api = OpenSkyApi() states = api.get_states() for s in states.states: self.altitude.append(s.altitude) self.callsign.append(s.callsign) self.heading.append(s.heading) self.icao24.append(s.icao24) self.latitude.append(s.latitude) self.longitude.append(s.longitude) self.on_ground.append(s.on_ground) self.origin_country.append(str(s.origin_country)) self.sensors.append(s.sensors) self.time_position.append(s.time_position) self.time_velocity.append(s.time_velocity) self.velocity.append(s.velocity) self.vertical_rate.append(s.vertical_rate)
def get_plane_full_data(bbox): api = OpenSkyApi() df_planes = pd.DataFrame(columns=os_columns) # bbox = (min latitude, max latitude, min longitude, max longitude) try: states = api.get_states(bbox=bbox) except: print('Open Sky Network API is not responding') for s in states.states: df_planes = df_planes.append( pd.DataFrame([[ s.icao24, s.callsign, s.origin_country, s.time_position, s.longitude, s.latitude, s.geo_altitude, s.on_ground, s.velocity, s.heading, s.sensors, s.baro_altitude, s.squawk, s.spi, s.position_source ]], columns=df_planes.columns)) return df_planes
class OpenSkyScanner(Scanner): ''' This scanner pulls all state vectors from the open sky network. To filter down to only include planes in sight from window: 1. make settings.py file 2. define a dict w/ the following format: coords = { window: ( , ), left: ( , ), right: ( , ) } Each value in coords is a tuple containing a lat and long. Together, these define the dimensions of the area in which the scanner will search for planes ''' def __init__(self): self.api = OpenSkyApi() self.pt1 = Point(*settings.coords['window']) self.pt2 = Point(*settings.coords['right']) self.pt3 = Point(*settings.coords['left']) def _sign(self, p1, p2, p3): return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y) def _in_range(self, state): if not (state.latitude and state.longitude) or state.on_ground: return False pt = Point(state.latitude, state.longitude) b1 = self._sign(pt, self.pt1, self.pt2) < 0.0 b2 = self._sign(pt, self.pt2, self.pt3) < 0.0 b3 = self._sign(pt, self.pt3, self.pt1) < 0.0 return b1 == b2 == b3 def _get_states(self): return self.api.get_states().states def nearby(self): states = self._get_states() return [state for state in states if self._in_range(state)]
def plot_planes_in_us(ims): api = OpenSkyApi() states = api.get_states(bbox=(13, 58, -144, -53)) lat = [] lon = [] icao = [] for s in states.states: ''' print("(%r, %r, %r, %r, %r)" % (s.longitude, s.latitude, s.baro_altitude, s.velocity, s.icao24)) ''' lon.append(s.longitude) lat.append(s.latitude) icao.append(s.icao24) # plt.figure(figsize=(12, 6)) m = Basemap(projection='merc', llcrnrlat=13, urcrnrlat=58, llcrnrlon=-144, urcrnrlon=-53, resolution='c') m.drawstates() m.drawcountries(linewidth=1.0) m.drawcoastlines() map_lon, map_lat = m(*(lon, lat)) ims.append(m.plot(map_lon, map_lat, 'b.')) ''' for i in range(len(icao)): if icao[i] == 'aa56b4': ims.append(m.plot(map_lon[i], map_lat[i], 'r.')) print('hi', icao[i]) ''' ''' # Doesn't work, need a large if statement outside the loop checking if # the desired icao number exists else: ims.append(m.plot(map_lon, map_lat, 'b.')) ''' # plt.show() return ims
def pull_opensky(planes): import configparser main_config = configparser.ConfigParser() main_config.read('./configs/mainconf.ini') from opensky_api import OpenSkyApi planeData = None opens_api = OpenSkyApi( username=None if main_config.get('OPENSKY', 'USERNAME').upper() == "NONE" else main_config.get('OPENSKY', 'USERNAME'), password=None if main_config.get('OPENSKY', 'PASSWORD').upper() == "NONE" else main_config.get('OPENSKY', 'PASSWORD').upper()) failed = False icao_array = [] for key in planes.keys(): icao_array.append(key.lower()) try: planeData = opens_api.get_states(time_secs=0, icao24=icao_array) except Exception as e: print("OpenSky Error", e) failed = True return planeData, failed
def read_source(self): api = OpenSkyApi(username='******', password='******') states = api.get_states() df = pd.DataFrame.from_items([ ('time', states.time), ('origin_country', self._convert_state_api('origin_country', states.states)), ('callsign', list( map(str.strip, self._convert_state_api('callsign', states.states)))), ('longitude', self._convert_state_api('longitude', states.states)), ('latitude', self._convert_state_api('latitude', states.states)), ('altitude', self._convert_state_api('altitude', states.states)), ]) filter_out = (df['origin_country'] == self.source) \ & df['callsign'] \ & ~np.isnan(df['longitude']) \ & ~np.isnan(df['latitude']) \ & ~np.isnan(df['altitude']) return df[filter_out]
def test(): #объект всех самолетов api = OpenSkyApi() count = [] # bbox = (min latitude, max latitude, min longitude, max longitude) states = api.get_states() #присвоение каждому самолету номер #для того чтобы в телеграме узнать информацию о нем counts = 1 for s in states.states: if "AFL" in s.callsign: count.append([ s.icao24, s.callsign, s.last_contact, s.longitude, s.latitude, s.velocity, s.geo_altitude, s.heading, s.on_ground, counts, s.origin_country ]) counts += 1 x = "" #формировка запроса для карт (обозначение меток) for i in count: x = x + str(i[3]) + "," + str(i[4]) + "," + str(i[9]) + "~" return [count, x]
def get_last_states(self): s = None while True: try: api = OpenSkyApi() s = api.get_states() break except: s = None print("Get states error. Reload...") columns = s.states[0].keys sky_list = [state.__dict__ for state in s.states] sky_frame = pd.DataFrame(sky_list, columns=columns) del (sky_frame["sensors"]) sky_frame["time_position"] = pd.to_datetime(sky_frame["time_position"], unit="s") sky_frame["last_contact"] = pd.to_datetime(sky_frame["last_contact"], unit="s") sky_frame["create_date"] = datetime.now() return sky_frame
def call_opensky_api(lowerboundlat, upperboundlat, lowerboundlong, upperboundlong): ''' Call the opensky api return states if there are any else return empty list ''' try: api = OpenSkyApi() #min_latitude, max_latitude, min_longitude, max_longitude states = api.get_states(bbox=(lowerboundlat, upperboundlat, lowerboundlong, upperboundlong)) if len(states.states) >= 1: return states.states #else emptystatestring = [] print("No planes in range") return emptystatestring except Exception as exept: print("Opensky api call broke: {0}".format(exept)) print(sys.exc_info()[0]) print(traceback.format_exc()) emptystatestring = [] return emptystatestring
def find_current_planes(bounding_box, current_location): print("\nFinding planes within distance") api = OpenSkyApi() # bbox = (min latitude, max latitude, min longitude, max longitude) states = api.get_states(bbox=(bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3])) print("Please wait...") for s in states.states: a = numpy.array((current_location[0], current_location[1], 0)) height = s.baro_altitude if height == None: height = 0 b = numpy.array((s.latitude, s.longitude, height)) distance = numpy.linalg.norm(a-b) print(("\nCallsign: " + bcolors.FAIL + "%r" + bcolors.ENDC + "\nOrigin Country: " + bcolors.HEADER + "%r" + bcolors.ENDC + "\nLongitude: " + bcolors.OKBLUE + "%r" + bcolors.ENDC + "\nLatidue: " + bcolors.OKGREEN + "%r" + bcolors.ENDC + "\nVelocity: " + bcolors.WARNING + "%r" + "m/s" + bcolors.ENDC + "\nAltitude: " + bcolors.WARNING + "%r" + " meters" + bcolors.ENDC + "\nDistance from you: " + bcolors.FAIL + str(distance) + bcolors.ENDC + " meters" + "\nOn Ground: " + bcolors.ENDC + "%r" + bcolors.ENDC) % (s.callsign, s.origin_country, s.longitude, s.latitude, s.velocity, s.baro_altitude, s.on_ground)) print("Planes found")
class PlaneState(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.api = OpenSkyApi() self.data = {} def fetch(self): data = self.api.get_states() if data is not None: self.data = data def plane_info(self, callsign): res = [s for s in self.data.states if s.callsign.startswith(callsign)] if not res: return None if len(res) == 1: return res[0] raise Exception("Multiple matches for callsign {}: {}".format( callsign, res)) async def update_loop(self): while True: self.fetch() await asyncio.sleep(11)
class OpenSkyTraffic(object): def __init__(self, period=10., margin=1., timeout=60., verbose=False): self.period = period self.margin = margin self.timeout = timeout self.last_receive = time() self.verbose = verbose self._interface = IvyMessagesInterface("OpenSkyTraffic") self._opensky = OpenSkyApi() self.ac_list = {} self.intruder_list = {} self.running = False if self.verbose: print("Starting opensky interface...") # subscribe to FLIGHT_PARAM ground message self._interface.subscribe(self.update_ac, PprzMessage("ground", "FLIGHT_PARAM")) def stop(self): if self.verbose: print("Shutting down opensky interface...") self.running = False if self._interface is not None: self._interface.shutdown() def __del__(self): self.stop() def update_ac(self, ac_id, msg): # update A/C info self.last_receive = time() self.ac_list[ac_id] = (self.last_receive, float(msg['lat']), float(msg['long'])) def filter_ac(self): # purge timeout A/C timeout = time() - self.timeout for ac, (t, lat, lon) in self.ac_list.items(): if t < timeout: del self.ac_list[ac] def compute_bbox_list(self): bbox = [] # for now assume that all UAVs are close enough, so merge all boxes into one # future improvement could handle groups of UAVs far appart lat_min, lat_max, lon_min, lon_max = None, None, None, None for ac, (t, lat, lon) in self.ac_list.items(): if lat_min is None: lat_min = lat lat_max = lat lon_min = lon lon_max = lon else: lat_min = min(lat, lat_min) lat_max = max(lat, lat_max) lon_min = min(lon, lon_min) lon_max = max(lon, lon_max) if lat_min is not None: bbox.append((lat_min-self.margin, lat_max+self.margin, lon_min-self.margin, lon_max+self.margin)) return bbox def get_intruders(self): self.filter_ac() bbox = self.compute_bbox_list() # request surounding aircraft to opensky-network self.intruder_list = {} for bb in bbox: states = self._opensky.get_states(bbox=bb) if states is not None: for s in states.states: self.intruder_list[s.callsign] = s def send_intruder_msgs(self): self.get_intruders() def val_or_default(val, default): if val is None: return default else: return val for i in self.intruder_list: intruder = self.intruder_list[i] if intruder.callsign is not None and len(intruder.callsign) > 0: msg = PprzMessage("ground", "INTRUDER") msg['id'] = intruder.icao24 msg['name'] = intruder.callsign.replace(" ", "") msg['lat'] = int(intruder.latitude * 1e7) msg['lon'] = int(intruder.longitude * 1e7) msg['alt'] = int(val_or_default(intruder.geo_altitude, 0.) * 1000.) msg['course'] = val_or_default(intruder.heading, 0.) msg['speed'] = val_or_default(intruder.velocity, 0.) msg['climb'] = val_or_default(intruder.vertical_rate, 0.) msg['itow'] = intruder.time_position if self.verbose: print(msg) self._interface.send(msg) def run(self): try: self.running = True t = 0. while self.running: t = t + 0.1 # increment timer until next update time is reach if t > self.period: self.send_intruder_msgs() t = 0. sleep(0.1) # wait a short time except KeyboardInterrupt: self.stop() except Exception as e: print("Failing with: "+str(e)) self.stop()