Let's Build a Flight Tracker Part 1: OpenSky API
A nice big military aircraft Hmmm, I wonder what callsign that is there.

Let's Build a Flight Tracker Part 1: OpenSky API

Welcome to my first LinkedIn Python tutorial. My name is Henry, I fix computers and remove malware. I am a former Private Client Banker at Chase. Today we are going to be building a flight tracker using Python and the OpenSky API.

LEGAL DISCLAIMER:

Tracking airplanes using the OpenSky API is legal because the API accesses publicly available flight information from Automatic Dependent Surveillance-Broadcast (ADS-B) technology. This technology transmits information from aircraft, such as their GPS position, flight number, and altitude, which is then picked up by receivers on the ground and shared with services like OpenSky. The information shared is not considered confidential and is intended to improve air traffic control and safety. It's important to note that the use of flight information obtained through the API should comply with applicable laws and regulations, and not be used for illegal or malicious purposes.

Now that I got the legal disclaimer out of the way let me demonstrate the output of the code I created.


/usr/bin/python3.10 /home/bot/PycharmProjects/plane/tracker.py?
{'ICAO24': 'a33716', 'Callsign': 'AAL2280 ', 'Latitude': 37.6155, 'Longitude': -122.3619, 'Geo Altitude': -7.62, 'On Ground': False, 'Velocity': 71.57, 'True Track': 297.85}        

Wow that is a lot of garbage right there, lets break it down. We see the ICAO24 of the aircraft and the callsign. The ICAO24 is a unique identifier assigned to an aircraft by the International Civil Aviation Organization (ICAO). It is a 24-bit hexadecimal identifier used to identify an aircraft, much like a license plate number on a car. We also see a lot of other information that is returned from the ICAO24. I will get into that soon.

The callsign is a unique identifier assigned to an aircraft in flight. It is usually composed of a combination of letters and numbers and is used by air traffic control (ATC) to communicate with the aircraft during its flight. The callsign is usually issued by the aircraft's operator and may differ from flight to flight. It provides a quick and easy way for ATC to communicate with the aircraft, rather than using its ICAO24 identifier or other less recognizable information.

The OpenSky API has a nice Python return type over at the GitHub for hunting down information using an ICAO24 lets go take a look.

Here is a screenshot of what we need: class opensky_api.StateVector(arr)

No alt text provided for this image
That is a lot of information per aircraft. And it's FREE?

The opensky_api.StateVector class is a class in the opensky_api library that represents a single state vector, which is a snapshot of the current state of an aircraft. The arr parameter is an array-like object that contains the state vector data.

This is going to be a great starting point for our little tracker. Right now, you need to go to OpenSky API and go get a username and password so we can use this method. I already got an account; my username is Henry and my password is 123456. You can hack me if you like.

Let's get coding. I am going to assume for this tutorial that you are an intermediate level python programmer. if not please pay attention to all the comments. If you have questions, please message me. Also, if you are new, just copy and paste the code into your Python IDE and run it! The best way to learn is breaking things and examining bugs!

import opensky_api

def get_aircraft_info(icao24, username="Henry", password="123456"):
    # Create an instance of the OpenSkyApi class with the provided username and password
    api = opensky_api.OpenSkyApi(username=username, password=password)

    # Get the states for the aircraft with the specified icao24 identifier
    states = api.get_states(icao24=icao24)

    # Check if there are any states returned
    if states.states:
        # If there are states, select the first one
        sv = states.states[0]
        # Return the state information as a dictionary
        return {
            'ICAO24': sv.icao24,
            # Unique identifier for the aircraft
            'Callsign': sv.callsign,
            # Callsign of the aircraft
            'Latitude': sv.latitude,
            # Latitude of the aircraft's current position
            'Longitude': sv.longitude,
            # Longitude of the aircraft's current position
            'Geo Altitude': sv.geo_altitude,
            # Altitude above sea level in meters
            'On Ground': sv.on_ground,
            # Boolean indicating whether the aircraft is on the ground or not
            'Velocity': sv.velocity,
            # Velocity of the aircraft in meters per second
            'True Track': sv.true_track,
            # Heading of the aircraft in degrees from North
        }
    else:
        # If there are no states returned, return None
        return None
