|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Example usage of the OpenSky Network API client. |
| 5 | +# |
| 6 | +# Retrieves all aircraft currently over Germany and prints a summary, |
| 7 | +# then shows which of your own receivers are currently active. |
| 8 | +# |
| 9 | +# Author: Jannis Lübbe <luebbe@opensky-network.org> |
| 10 | +# URL: http://github.com/openskynetwork/opensky-api |
| 11 | +# |
| 12 | +import os |
| 13 | + |
| 14 | +from opensky_api import OpenSkyApi, TokenManager |
| 15 | + |
| 16 | +# Use credentials file if available, otherwise fall back to anonymous access. |
| 17 | +# Anonymous access has reduced rate limits and no access to own sensor data. |
| 18 | +_CREDENTIALS_PATH = "credentials.json" |
| 19 | + |
| 20 | + |
| 21 | +def fmt_alt(value): |
| 22 | + """Format an altitude value, omitting the unit if the value is None.""" |
| 23 | + return f"{value}m" if value is not None else "None" |
| 24 | + |
| 25 | + |
| 26 | +def main(): |
| 27 | + if os.path.exists(_CREDENTIALS_PATH): |
| 28 | + tm = TokenManager.from_json_file(_CREDENTIALS_PATH) |
| 29 | + print("Authenticated with credentials file.") |
| 30 | + else: |
| 31 | + tm = None |
| 32 | + print("No credentials file found, using anonymous access (reduced rate limits).") |
| 33 | + |
| 34 | + with OpenSkyApi(token_manager=tm) as api: |
| 35 | + # Get all aircraft currently over Germany (bounding box) |
| 36 | + print("\n--- Aircraft over Germany ---") |
| 37 | + states = api.get_states(bbox=(47.2, 55.1, 5.9, 15.1)) |
| 38 | + if states and states.states: |
| 39 | + for s in states.states: |
| 40 | + print( |
| 41 | + f"{s.icao24:8s} {s.callsign or '?':10s} {s.origin_country:20s} " |
| 42 | + f"baro={fmt_alt(s.baro_altitude)} " |
| 43 | + f"geo={fmt_alt(s.geo_altitude)} " |
| 44 | + f"{'on ground' if s.on_ground else 'airborne'}" |
| 45 | + ) |
| 46 | + else: |
| 47 | + print("No states received.") |
| 48 | + |
| 49 | + # Show which own receivers are currently active and delivering data. |
| 50 | + # Requires authentication. |
| 51 | + if tm is not None: |
| 52 | + print("\n--- Own receivers ---") |
| 53 | + my_states = api.get_my_states() |
| 54 | + if my_states and my_states.states: |
| 55 | + active_serials = set() |
| 56 | + for s in my_states.states: |
| 57 | + if s.sensors: |
| 58 | + active_serials.update(s.sensors) |
| 59 | + if active_serials: |
| 60 | + print(f"Active serials providing data: {sorted(active_serials)}") |
| 61 | + else: |
| 62 | + print("No sensor information available in state vectors.") |
| 63 | + else: |
| 64 | + print("No states received from own receivers.") |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments