예제 #1
0
    def __init__(self, codeIATA, parent=None):
        super(QueueModel, self).__init__(parent)

        self._QUEUE = []
        self._codeIATA = codeIATA

        self._fapi = FlightData()
        try:
            self._fapi.login('*****@*****.**', 'monrepo1')
            print('Logged in seccesfully...')
            self.update()
            print('Updated')
        except:
            print('Logged in failed.')
            sys.exit(0)
예제 #2
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 01:30:51 2020
@author: tridhachaudhuri
"""
from pyflightdata import FlightData
import csv
api = FlightData()

header = ['country', 'img']

file = open('country_list.csv', 'a+', newline='')
with file:
    writer = csv.writer(file)
    writer.writerow(header)
    file.close()

details = api.get_countries()
final = []
for d in details:
    country = d['country']
    img = d['img']
    row_list = []
    row_list.append(country)
    row_list.append(img)

    final.append(row_list)

file = open('country_list.csv', 'a+', newline='')
예제 #3
0
def log_airport_flight(airport_name, date):
    flights_dep = get_date_flight_airport_departures(airport_name, date)
    pathname = "./airport/" + airport_name + "/"
    filename = pathname + "departures_" + date.strftime("%d_%m_%Y") + ".json"
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "w") as output:
        output.write(json.dumps(flights_dep))

    flights_arr = get_date_flight_airport_arrival(airport_name, date)
    pathname = "./airport/" + airport_name + "/"
    filename = pathname + "arrivals_" + date.strftime("%d_%m_%Y") + ".json"
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "w") as output:
        output.write(json.dumps(flights_arr))


if __name__ == "__main__":
    f = FlightData()

    top_10_airport = [
        "ATL", "PEK", "DXB", "LAX", "HND", "ORD", "LHR", "HKA", "PVG", "CDG"
    ]

    for airport in top_10_airport:
        try:
            log_airport_flight(airport, datetime.date.today())
        except:
            print("Error while getting flight for airport: " + airport)
            traceback.print_exc()
        #Avoid DOS the API we have all the time in the world
        time.sleep(5)
예제 #4
0
파일: fly.py 프로젝트: Mykola-Z/MFM_project
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 18 21:05:56 2019

@author: mzly903
"""
# -*- coding: utf-8 -*-

import gmplot 
from pyflightdata import FlightData

f=FlightData()

AKL = f.get_airport_details('AKL')

HRK = f.get_airport_details('HRK')
  
latit_AKL, longit_AKL = AKL['position']['latitude'], AKL['position']['longitude']

latit_HRK, longit_HRK = HRK['position']['latitude'], HRK['position']['longitude']

latitude_list = [ latit_HRK, latit_AKL] 
longitude_list = [  longit_HRK ,longit_AKL] 
  
gmap3 = gmplot.GoogleMapPlotter(latit_AKL, longit_AKL, 73) 
  

gmap3.scatter( latitude_list, longitude_list, '# FF0000', size = 40, marker = False ) 

gmap3.plot(latitude_list, longitude_list, 'cornflowerblue', edge_width = 2.5) 
  