# Call the function with the icao24 identifier "icao24"
print(get_aircraft_info("icao24"))        

Look back at the picture for the article. I see something!

No alt text provided for this image
ZM400? Some kind of gang sign?

ZM400? What can Google tell us?

Cool!

"ZM400" is a registration. The airplane has a name even. The Airbus A400M is a military transport aircraft developed by Airbus Defense and Space. It is designed to provide tactical and strategic airlift capabilities to military forces, with a capacity to transport troops, heavy equipment, and supplies over long distances. The aircraft features a spacious cargo hold, high-performance turboprop engines, and advanced avionics. It can operate from rough and short airfields, as well as perform aerial delivery missions. The A400M has been ordered by several countries including Germany, France, Spain, the United Kingdom, and Turkey, among others. That registration there tells us the information we need!

I hope you took a glance at the code and the web page. I don't need every returned field because I'm not an Air Traffic Controller. Now one line of code is very very important.

import opensky_api        

How in God's name are we going to do that? After 4 hours of playing with package managers on Arch Linux and almost having my girlfriend break up with me. I figured it out for you. And no you do not have to use Arch Linux that's just the distro I use.

Go over to the GitHub for OpenSky.

We need the opensky_api so just download the code.

No alt text provided for this image

It will be in a folder in your downloads so extract the file.

No alt text provided for this image

Ok here is the tricky part. We are going to use the console in order to enter the specific folder for the python part of the API and then run a specific command.

python setup.py install        

This will ensure the import works properly.

No alt text provided for this image
Yes I use XFCE

Now we can import the python version of the API for use in the program. Remember I am assuming you understand then basics of software installation and python here. and yes, it's "python setup.py install"

Let's go find us an aircraft people, I'm getting tired of waiting here. We are going to find all kinds of planes and helicopters and UFOs flying over our heads. I live next to a hospital so I think there should be some helicopters around.

No alt text provided for this image
Helicopter near Minden!

I used the website FlightRadar24 to see flights in my area and I see a helicopter near Minden, Nevada! Maybe it's a private owner or a medical transport? Let's check it out!

Here is some information about the helicopter.

No alt text provided for this image

The Airbus Helicopters H125, previously known as the Eurocopter AS350 écureuil, is a light utility helicopter designed for a wide range of missions, including passenger transport, aerial work, and law enforcement. It is equipped with a powerful engine, high set fenestron tail rotor, and a spacious cabin. The H125 has a reputation for being easy to fly and maintain, with a low operating cost. It has a proven track record in demanding environments, including high altitudes, hot temperatures, and rough terrain. The helicopter is widely used around the world and has a strong customer base in industries such as tourism, emergency medical services, and firefighting.

And we're gonna track it. GET ME THAT ICAO24!

No alt text provided for this image

Now paste it but use lowercase for the letters or it won't work.

No alt text provided for this image
Wow I am so excited you guys...

This should return some data.

/usr/bin/python3.10 /home/bot/PycharmProjects/plane/tracker.py
None

Process finished with exit code 0y        

WHAT?! WHY? I DID EVERYTHING RIGHT! Oh, it would seem the helicopter was actually on the landing pad at the time. It's not transmitting data to our local ADSB receivers. ADSB receivers are installed on both aircraft and ground-based systems and receive signals transmitted via the 1090 MHz frequency. The data received by the receiver is then processed and displayed on a screen, allowing air traffic controllers to monitor the movements of aircraft in their airspace.

Lets find a new victim...

No alt text provided for this image
Alaska Airlines, where you can have your emotional support Emu sit next to you.

Type in "a726fb" in the same area I showed you.

/usr/bin/python3.10 /home/bot/PycharmProjects/plane/tracker.py
{'ICAO24': 'a726fb', 'Callsign': 'ASA1061 ', 'Latitude': 39.4091, 'Longitude': -119.7473, 'Geo Altitude': 10408.92, 'On Ground': False, 'Velocity': 195.05, 'True Track': 349.67}