예제 #5
0
def main(argv):
    
    pd.options.mode.chained_assignment = None  # default='warn'
    
    parser = argparse.ArgumentParser(description='script to check flight radar data for a terminal')
    
    parser.add_argument('-m','--mac', help='mac address of terminal, eg -m 00:0d:2e:00:02:81 (no quotes !)', required=False)
    parser.add_argument('-t','--tail', help='tail nr of aircraft eg -t N482UA (no quotes !)', required=False)
    parser.add_argument('-p','--path', help='path to dmm.log.* file', required=False)
    parser.add_argument('-l','--modemlist', help='path to modem_list.csv, which can be fetched via rest_api_all_modems.py', required=True)
    
    args = vars(parser.parse_args())
   
    path_to_modem_list = args['modemlist']
    mac = args['mac']
    
    if mac is None:
        tail = args['tail']        
        modem_df = pd.read_csv(path_to_modem_list)  
        row = modem_df[modem_df['tail']==tail]
        mac = row.iloc[0]['mac']
    
    path = args['path']
    
    
    columns = ['dateTimes','mac','operational','located','event','airport']
    dfChanges = dmm.changes_to_dataframe(path, mac)
    
    #df = dmm.mobile_info_to_dataframe(path, mac)
    
    
    
    tail =get_flightradar_info_for_mac(mac,path_to_modem_list)

    api=FlightData()
    
    max_nr_entries = 100
    r = api.get_history_by_tail_number(tail)[-max_nr_entries:]
    
    m = json.dumps(r)
    rjson = json.loads(m)
    
    #print(rjson)
    
    for item in rjson:
        # first items are most recent    
        status = item["status"]["generic"]["status"]["text"]
        
        if status == "landed": # everything else is scheduled or estimated
            from_airport = str(item["airport"]["origin"]["name"])
            to_airport = str(item["airport"]["destination"]["name"])
            
            
            try:
                departure_utc = datetime.utcfromtimestamp(int(item["time"]["real"]["departure"]))
                departure_known = True
            except:
                departure_known = False
                
            try:
                arrival_utc = datetime.utcfromtimestamp(int(item["time"]["real"]["arrival"]))
                arrival_known = True
            except:
                arrival_known = False
            
            if departure_known:
                row=pd.Series([departure_utc, mac,'','',"departure",from_airport],columns)
                dfChanges = dfChanges.append([row],ignore_index=True)
                #print("departure " + str(departure_utc))
                
            if arrival_known:
                row=pd.Series([arrival_utc, mac,'','',"arrival",to_airport],columns)
                dfChanges = dfChanges.append([row],ignore_index=True)
                #print("arrival " + str(arrival_utc))
            
            #print("\n")
            
            
    # TODO: add beam switch events
    # 18/03/11-23:21:54.618 [I] [ility.DMM.Mobile.Fsm] 00:0d:2e:00:06:74 performs switch to beam 'BEAM_AMZ2_W02_0003' (active-beam: 'BEAM_AMC15_W06_0027')
    
 
    dfMutes = dmm.txmutes_to_dataframe(path, mac)
    dfBeams = dmm.beam_info_to_dataframe(path, mac)    
    dfSLA = pd.concat([dfMutes,dfChanges,dfBeams])
    
    dfSLA = dfSLA.sort_values(by='dateTimes',ascending=True)
    dfSLA.to_csv('input_for_sla.csv', index=False)