Process finished with exit code 0

?        

We did it. We have the information, we have Latitude, Longitude, Geo Altitude, an "On Ground" Boolean status, a velocity, and a "True Track".

This is a lot of information to parse through, I already have big plans for this code in a future article.

In review, this is a Python function that uses the opensky_api library to retrieve information about an aircraft based on its icao24 identifier. The function creates an instance of the OpenSky API class with the provided username and password, then retrieves the states for the aircraft using the get_states() method and passing the icao24 parameter. If there are any states returned, the function selects the first one and returns the state information as a dictionary with various details such as the aircraft's callsign, latitude, longitude, altitude, on-ground status, velocity, and true track. If there are no states returned, the function returns None.

Here are some ideas to improve the code:

  1. Error handling: Add error handling to the code in case the API request fails. For example, if the API raises an exception or returns an error, the function could catch the exception and return an error message. We can use try and except here.
  2. Input validation: we can validate the input parameters such as the icao24 identifier to ensure that they are in the correct format. Remember that we have to type lowercase letters? We can format that and use argparse to make the code easier to run.
  3. Additional information: we can add more information to the returned dictionary if available in the API response, I plan to make new methods to find the nearest airport and use True Track to determine if the airplane is flying to or away from the airport.
  4. Logging: Add logging to the code to log information about the API requests and responses, which can be useful for debugging and monitoring the function's behavior. I plan on logging flight data to a .csv file.

Thank you for reading and coding along - Henry

Claus Ruttgers

Financial Analyst at Intrado

1 年

Henry, I am having some issues with the downloading of the API. It looks like you had to do some troubleshooting as well. Are you available to help me troubleshoot why my setup file isn't running?

回复
Nikolay Klimchuk

Director, Software Engineering at London Stock Exchange Group (LSEG)

1 年

Too bad OpenSky API is down for almost a month

回复

要查看或添加评论,请登录

Henry Meier的更多文章

  • Chess Part 2: Finish The Game

    Chess Part 2: Finish The Game

    Welcome back, today we are working on the Front-End. OK, on to the big boy file.

  • Chess Part 1: Multiplayer

    Chess Part 1: Multiplayer

    It's been quite some time since I was able to write an article. Many of my articles have started to blow up so I…

  • Neural Network in C Part 4: Hidden Layer Analysis

    Neural Network in C Part 4: Hidden Layer Analysis

    I want to look under the hood today. Obviously we can see the input layer and output layer.

  • Neural Network in C Part 3: Assembly VS C

    Neural Network in C Part 3: Assembly VS C

    Our Neural Network is fast but we can make it even faster. We will convert the code to assembly, then race the two side…

    2 条评论
  • Neural Network in C Part 2: C Programming

    Neural Network in C Part 2: C Programming

    In this article, we explore how to build a simple feed forward neural network in C to recognize handwritten digits from…

  • Neural Network in C Part 1: Idea

    Neural Network in C Part 1: Idea

    Welcome, normally I enjoy programming in Python and using the TensorFlow library to create machine learning…

  • Free CRM Part 2: Client Notes, Dark Mode, Adding Customers

    Free CRM Part 2: Client Notes, Dark Mode, Adding Customers

    We have a lot of stuff to add to our free CRM software. Small businesses are counting on us! Small businesses don't…

  • Free CRM Part 1: Idea

    Free CRM Part 1: Idea

    Salesforce is expensive. Lets make our own CRM (Customer Relationship Management) software.

  • Firmware Engineering Part 3: OLED Display

    Firmware Engineering Part 3: OLED Display

    The temperature/humidity sensor works. Currently, this device communicates with a website and shares data over MQTT.

  • Firmware Engineering Part 2: Data Logging Website

    Firmware Engineering Part 2: Data Logging Website

    Last article, we wrote a simple MicroPython program for the ESP32. This device broadcasts raw temperature and humidity…

社区洞察

其他会员也浏览了