예제 #6
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 01:40:30 2020
@author: tridhachaudhuri
"""

from pyflightdata import FlightData
import csv

api = FlightData()
#import pandas as pd

airport_iata = []

with open('country_list.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0

    for row in csv_reader:
        if line_count == 0:
            line_count += 1
        else:
            airport_iata.append(row[0])

header = ['country', 'name', 'iata', 'lat', 'lon']

file = open('country_airport.csv', 'a+', newline='')
with file:
    writer = csv.writer(file)
    writer.writerow(header)
예제 #7
0
 def __init__(self, airport_dep, airport_arr):
     f = FlightData()
     self.airport_dep = f.get_airport_details(airport_dep)
     self.airport_arr = f.get_airport_details(airport_arr)
예제 #8
0
class QueueModel(QAbstractTableModel):

    # Roles definitions
    #
    QueueTypeRole = Qt.UserRole + 1
    LiveRole = Qt.UserRole + 2
    FlightIATARole = Qt.UserRole + 3
    FlightICAORole = Qt.UserRole + 4
    ICAODEPRole = Qt.UserRole + 5
    ACFTRole = Qt.UserRole + 6
    ETARole = Qt.UserRole + 7
    ETAUTCRole = Qt.UserRole + 8
    ETAUTCHourRole = Qt.UserRole + 9
    GroundSpeedRole = Qt.UserRole + 10

    _roleNames = {
        QueueTypeRole: b"queue_type",
        LiveRole: b"live",
        FlightIATARole: b"flight_iata",
        FlightICAORole: b"flight_icao",
        ICAODEPRole: b"icao_dep",
        ACFTRole: b"acft",
        ETARole: b"eta",
        ETAUTCRole: b"eta_utc",
        ETAUTCHourRole: b"eta_utc_hour",
        GroundSpeedRole: b"ground_speed"
    }

    def __init__(self, codeIATA, parent=None):
        super(QueueModel, self).__init__(parent)

        self._QUEUE = []
        self._codeIATA = codeIATA

        self._fapi = FlightData()
        try:
            self._fapi.login('*****@*****.**', 'monrepo1')
            print('Logged in seccesfully...')
            self.update()
            print('Updated')
        except:
            print('Logged in failed.')
            sys.exit(0)

    def roleNames(self):
        return self._roleNames

    def flags(self, index):
        return Qt.ItemIsEditable | Qt.ItemIsEnabled

    def columnCount(self, parent=QModelIndex()):
        return len(self._roleNames)

    def rowCount(self, parent=QModelIndex()):
        return len(self._QUEUE)

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()

        row = index.row()
        col = role - Qt.UserRole - 1
        return self._QUEUE[row][col]

    def update(self):
        self.beginResetModel()

        self._QUEUE = []

        self.updateARR()
        print('(' + self._codeIATA + ') Arrival Queue updated succesfully.')
        print(self._QUEUE)

        #        self.updateDEP()
        #        print('(' + self._codeIATA + ') Departure Queue updated seccesfully.')

        self._QUEUE.sort(key=lambda row: row[7])

        self.endResetModel()

    def updateARR(self):
        arrs = self._fapi.get_airport_arrivals(self._codeIATA)
        arrs = json.loads(json.dumps(arrs))
        arrs = sorted(arrs,
                      key=lambda k: k['flight']['time']['other']['eta'],
                      reverse=True)
        arrs = arrs[::-1]

        for arr in arrs:
            live = arr['flight']['status']['live']

            if bool(live) is False:
                pass
            else:
                queue_type = 'ARR'

                flight_iata = arr['flight']['identification']['number'][
                    'default']  # IATA flight code
                flight_icao = arr['flight']['identification'][
                    'callsign']  # ICAO flight code

                dep_icao = arr['flight']['airport']['origin']['code'][
                    'icao']  # ICAO departure airport code

                if arr['flight']['aircraft'] == 'None':
                    acft = 'None'
                else:
                    acft = arr['flight']['aircraft']['model'][
                        'code']  # ACFT code

                eta = arr['flight']['status']['text']  # ETA local time
                eta_utc = arr['flight']['time']['estimated'][
                    'arrival']  # ETA UTC
                if eta_utc == 'None':
                    eta_utc = '0'

                if arr['flight']['airline'] == 'None':
                    airline_icao = 'None'
                else:
                    airline_icao = arr['flight']['airline']['code']['icao']

                if (eta.find('Estimated') != -1):
                    #                    ground_speed = acft_details.get_ground_speed(flight_icao, airline_icao)
                    ground_speed = 0

                    arr = [
                        queue_type, live, flight_iata, flight_icao, dep_icao,
                        acft,
                        str(eta),
                        int(eta_utc),
                        datetime.datetime.utcfromtimestamp(int(eta_utc)).hour,
                        ground_speed
                    ]

                    self.beginInsertRows(QModelIndex(), self.rowCount(),
                                         self.rowCount())
                    self._QUEUE.append(arr)
                    self.endInsertRows()

    def updateDEP(self):
        deps = self._fapi.get_airport_departures(self._codeIATA)
        deps = json.loads(json.dumps(deps))
        deps = sorted(deps,
                      key=lambda k: k['flight']['time']['other']['eta'],
                      reverse=True)
        deps = deps[::-1]

        for dep in deps:
            queue_type = 'DEP'
            live = dep['flight']['status']['live']
            if bool(live) is True:
                flight_iata = dep['flight']['identification']['number'][
                    'default']  # IATA flight code
                flight_icao = dep['flight']['identification'][
                    'callsign']  # ICAO flight code
                #                dep_icao = dep['flight']['airport']['origin']['code']['icao'] # ICAO departure airport code
                dep_icao = None

            if dep['flight']['aircraft'] == 'None':
                acft = 'None'
            else:
                acft = dep['flight']['aircraft']['model']['code']  # ACFT code

            eta = dep['flight']['status']['text']  # ETA local time
            eta_utc = dep['flight']['time']['estimated'][
                'departure']  # ETA UTC
            if eta_utc == 'None':
                eta_utc = '0'

            if dep['flight']['airline'] == 'None':
                airline_icao = 'None'
            else:
                airline_icao = dep['flight']['airline']['code']['icao']

            if (eta.find('Estimated') != -1):
                ground_speed = 0
                dep = [
                    queue_type, live, flight_iata, flight_icao, dep_icao, acft,
                    str(eta),
                    int(eta_utc),
                    datetime.datetime.utcfromtimestamp(int(eta_utc)).hour,
                    ground_speed
                ]

                self.beginInsertRows(QModelIndex(), self.rowCount(),
                                     self.rowCount())
                self._QUEUE.append(dep)
                self.endInsertRows()
예제 #9
0
def realtime_airport_arrivals(iata):
    fd = FlightData()
    airport_arrivals = fd.get_airport_arrivals(iata, page=1, limit=10)
    return jsonify(airport_arrivals)
예제 #10
0
def realtime_airport_weather(iata):
    fd = FlightData()
    airport_weather = fd.get_airport_weather(iata)
    return jsonify(airport_weather)
예제 #11
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 22:23:15 2020

@author: tridhachaudhuri
"""

from pyflightdata import FlightData
import csv
api = FlightData()
#import pandas as pd

airport_iata = []

with open('US_airlines.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            line_count += 1
        else:
            airport_iata.append(row[0])

#airport_iata=["LAX","JFK"]

header = [
    'airport_iata', 'url', 'avg_rating', 'total_rating', 'comment',
    'author_facebookid', 'author_name', 'timestamp_date', 'timestamp_time',
    'number_of_reviews', 'number_of_evaluation'
]
예제 #12
0
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 11:54:16 2018

@author: aro

    prerequisite is having run
    "pip install pyflightdata"

"""
import json
from datetime import datetime
from pyflightdata import FlightData

api = FlightData()

max_nr_entries = 100
r = api.get_history_by_tail_number('N812UA')[-max_nr_entries:]

m = json.dumps(r)
rjson = json.loads(m)

#print(rjson)

for item in rjson:
    # first items are most recent
    status = item["status"]["generic"]["status"]["text"]

    if status == "landed":  # everything else is scheduled or estimated
        print('from :' + str(item["airport"]["origin"]["name"]))
        print('to: ' + str(item["airport"]["destination"]["name"]))
예제 #13
0
    print ("query: ", query)
    print ("")
    #sys.exit()

#if __name__ == "__main__":
#   main()

#------------------------------------------------
#  MAIN
#------------------------------------------------

# If using API credentials
if apicreds == 1 :
    apiuser = "******"
    apipass = "******"
    api=FlightData(apiuser,apipass)
    api.login(apiuser,apipass)
    # Don't forget to: api.logout()
else :
    api=FlightData()    # Skip API credentials


if query == 1 : 
    if nmax == 0:
        alist = api.get_airport_arrivals(airport);    # Return: a JSON dictionary of xxxxx 
    else :
        alist = api.get_airport_arrivals(airport, page=1, limit=nmax); 
    if not alist : iataerr();
elif query == 2 : 
    if nmax == 0 :
        alist = api.get_airport_departures(airport);  # Return: a JSON dictionary of xxxxx
예제 #14
0
def realtime_airport_arrivals(iata):
    fd = FlightData()
    airport_arrivals = fd.get_airport_arrivals(iata, page=1, limit=10)
    airport_departures = fd.get_airport_departures(iata, page=1, limit=10)
    airport_flights = airport_arrivals + airport_departures
    return jsonify(airport_flights)
예제 #15
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 22:23:15 2020

@author: tridhachaudhuri
"""


from pyflightdata import FlightData
import csv
api=FlightData()
#import pandas as pd

airport_iata=[]


with open('US_airlines.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            line_count += 1
        else:
            airport_iata.append(row[0])


#airport_iata=["LAX","JFK"]

header = ['airport_iata','name','iatacode','icaocode','delayindex_arrivals','delayindex_departures','stats',
          'latitude','longitude','elevation_m','elevation_ft','timezone_name','timezone_offset',
예제 #16
0
def realtime_airport_departures(iata):
    fd = FlightData()
    airport_departures = fd.get_airport_departures(iata, page=1, limit=10)
    return jsonify(airport_departures)
예제 #17
0
def flights():
    while True:
        f = FlightData()
        airport = "DUB"
        arrival_list = f.get_airport_arrivals(airport, 1, 10)
        departures_list = f.get_airport_departures(airport, 1, 38)

        doc = open("template.html")
        soup = bs(doc)

        #iterate through current arriving flights and save data to dict
        #and place in correct location in table
        x = 1
        for flights in arrival_list:
            arrival_dict = {}

            #save flight data to dict
            arrival_dict["flightNumber"] = flights["flight"]["identification"]["number"]["default"]
            airline = flights["flight"]["airline"]["name"]
            if len(airline) > 23:
                temp = airline[0:22]
                airline = "{0:<22}".format(temp)
            arrival_dict["airline"] = airline
            arrival_dict["terminal"] = flights["flight"]["airport"]["destination"]["info"]["terminal"]

            estArrivalTime = flights["flight"]["time"]["estimated"]["arrival"]
            if estArrivalTime != 'None':
                utc_time = datetime.fromtimestamp(int(estArrivalTime), timezone.utc)
                local_time = utc_time.astimezone()
                estArrivalTime = (local_time.strftime("%H:%M"))
            arrival_dict["estArrivalTime"] = estArrivalTime

            arrivalTime = flights["flight"]["time"]["scheduled"]["arrival"]
            utc_time = datetime.fromtimestamp(int(arrivalTime), timezone.utc)
            local_time = utc_time.astimezone()
            arrivalTime = (local_time.strftime("%H:%M"))
            arrival_dict["arrivalTime"] = arrivalTime

            origin = flights["flight"]["airport"]["origin"]["name"]
            if len(origin) > 35:
                temp = origin[0:34]
                origin = "{0:<34}".format(temp)
            arrival_dict["origin"] = origin

            #place flight data into table
            for tele in soup.find_all("td"):
                telep = tele.find_parent("tr")
                table = tele.find_parent("table")
                if table["id"] == "arrivals":
                    if telep["id"] == str(x):
                        tele.string = arrival_dict[tele["id"]]
            x += 1

        #iterate through current departing flights and save data to dict
        #and place in correct location in table
        x = 1
        for flights in departures_list:
            departure_dict = {}

            #save flight data to dict
            departure_dict["flightNumber"] = flights["flight"]["identification"]["number"]["default"]
            airline= flights["flight"]["airline"]["name"]
            if len(airline) > 23:
                temp = airline[0:22]
                airline = "{0:<22}".format(temp)
            departure_dict["airline"] = airline
            departure_dict["terminal"] = flights["flight"]["airport"]["origin"]["info"]["terminal"]

            estDepartureTime = flights["flight"]["time"]["estimated"]["departure"]
            if estDepartureTime != 'None':
                utc_time = datetime.fromtimestamp(int(estDepartureTime), timezone.utc)
                local_time = utc_time.astimezone()
                estDepartureTime = (local_time.strftime("%H:%M"))
            departure_dict["estDepartureTime"] = estDepartureTime

            departureTime = flights["flight"]["time"]["scheduled"]["departure"]
            utc_time = datetime.fromtimestamp(int(departureTime), timezone.utc)
            local_time = utc_time.astimezone()
            departureTime = (local_time.strftime("%H:%M"))
            departure_dict["departureTime"] = departureTime

            destination = flights["flight"]["airport"]["destination"]["name"]
            if len(destination) > 35:
                temp = destination[0:34]
                destination = "{0:<34}".format(temp)
            departure_dict["destination"] = destination

            #place flight data into table
            for tele in soup.find_all("td"):
                telep = tele.find_parent("tr")
                table = tele.find_parent("table")
                if table["id"] == "departures":
                    if telep["id"] == str(x):
                        tele.string = departure_dict[tele["id"]]
            x += 1

        #write changes to html file
        doc.close()
        html = soup.prettify("utf-8")
        with open("index.html", "wb") as file:
            file.write(html)

        time.sleep(180)
예제 #18
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 02:59:25 2020

@author: tridhachaudhuri
"""


from pyflightdata import FlightData
import csv
from datetime import date 
  

api=FlightData()

filename=''


def writeheader(filename):
    
            
    header = ['arrival_airport_iata','number','callsign', 'live', 'text','type_Arrival','color','diverted',
          'utc_millis','utc_date','utc_time','utc',
          'local_date','local_time','model_code','model_name','registration',
          'country_name','country_alpha2','country_alpha3','restricted','owner_name',
          'owner_iata','owner_icao','airline_name','airline_iata','airline_icao','airline_short',
          'origin_aiportcode_iata','origin_aiportcode_icao','origin_aiporttimezone_name','origin_aiporttimezone_offset','origin_aiporttimezone_abbr','origin_aiporttimezone_abbrname','origin_airport_terminal','origin_airport_baggage','origin_airport_gate','origin_airport_name','origin_airport_latitude','origin_airport_longitude','origin_airport_countryname','origin_airport_countrycode','origin_airport_city','dest_airport_timezone_name','dest_airport_timezone_offset','dest_airport_timezone_abbr','dest_airport_timezone_abbrname','dest_airport_terminal','dest_airport_baggage','dest_airport_gate','scheduled_departuredate','scheduled_departuretime','scheduled_arrivaldate','scheduled_arrivaltime',
          'real_departuredate','real_departuretime','estimated_arrivaldate','estimated_arrivaltime']

예제 #19
0
 def sign_in(login, password):
     flight_data = FlightData()
     flight_data.login(login, password)
     return flight_data