Exemplo n.º 1
0
    def process_messages(self, messages):
        for msg, ts in messages:
            nstr = len(msg)
            df = pms.df(msg)

            if (nstr == 14) and (df not in self.short_msg_dfs):
                continue

            if (nstr == 28) and (df not in self.long_msg_dfs):
                continue

            icao = pms.adsb.icao(msg)
            line = ['%.9f' % ts, '%02d' % df, icao, msg]

            if self.debug:
                print(line)
                continue

            self.csvbuff.append(line)
            if len(self.csvbuff) > 1000:
                # get the current data/hour for the file name
                dh = str(datetime.datetime.utcnow().strftime("%Y%m%d_%H"))
                csv_path = dataroot + 'RAW_%s.csv' % dh

                with open(csv_path, 'a') as fcsv:
                    writer = csv.writer(fcsv)
                    writer.writerows(self.csvbuff)
                self.csvbuff = []
Exemplo n.º 2
0
    def handle_messages(self, messages):

        if self.stop_flag.value is True:
            self.stop()
            return

        for msg, t in messages:
            if len(msg) < 28:  # only process long messages
                continue

            df = pms.df(msg)

            if df == 17 or df == 18:
                self.local_buffer_adsb_msg.append(msg)
                self.local_buffer_adsb_ts.append(t)
            elif df == 20 or df == 21:
                self.local_buffer_commb_msg.append(msg)
                self.local_buffer_commb_ts.append(t)
            else:
                continue

        if len(self.local_buffer_adsb_msg) > 1:
            self.raw_pipe_in.send({
                "adsb_ts": self.local_buffer_adsb_ts,
                "adsb_msg": self.local_buffer_adsb_msg,
                "commb_ts": self.local_buffer_commb_ts,
                "commb_msg": self.local_buffer_commb_msg,
            })
            self.reset_local_buffer()
Exemplo n.º 3
0
    def handle_messages(self, messages):
        # get the current date file
        today = str(datetime.datetime.now().strftime("%Y%m%d"))
        csvfile = dataroot + 'ADSB_RAW_%s.csv' % today

        with open(csvfile, 'a') as f:
            writer = csv.writer(f)

            for msg, ts in messages:
                if len(msg) < 28:
                    continue

                df = pms.df(msg)

                if df != 17:
                    continue

                if '1' in pms.crc(msg):
                    continue

                addr = pms.adsb.icao(msg)
                tc = pms.adsb.typecode(msg)

                line = ['%.6f'%ts, addr, '%02d'%tc, msg]

                writer.writerow(line)
Exemplo n.º 4
0
Arquivo: base.py Projeto: junzis/sil
    def process_messages(self, messages):
        for msg, ts in messages:
            nstr = len(msg)
            df = pms.df(msg)

            if df not in self.df_filter:
                continue

            if (nstr == 14) and (df not in self.short_msg_dfs):
                continue

            if (nstr == 28) and (df not in self.long_msg_dfs):
                continue

            icao = pms.adsb.icao(msg)
            line = ["%.9f" % ts, "%02d" % df, icao, msg]

            if self.debug:
                print(line)
                continue

            self.csvbuff.append(line)
            if len(self.csvbuff) > self.buff_size:
                # get the current data/hour for the file name
                dh = str(datetime.datetime.utcnow().strftime("%Y%m%d_%H"))
                csv_path = self.output_dir + "RAW_%s.csv" % dh

                with open(csv_path, "a") as fcsv:
                    writer = csv.writer(fcsv)
                    writer.writerows(self.csvbuff)
                self.csvbuff = []
Exemplo n.º 5
0
    def handle_messages(self, messages):
        # get the current date file
        today = str(datetime.datetime.now().strftime("%Y%m%d"))
        csvfile = dataroot + 'ADSB_RAW_%s.csv' % today

        for msg, ts in messages:
            if len(msg) < 28:
                continue

            df = pms.df(msg)

            if df != 17:
                continue

            if '1' in pms.crc(msg):
                continue

            addr = pms.adsb.icao(msg)
            tc = pms.adsb.typecode(msg)

            line = ['%.6f' % ts, addr, '%02d' % tc, msg]

            self.lines.append(line)

        if len(self.lines) > 1000:
            try:
                fcsv = open(csvfile, 'a')
                writer = csv.writer(fcsv)
                writer.writerows(self.lines)
                fcsv.close()
            except Exception, err:
                print err

            self.lines = []
Exemplo n.º 6
0
    def handle_messages(self, messages):
        # get the current date file
        today = str(datetime.datetime.now().strftime("%Y%m%d"))
        csvfile = dataroot + 'ELS_RAW_%s.csv' % today

        for msg, ts in messages:
            if len(msg) > 14:
                continue

            df = pms.df(msg)

            if df not in [4, 5, 11]:
                continue

            line = ['%.6f' % ts, 'DF%02d' % df, msg]

            self.lines.append(line)

        if len(self.lines) > 1000:
            try:
                fcsv = open(csvfile, 'a')
                writer = csv.writer(fcsv)
                writer.writerows(self.lines)
                fcsv.close()
            except Exception, err:
                print err

            self.lines = []
Exemplo n.º 7
0
    def handle_messages(self, messages):
        self.i += 1
        for msg, ts in messages:
            if len(msg) != 28:  # wrong data length
                continue

            df = pms.df(msg)

            if df != 17:  # not ADSB
                continue

            if pms.crc(msg) !=0:  # CRC fail
                continue

            icao = pms.adsb.icao(msg)
            tc = pms.adsb.typecode(msg)
            flight = None

            if icao in self.flights:
                flight = self.flights[icao]
            else:
                flight = Flight(icao)

            flight.last_seen = datetime.now()

            # Message Type Codes:  https://mode-s.org/api/
            if tc >= 1 and tc <= 4:
                # Typecode 1-4
                flight.call_sign = pms.adsb.callsign(msg).strip('_')
            elif tc >= 9 and tc <= 18:
                # Typecode 9-18 (airborne, barometric height)
                flight.location = pms.adsb.airborne_position_with_ref(msg,
                        self.lat_ref, self.lon_ref)
                flight.altitude_ft = pms.adsb.altitude(msg)
                flight.sent = False
            elif tc == 19:
                # Typecode: 19
                # Ground Speed (GS) or Airspeed (IAS/TAS)
                # Output (speed, track angle, vertical speed, tag):
                (flight.speed_kts, flight.track_angle_deg, flight.vertical_speed_fpm,
                    flight.speed_ref) = pms.adsb.velocity(msg)

            self.flights[icao] = flight

            if self.i > 10:
                self.i = 0
                #print("Flights: ", len(self.flights))
                for key in list(self.flights):
                    f = self.flights[key]
                    if f.has_info() and not f.sent:
                        #f.pretty_print()
                        f.json_print()
                        f.sent = True
                    elif f.last_seen < (datetime.now() - timedelta(minutes=5)):
                        #print("Deleting ", key)
                        del self.flights[key]
Exemplo n.º 8
0
 def _check_msg(self, msg):
     df = pms.df(msg)
     msglen = len(msg)
     if df == 17 and msglen == 28:
         if pms.crc(msg) == 0:
             return True
     elif df in [20, 21] and msglen == 28:
         return True
     elif df in [4, 5, 11] and msglen == 14:
         return True
def decode(msg, dt):
    if len(msg) == 28:  # wrong data length
        # print(msg,end='\n')
        df = pms.df(msg)
        if df == 17:
            icao = pms.adsb.icao(msg)
            if icao in plane:
                pass
            else:
                # insert icao to db
                icaosql = f"Insert Into airplane(ICAO) Value ('{icao}')"
                dbcur.execute(icaosql)

                # insert plane to list
                plane.append(icao)
                # create Position obj
                planedata.append(Position(icao))

            # get position index for planedata
            plane_index = plane.index(icao)

            tc = pms.adsb.typecode(msg)
            if 1 <= tc <= 4:
                callsign = pms.adsb.callsign(msg)
                print("ICAO: {} Callsign: {}".format(icao, callsign), end="\n")
                # update callsign to db
                callsign_sql = f"UPDATE `airplane` SET `callsign` = '{callsign}' WHERE `ICAO` = '{icao}'"
                dbcur.execute(callsign_sql)

            if tc == 19:
                airborne_velocity = pms.adsb.velocity(msg)
                print("ICAO: {} Speed: {} ".format(icao, airborne_velocity),
                      end="\n")
                # update ground_speed,heading,rate of climb to db
                velocity_sql = f"UPDATE `airplane` SET `ground_speed` = '{airborne_velocity[0]}', `heading` = '{airborne_velocity[1]}', `rate_of_climb` = '{airborne_velocity[2]}' WHERE `airplane`.`ICAO` = '{icao}'"
                dbcur.execute(velocity_sql)

            if 5 <= tc <= 18:
                altitude = pms.adsb.altitude(msg)
                print(f"ICAO: {icao} height: {altitude}", end="\n")
                altitude_sql = f"UPDATE `airplane` SET `altitude` = '{altitude}' WHERE `airplane`.`ICAO` = '{icao}'"
                dbcur.execute(altitude_sql)

                if pms.adsb.oe_flag(msg):
                    planedata[plane_index].msgodd(msg, dt)
                else:
                    planedata[plane_index].msgeven(msg, dt)

                planedata[plane_index].cal_pos()

            # update time of packet just recv
            live_sql = f"UPDATE `airplane` SET `live` = '{1}' WHERE `ICAO` = '{icao}'"
            dbcur.execute(live_sql)
            db.commit()
Exemplo n.º 10
0
 def _debug_msg(self, msg):
     df = pms.df(msg)
     msglen = len(msg)
     if df == 17 and msglen == 28:
         print(msg, pms.icao(msg), pms.crc(msg))
     elif df in [20, 21] and msglen == 28:
         print(msg, pms.icao(msg))
     elif df in [4, 5, 11] and msglen == 14:
         print(msg, pms.icao(msg))
     else:
         # print("[*]", msg)
         pass
Exemplo n.º 11
0
    def handle_messages(self, messages):
        for msg, ts in messages:
            if len(msg) != 28:  # wrong data length
                continue

            df = pms.df(msg)

            if df != 17:  # not ADSB
                continue

            if pms.crc(msg) != 0:  # CRC fail
                continue

            icao = pms.adsb.icao(msg)
            saved = self.r.get(icao)
            to_save = pms.get_all(msg)
            if saved is not None:
                saved = json.loads(saved)
                try:
                    if 'location_message' in saved and 'cpr_latitude' in to_save:
                        if saved['location_type'] == to_save['type'] and saved[
                                'cpr_format'] != to_save['cpr_format']:
                            if saved['cpr_latitude'] != to_save[
                                    'cpr_latitude'] and saved[
                                        'cpr_longitude'] != to_save[
                                            'cpr_longitude']:
                                gps = pms.adsb.position(
                                    msg, saved['location_message'], ts,
                                    saved['location_timestamp'])
                                if gps is not None:
                                    to_save['gps_latitude'] = gps[0]
                                    to_save['gps_longitude'] = gps[1]
                except:
                    pass

                saved.update(to_save)
                if 'cpr_latitude' in to_save:
                    saved['location_type'] = to_save['type']
                    saved['location_message'] = msg
                    saved['location_timestamp'] = ts
                self.r.set(icao, json.dumps(saved), ex=60)
            else:
                if 'cpr_latitude' in to_save:
                    to_save['location_type'] = to_save['type']
                    to_save['location_message'] = msg
                    to_save['location_timestamp'] = ts
                self.r.set(icao, json.dumps(to_save), ex=60)
Exemplo n.º 12
0
def start(msg):
    global aircrafts

    # verificação da mensagem
    try:
        if int(pms.crc(msg[0], encode=False)) != 0:
            with open('../mensagens/output/corrupted.txt', 'a') as f:
                f.write('{} {}\n'.format(msg[0], msg[1]))
        elif 17 != pms.df(msg[0]) != 18:
            with open('../mensagens/output/incorrectDF.txt', 'a') as f:
                f.write('{} {}\n'.format(msg[0], msg[1]))
        else:
            icao = pms.adsb.icao(msg[0])  # ICAO aeronave

            if icao not in aircrafts:
                aircrafts[icao] = Aircraft(icao)

            aircrafts[icao].code(msg)
    except:
        print("Erro com a mensage: ", msg)
Exemplo n.º 13
0
    def handle_messages(self, messages):
        # get the current date file
        today = str(datetime.datetime.now().strftime("%Y%m%d"))
        csvfile = dataroot + 'EHS_RAW_%s.csv' % today

        with open(csvfile, 'a') as f:
            writer = csv.writer(f)
            for msg, ts in messages:
                if len(msg) < 28:
                    continue

                df = pms.df(msg)

                if df not in [20, 21]:
                    continue

                addr = pms.ehs.icao(msg)

                line = ['%.6f'%ts, addr, msg]

                writer.writerow(line)
Exemplo n.º 14
0
    def handle_messages(self, messages):
        global ADSB_TS
        global ADSB_MSGS
        global EHS_TS
        global EHS_MSGS
        global TNOW
        global TFLAG

        for msg, ts in messages:
            if len(msg) != 28:  # wrong data length
                continue

            df = pms.df(msg)

            if df == 17:
                ADSB_TS.append(ts)
                ADSB_MSGS.append(msg)

            if df == 20 or df == 21:
                EHS_TS.append(ts)
                EHS_MSGS.append(msg)
Exemplo n.º 15
0
    def process_raw(self, adsb_ts, adsb_msgs, ehs_ts, ehs_msgs, tnow=None):
        """process a chunk of adsb and ehs messages received in the same
        time period.
        """
        if tnow is None:
            tnow = time.time()

        self.t = tnow

        local_ehs_updated_acs_buffer = []

        # process adsb message
        for t, msg in zip(adsb_ts, adsb_msgs):
            icao = pms.icao(msg)
            tc = pms.adsb.typecode(msg)

            if icao not in self.acs:
                self.acs[icao] = {}
                if self.correction:
                    try:
                        self.acs[icao]['magdev'] = acdb.loc[icao]['magdev']
                    except:  #no icao in database
                        self.acs[icao]['magdev'] = 0
                else:
                    self.acs[icao]['magdev'] = 0

            self.acs[icao]['t'] = t

            if 1 <= tc <= 4:
                self.acs[icao]['callsign'] = pms.adsb.callsign(msg)

            if (5 <= tc <= 8) or (tc == 19):
                vdata = pms.adsb.velocity(msg)
                if vdata is None:
                    continue

                spd, trk, roc, tag = vdata
                if tag != 'GS':
                    continue

                self.acs[icao]['gs'] = spd
                self.acs[icao]['trk'] = trk
                self.acs[icao]['roc'] = roc
                self.acs[icao]['tv'] = t

            if (5 <= tc <= 18):
                oe = pms.adsb.oe_flag(msg)
                self.acs[icao][oe] = msg
                self.acs[icao]['t' + str(oe)] = t

                if ('tpos' in self.acs[icao]) and (t - self.acs[icao]['tpos'] <
                                                   180):
                    # use single message decoding
                    rlat = self.acs[icao]['lat']
                    rlon = self.acs[icao]['lon']
                    latlon = pms.adsb.position_with_ref(msg, rlat, rlon)
                elif ('t0' in self.acs[icao]) and ('t1' in self.acs[icao]) and \
                     (abs(self.acs[icao]['t0'] - self.acs[icao]['t1']) < 10):
                    # use multi message decoding
                    try:
                        latlon = pms.adsb.position(self.acs[icao][0],
                                                   self.acs[icao][1],
                                                   self.acs[icao]['t0'],
                                                   self.acs[icao]['t1'],
                                                   self.lat0, self.lon0)
                    except:
                        # mix of surface and airborne position message
                        continue
                else:
                    latlon = None

                if latlon is not None:
                    self.acs[icao]['tpos'] = t
                    self.acs[icao]['lat'] = latlon[0]
                    self.acs[icao]['lon'] = latlon[1]
                    self.acs[icao]['alt'] = pms.adsb.altitude(msg)

        # process ehs message
        for t, msg in zip(ehs_ts, ehs_msgs):
            icao = pms.icao(msg)

            if icao not in self.acs:
                continue

            if self.correction:
                # Check DF20
                if pms.df(msg) == 20:
                    alt_ehs = pms.altcode(msg)

                    if ('alt' in self.acs[icao]) and (alt_ehs is not None):
                        if abs(self.acs[icao]['alt'] - alt_ehs) > 250:
                            continue
                    else:
                        # No ADS-B altitude yet, so no altitude comparision possible
                        continue

                # Check DF21
                if pms.df(msg) == 21:
                    squawk = pms.idcode(msg)

                    if squawk not in self.squawks:
                        self.squawks[squawk] = {}

                    if icao not in self.squawks[squawk]:
                        self.squawks[squawk][icao] = {}
                        self.squawks[squawk][icao]['count'] = 0

                    self.squawks[squawk][icao]['count'] += 1
                    self.squawks[squawk][icao]['ts'] = t

                    if self.squawks[squawk][icao]['count'] < 10:
                        # Reject if Squawk and ICAO combination has seen less than 10 times.
                        continue

            bds = pms.bds.infer(msg)

            if bds == 'BDS50,BDS60':
                try:
                    bds = pms.bds.is50or60(msg, self.acs[icao]['gs'],
                                           self.acs[icao]['trk'],
                                           self.acs[icao]['alt'])
                except:
                    pass

            if bds == 'BDS50':
                tas = pms.commb.tas50(msg)
                roll = pms.commb.roll50(msg)

                if tas and roll:
                    self.acs[icao]['t50'] = t
                    self.acs[icao]['tas'] = tas
                    self.acs[icao]['roll'] = roll
                    local_ehs_updated_acs_buffer.append(icao)

            elif bds == 'BDS60':
                ias = pms.commb.ias60(msg)
                hdg = pms.commb.hdg60(msg)
                mach = pms.commb.mach60(msg)

                if ias and hdg and mach:
                    self.acs[icao]['t60'] = t
                    self.acs[icao]['ias'] = ias
                    self.acs[icao]['hdg'] = hdg
                    self.acs[icao]['mach'] = mach
                    local_ehs_updated_acs_buffer.append(icao)

        # clear up old data
        for icao in list(self.acs.keys()):
            if self.t - self.acs[icao]['t'] > 180:
                del self.acs[icao]
                continue

            if ('t50' in self.acs[icao]) and (self.t - self.acs[icao]['t50'] >
                                              5):
                del self.acs[icao]['t50']
                del self.acs[icao]['tas']

            if ('t60' in self.acs[icao]) and (self.t - self.acs[icao]['t60'] >
                                              5):
                del self.acs[icao]['t60']
                del self.acs[icao]['ias']
                del self.acs[icao]['hdg']
                del self.acs[icao]['mach']

        self.add_ehs_updated_aircraft(local_ehs_updated_acs_buffer)

        if self.correction:
            for squawk in list(self.squawks):
                for icao in list(self.squawks[squawk]):
                    if self.t - self.squawks[squawk][icao]['ts'] > 300:
                        del self.squawks[squawk][icao]

    #                     print('deleted', squawk, icao)

        return
Exemplo n.º 16
0
    def process(
        self,
        time: datetime,
        msg: bytes,
        *args,
        spd: Optional[float] = None,
        trk: Optional[float] = None,
        alt: Optional[float] = None,
    ) -> None:

        if len(msg) != 28:
            return

        df = pms.df(msg)

        if df == 4 or df == 20:
            icao = pms.icao(msg)
            ac = self.acs[icao.lower()]
            ac.altcode = time, msg

        if df == 5 or df == 21:
            icao = pms.icao(msg)
            ac = self.acs[icao.lower()]
            ac.idcode = time, msg

        if df == 17 or df == 18:  # ADS-B

            if pms.crc(msg, encode=False) != 0:
                return

            tc = pms.adsb.typecode(msg)
            icao = pms.icao(msg)
            ac = self.acs[icao.lower()]

            if 1 <= tc <= 4:
                ac.callsign = time, msg

            if 5 <= tc <= 8:
                ac.surface = time, msg

            if tc == 19:
                ac.speed = time, msg

            if 9 <= tc <= 18:
                # This is barometric altitude
                ac.position = time, msg

            if 20 <= tc <= 22:
                # Only GNSS altitude
                pass

            # if 9 <= tc <= 18:
            #     ac["nic_bc"] = pms.adsb.nic_b(msg)

            # if (5 <= tc <= 8) or (9 <= tc <= 18) or (20 <= tc <= 22):
            #     ac["HPL"], ac["RCu"], ac["RCv"] = pms.adsb.nuc_p(msg)

            #     if (ac["ver"] == 1) and ("nic_s" in ac.keys()):
            #         ac["Rc"], ac["VPL"] = pms.adsb.nic_v1(msg, ac["nic_s"])
            #     elif (
            #         (ac["ver"] == 2)
            #         and ("nic_a" in ac.keys())
            #         and ("nic_bc" in ac.keys())
            #     ):
            #         ac["Rc"] = pms.adsb.nic_v2(msg, ac["nic_a"], ac["nic_bc"])

            # if tc == 19:
            #     ac["HVE"], ac["VVE"] = pms.adsb.nuc_v(msg)
            #     if ac["ver"] in [1, 2]:
            #         ac["EPU"], ac["VEPU"] = pms.adsb.nac_v(msg)

            # if tc == 29:
            #     ac["PE_RCu"], ac["PE_VPL"], ac["base"] = pms.adsb.sil(
            #         msg, ac["ver"]
            #     )
            #     ac["HFOMr"], ac["VFOMr"] = pms.adsb.nac_p(msg)

            # if tc == 31:
            #     ac["ver"] = pms.adsb.version(msg)
            #     ac["HFOMr"], ac["VFOMr"] = pms.adsb.nac_p(msg)
            #     ac["PE_RCu"], ac["PE_VPL"], ac["sil_base"] = pms.adsb.sil(
            #         msg, ac["ver"]
            #     )

            #     if ac["ver"] == 1:
            #         ac["nic_s"] = pms.adsb.nic_s(msg)
            #     elif ac["ver"] == 2:
            #         ac["nic_a"], ac["nic_bc"] = pms.adsb.nic_a_c(msg)

        elif df == 20 or df == 21:

            bds = pms.bds.infer(msg)
            icao = pms.icao(msg)
            ac = self.acs[icao.lower()]

            if bds == "BDS20":
                ac.bds20 = time, msg
                return

            if bds == "BDS40":
                ac.bds40 = time, msg
                return

            if bds == "BDS44":
                ac.bds44 = time, msg
                return

            if bds == "BDS45":
                ac.bds45 = time, msg
                return

            if bds == "BDS50,BDS60":
                if spd is not None and trk is not None and alt is not None:
                    bds = pms.bds.is50or60(msg, spd, trk, alt)
                elif (ac.spd is not None and ac.trk is not None
                      and ac.alt is not None):
                    bds = pms.bds.is50or60(msg, ac.spd, ac.trk, ac.alt)
                else:
                    return
                # do not return!

            if bds == "BDS50":
                ac.bds50 = time, msg
                return

            if bds == "BDS60":
                ac.bds60 = time, msg
                return
Exemplo n.º 17
0
with open("../mensagens/adsb_all.txt") as f:
    msgs = []

    for line in f.readlines():
        msgs.append(line.replace("*", "").replace(";", "").replace("\n", ""))

print("Total de mensagens captadas: %d" % (len(msgs)))

for msg in msgs:

    # verificação da mensagem
    if int(pms.crc(msg, encode=False)) != 0:
        corrupted.append(msg)
        continue
    elif 17 != pms.df(msg) != 18:
        incorrectDF.append(msg)
        continue

    icao = pms.adsb.icao(msg)  # ICAO aeronava

    # Informações necessárias da aeronave
    if not icao in data:
        data[icao] = {
            'mensagens': 0,
            'identificação': None,
            'posiçãoSurface': [],
            'BARO': [],
            'velocidades': [],
            'GNSS': [],
            'reserved': [],
aircraft_list = {}
icao_list = []
while True:
    try:
        s.connect((TCP_IP, TCP_PORT))
    except:
        pass
    try:
        data = s.recv(BUFFER_SIZE)
    except:
        continue

    data = data[data.find(char1) + 1:data.find(char2)]
    data_length = len(data)
    try:
        dl_format = pms.df(data)
    except:
        break

    #CHECK MESSAGE CORRUPTED
    try:
        MSG = pms.hex2bin(data)
    except:
        pass

    if data_length > 14:
        CRC = pms.crc(MSG, encode=False)

        if int(CRC, 2) == 0:
            #print "Received Data:", data
            #print 'MSG is CORRECT'
Exemplo n.º 19
0
    def process(
        self,
        time: datetime,
        msg: str,
        *args: Any,
        uncertainty: bool = False,
        spd: Optional[float] = None,
        trk: Optional[float] = None,
        alt: Optional[float] = None,
    ) -> None:

        ac: Aircraft

        if len(msg) != 28:
            return

        df = pms.df(msg)

        if df == 4 or df == 20:
            icao = pms.icao(msg)
            if isinstance(icao, bytes):
                icao = icao.decode()
            ac = self.acs[icao.lower()]
            ac.altcode = time, msg  # type: ignore

        if df == 5 or df == 21:
            icao = pms.icao(msg)
            if isinstance(icao, bytes):
                icao = icao.decode()
            ac = self.acs[icao.lower()]
            ac.idcode = time, msg  # type: ignore

        if df == 17 or df == 18:  # ADS-B

            if pms.crc(msg, encode=False) != 0:
                return

            tc = pms.adsb.typecode(msg)
            icao = pms.icao(msg)

            # before it's fixed in pyModeS release...
            if isinstance(icao, bytes):
                icao = icao.decode()

            ac = self.acs[icao.lower()]

            if 1 <= tc <= 4:
                ac.callsign = time, msg  # type: ignore

            if 5 <= tc <= 8:
                ac.surface = time, msg  # type: ignore

            if tc == 19:
                ac.speed = time, msg  # type: ignore

            if 9 <= tc <= 18:
                # This is barometric altitude
                ac.position = time, msg  # type: ignore

            if 20 <= tc <= 22:
                # Only GNSS altitude
                pass

            if not uncertainty:
                return

            if 9 <= tc <= 18:
                ac.nic_bc = pms.adsb.nic_b(msg)

            if (5 <= tc <= 8) or (9 <= tc <= 18) or (20 <= tc <= 22):
                ac.nuc_p = time, msg  # type: ignore
                if ac.version == 1:
                    ac.nic_v1 = time, msg  # type: ignore
                elif ac.version == 2:
                    ac.nic_v2 = time, msg  # type: ignore

            if tc == 19:
                ac.nuc_r = time, msg  # type: ignore
                if ac.version in [1, 2]:
                    ac.nac_v = time, msg  # type: ignore

            if tc == 29:
                ac.sil = time, msg  # type: ignore
                ac.nac_p = time, msg  # type: ignore

            if tc == 31:
                ac.version = pms.adsb.version(msg)
                ac.sil = time, msg  # type: ignore
                ac.nac_p = time, msg  # type: ignore

                if ac.version == 1:
                    ac.nic_s = pms.adsb.nic_s(msg)
                elif ac.version == 2:
                    ac.nic_a, ac.nic_bc = pms.adsb.nic_a_c(msg)

        elif df == 20 or df == 21:

            bds = pms.bds.infer(msg)
            icao = pms.icao(msg)
            if isinstance(icao, bytes):
                icao = icao.decode()
            ac = self.acs[icao.lower()]

            if bds == "BDS20":
                ac.bds20 = time, msg  # type: ignore
                return

            if bds == "BDS40":
                ac.bds40 = time, msg  # type: ignore
                return

            if bds == "BDS44":
                ac.bds44 = time, msg  # type: ignore
                return

            if bds == "BDS45":
                ac.bds45 = time, msg  # type: ignore
                return

            if bds == "BDS50,BDS60":
                if spd is not None and trk is not None and alt is not None:
                    bds = pms.bds.is50or60(msg, spd, trk, alt)
                elif (ac.spd is not None and ac.trk is not None
                      and ac.alt is not None):
                    bds = pms.bds.is50or60(msg, ac.spd, ac.trk, ac.alt)
                else:
                    return
                # do not return!

            if bds == "BDS50":
                ac.bds50 = time, msg  # type: ignore
                return

            if bds == "BDS60":
                ac.bds60 = time, msg  # type: ignore
                return
def entity_type():
    pdu = EntityStatePdu()
                                           
    pdu.exerciseID = 2
    ts = int(time.time())
    pdu.timestamp = ts
    pdu.length = 144
                                            
    pdu.entityID.siteID = 1
    pdu.entityID.applicationID = 1000
    pdu.forceId = 1
    pdu.entityID.entityID = 1
    position_data = { '471F4A' : [] }
    velocity_data = { 1 : [] }
    track = input('PLease enter the ICAO of available aircraft with in the radius of 330Km...')
    while True:
            
        opn = open('/home/pi/pyModeS-master/tests/data/d.csv','rt')
        for i, r in enumerate(csv.reader(opn)):
            if r:                
                m = r[0]
                if r[0] == '' :
                    time.sleep(1000)
                elif len(m) == 30 :
                    hexstr = m[1:29]
                    df = pms.df(hexstr)
                    icao = adsb.icao(hexstr)                    
                    tc = adsb.typecode(hexstr)
                    msg_even = None
                    msg_odd = None
                    lat_ref = 47.6676454
                    lon_ref = 9.3847333

                    if icao == track :
                        f = csv.reader(open('/home/pi/pyModeS-master/tests/data/icao-model.csv',"rt"))
                                            
                        for row in f:
                            if icao == row[0]:
                                                                    
                                x = row
                                model = x[1]
                                           
                                g = csv.reader(open('/home/pi/pyModeS-master/tests/data/model-entity_id.csv',"rt"))
                                for row in g:
                                    if model == row[0]:
                                        entityID = row[1]
                                        entityKind = row[2]                                    
                                        domain = row[3]                                    
                                        country = row[4]                                    
                                        category = row[5]                                    
                                        subcategory = row[6]                                    
                                        specific = row[7]                                    
                                        extra = row[8]
                                                                                                
                                        pdu.entityType.entityKind = int(entityKind)                        
                                        pdu.entityType.domain = int(domain)                                  
                                        pdu.entityType.country = int(country)                                        
                                        pdu.entityType.category = int(category)
                                        pdu.entityType.subcategory = int(subcategory)
                                        pdu.entityType.specific = int(specific)
                                        pdu.entityType.extra = int(extra)

                                        pdu.alternativeEntityType.entityKind = int(entityKind)
                                        pdu.alternativeEntityType.domain = int(domain)
                                        pdu.alternativeEntityType.country = int(country)
                                        pdu.alternativeEntityType.category = int(category)
                                        pdu.alternativeEntityType.subcategory = int(subcategory)
                                        pdu.alternativeEntityType.specific = int(specific)
                                        pdu.alternativeEntityType.extra = int(extra)

                                        print (hexstr,icao)
                                        if df==17 or df==18 :
                                                
                                            if 1 <= tc <= 4:
                                                category = adsb.category(hexstr)                                                                
                                                                                
                                            elif (5<=tc<=8) :
                                                ts = int(time.time())
                                                k = icao
                                                if hexstr in position_data[k]:
                                                    print('that is the last position received........')
                                                elif k in position_data:
                                                    position_data[k].append(hexstr)
                                                    position_data[k].append(ts)
                                                    obj = position_data[k]
                                                    l2 = obj[len(obj)-2]
                                                    l1 = obj[len(obj)-4]
                                                    t2 = obj[len(obj)-1]
                                                    t1 = obj[len(obj)-3]
                                                    eo2 = adsb.oe_flag(l2)
                                                    eo1 = adsb.oe_flag(l1)
                                                    
                                                    if eo2 == 0 and eo1 == 1:                                
                                                        msg_even = l2
                                                        t_even = t2                           
                                                        msg_odd = l1
                                                        t_odd = t1
                                                                                                                
                                                        position = pms.adsb.position(msg_even, msg_odd, t_even, t_odd, lat_ref, lon_ref)
                                                        lat = position[0]
                                                        lon = position[1]
                                                        altitude = pms.adsb.altitude(hexstr)
                                                        alt = altitude*0.305                                        # converting feets to meters
                                                        print('input position',lat,lon,alt)

                                                        gps = GPS()           
                                                        montereyLocation = gps.lla2ecef((lat,lon,alt))
                                                        pdu.entityLocation.x = montereyLocation[0]
                                                        pdu.entityLocation.y = montereyLocation[1]
                                                        pdu.entityLocation.z = montereyLocation[2]
                                                        fid = pdu.entityID.entityID
                                                        p = [pdu.entityLocation.x,pdu.entityLocation.y,pdu.entityLocation.z] # x,y,z are in meters
                                                        print('ecef',p)

                                                        if fid not in velocity_data:
                                                            velocity_data[fid] = [[0.0,0.0,0.0,ts],p]
                                                            p.append(ts)
                                                            
                                                        else:        
                                                            velocity_data[fid].append(p)
                                                            p.append(ts)
                                                            fobject = velocity_data[fid]
                                                            list2 = fobject[len(fobject)-1]
                                                            list1 = fobject[len(fobject)-2]        
                                                            result = []
                                                            if len(list2) == len(list1):
                                                                for i,j in zip(list2,list1):
                                                                    diff = i-j
                                                                    result.append(diff)
                                                                if result[3] != 0:
                                                                    v = (result[0]/result[3],result[1]/result[3],result[2]/result[3])
                                                                    pdu.entityLinearVelocity.x = v[0]
                                                                    pdu.entityLinearVelocity.y = v[1]
                                                                    pdu.entityLinearVelocity.z = v[2]
                                                                    print(pdu.entityLinearVelocity.x,pdu.entityLinearVelocity.y,pdu.entityLinearVelocity.z)
                                                                #print(d)
                                                                #print(fid,result)
                                                            else:
                                                                print("list lengths are not same")
                                                    elif eo2 == 1 and eo1 == 0:
                                                        msg_even = l1
                                                        t_even = t1
                                                        msg_odd = l2
                                                        t_odd = t2

                                                        position = pms.adsb.position(msg_even, msg_odd, t_even, t_odd, lat_ref, lon_ref)
                                                        lat = position[0]
                                                        lon = position[1]
                                                        altitude = pms.adsb.altitude(hexstr)
                                                        alt = altitude*0.305                             # converting feets to meters
                                                        print('input position',lat,lon,alt)
                                                        
                                                        gps = GPS()           
                                                        montereyLocation = gps.lla2ecef((lat,lon,alt))
                                                        pdu.entityLocation.x = montereyLocation[0]
                                                        pdu.entityLocation.y = montereyLocation[1]
                                                        pdu.entityLocation.z = montereyLocation[2]
                                                        fid = pdu.entityID.entityID
                                                        p = [pdu.entityLocation.x,pdu.entityLocation.y,pdu.entityLocation.z] # x,y,z are in meters
                                                        print('ecef',p)
                                                        
                                                        if fid not in velocity_data:
                                                            velocity_data[fid] = [[0.0,0.0,0.0,ts],p]
                                                            p.append(ts)
                                                            
                                                        else:        
                                                            velocity_data[fid].append(p)
                                                            p.append(ts)
                                                            fobject = velocity_data[fid]
                                                            list2 = fobject[len(fobject)-1]
                                                            list1 = fobject[len(fobject)-2]        
                                                            result = []
                                                            if len(list2) == len(list1):
                                                                for i,j in zip(list2,list1):
                                                                    diff = i-j
                                                                    result.append(diff)
                                                                if result[3] != 0:
                                                                    v = (result[0]/result[3],result[1]/result[3],result[2]/result[3])
                                                                    pdu.entityLinearVelocity.x = v[0]
                                                                    pdu.entityLinearVelocity.y = v[1]
                                                                    pdu.entityLinearVelocity.z = v[2]
                                                                    print(pdu.entityLinearVelocity.x,pdu.entityLinearVelocity.y,pdu.entityLinearVelocity.z)
                                                                #print(d)
                                                                #print(fid,result)
                                                            else:
                                                                print("list lengths are not same")
                                                                                                                                    
                                                        otherLocation = (montereyLocation[0], montereyLocation[1], montereyLocation[2] + 1)
                                                        ned = gps.ecef2ned(montereyLocation, otherLocation)                                              
                                                        
                                            elif (9<=tc<=18) :
                                                ts = int(time.time())
                                                k = icao
                                                if hexstr in position_data[k]:
                                                    print('that is the last position received.........')
                                                elif k in position_data:
                                                    position_data[k].append(hexstr)
                                                    position_data[k].append(ts)
                                                    obj = position_data[k]
                                                    l2 = obj[len(obj)-2]
                                                    l1 = obj[len(obj)-4]
                                                    t2 = obj[len(obj)-1]
                                                    t1 = obj[len(obj)-3]
                                                    eo2 = adsb.oe_flag(l2)
                                                    eo1 = adsb.oe_flag(l1)
                                                    
                                                    if eo2 == 0 and eo1 == 1:                                
                                                        msg_even = l2
                                                        t_even = t2                           
                                                        msg_odd = l1
                                                        t_odd = t1
                                                                                                                
                                                        position = pms.adsb.position(msg_even, msg_odd, t_even, t_odd, lat_ref, lon_ref)
                                                        lat = position[0]
                                                        lon = position[1]
                                                        altitude = pms.adsb.altitude(hexstr)
                                                        alt = altitude*0.305                                        # converting feets to meters
                                                        print('input position',lat,lon,alt)

                                                        gps = GPS()           
                                                        montereyLocation = gps.lla2ecef((lat,lon,alt))
                                                        pdu.entityLocation.x = montereyLocation[0]
                                                        pdu.entityLocation.y = montereyLocation[1]
                                                        pdu.entityLocation.z = montereyLocation[2]
                                                        fid = pdu.entityID.entityID
                                                        p = [pdu.entityLocation.x,pdu.entityLocation.y,pdu.entityLocation.z] # x,y,z are in meters
                                                        print(p)

                                                        if fid not in velocity_data:
                                                            velocity_data[fid] = [[0.0,0.0,0.0,ts],p]
                                                            p.append(ts)
                                                            
                                                        else:        
                                                            velocity_data[fid].append(p)
                                                            p.append(ts)
                                                            fobject = velocity_data[fid]
                                                            list2 = fobject[len(fobject)-1]
                                                            list1 = fobject[len(fobject)-2]        
                                                            result = []
                                                            if len(list2) == len(list1):
                                                                for i,j in zip(list2,list1):
                                                                    diff = i-j
                                                                    result.append(diff)
                                                                if result[3] != 0:
                                                                    v = (result[0]/result[3],result[1]/result[3],result[2]/result[3])
                                                                    pdu.entityLinearVelocity.x = v[0]
                                                                    pdu.entityLinearVelocity.y = v[1]
                                                                    pdu.entityLinearVelocity.z = v[2]
                                                                    print(pdu.entityLinearVelocity.x,pdu.entityLinearVelocity.y,pdu.entityLinearVelocity.z)
                                                                #print(d)
                                                                #print(fid,result)
                                                            else:
                                                                print("list lengths are not same")
                                                    elif eo2 == 1 and eo1 == 0:
                                                        msg_even = l1
                                                        t_even = t1
                                                        msg_odd = l2
                                                        t_odd = t2

                                                        position = pms.adsb.position(msg_even, msg_odd, t_even, t_odd, lat_ref, lon_ref)
                                                        lat = position[0]
                                                        lon = position[1]
                                                        altitude = pms.adsb.altitude(hexstr)
                                                        alt = altitude*0.305                        # converting feets to meters
                                                        print('input position',lat,lon,alt)
                                                        
                                                        gps = GPS()           
                                                        montereyLocation = gps.lla2ecef((lat,lon,alt))
                                                        pdu.entityLocation.x = montereyLocation[0]
                                                        pdu.entityLocation.y = montereyLocation[1]
                                                        pdu.entityLocation.z = montereyLocation[2]
                                                        fid = pdu.entityID.entityID
                                                        p = [pdu.entityLocation.x,pdu.entityLocation.y,pdu.entityLocation.z] # x,y,z are in meters
                                                        print('ecef',p)
                                                        
                                                        if fid not in velocity_data:
                                                            velocity_data[fid] = [[0.0,0.0,0.0,ts],p]
                                                            p.append(ts)
                                                            
                                                        else:        
                                                            velocity_data[fid].append(p)
                                                            p.append(ts)
                                                            fobject = velocity_data[fid]
                                                            list2 = fobject[len(fobject)-1]
                                                            list1 = fobject[len(fobject)-2]        
                                                            result = []
                                                            if len(list2) == len(list1):
                                                                for i,j in zip(list2,list1):
                                                                    diff = i-j
                                                                    result.append(diff)
                                                                if result[3] != 0:
                                                                    v = (result[0]/result[3],result[1]/result[3],result[2]/result[3])
                                                                    pdu.entityLinearVelocity.x = v[0]
                                                                    pdu.entityLinearVelocity.y = v[1]
                                                                    pdu.entityLinearVelocity.z = v[2]
                                                                    print(pdu.entityLinearVelocity.x,pdu.entityLinearVelocity.y,pdu.entityLinearVelocity.z)
                                                                #print(d)
                                                                #print(fid,result)
                                                            else:
                                                                print("list lengths are not same")
                                                                                                                                    
                                                        otherLocation = (montereyLocation[0], montereyLocation[1], montereyLocation[2] + 1)
                                                        ned = gps.ecef2ned(montereyLocation, otherLocation)

                                            elif tc==19 :
                                                velocity = pms.adsb.velocity(hexstr)               # Handles both surface & airborne messages
                                                speed_heading = pms.adsb.speed_heading(hexstr)     # Handles both surface & airborne messages
                                                airborne_velocity = pms.adsb.airborne_velocity(hexstr)
                                                                
                                                
                                        elif df==16 or df==20 :
                                            altcode = common.altcode(hexstr)
                                                            
                                                                       
                                        elif df==21 :
                                            idcode = common.idcode(hexstr)
                                               
                                        #print('done')             

                                        pdu.marking.characterSet = 1
                                        marking = [0,0,0,0,0,0,0]
                                        m = [ord(c) for c in model]
                                                    
                                        pdu.marking.characters = m+marking #[101,49,57,48,0,0,0,0,0,0,0]
                                        #print (pdu.marking.characters)
                                        '''
                                        #Orientation
                                        pi = 3.1415926536
                                        
                                        roll = pms.decoder.bds.bds50.roll50(hexstr)
                                        if roll != None:
                                            roll = pms.decoder.bds.bds50.roll50(hexstr)
                                            pdu.entityOrientation.phi= roll * (pi/180)   #in radians
                                            
                                        trk = pms.decoder.bds.bds50.trk50(hexstr)
                                        if trk != None:        
                                            trk = pms.decoder.bds.bds50.trk50(hexstr)
                                            pdu.entityOrientation.theta = trk * (pi/180) #in radians 
                                            
                                        hdg = pms.decoder.bds.bds60.hdg60(hexstr)
                                        if hdg != None:
                                            hdg = pms.decoder.bds.bds60.hdg60(hexstr)                                       
                                            pdu.entityOrientation.psi = hdg * (pi/180)   #in radians    '''                             
                                                                                                                    
                                            
                                        pdu.variableParameters = []
                                        pdu.entityAppearance = 0
                                        
                                        pdu.deadReckoningParameters.deadReckoningAlgorithm = 3
                                        pdu.deadReckoningParameters.parameters =  [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                                        pdu.deadReckoningParameters.entityLinearAcceleration.x = 0
                                        pdu.deadReckoningParameters.entityLinearAcceleration.y = 0
                                        pdu.deadReckoningParameters.entityLinearAcceleration.z = 0
                                        pdu.deadReckoningParameters.entityAngularVelocity.x = 0
                                        pdu.deadReckoningParameters.entityAngularVelocity.y = 0
                                        pdu.deadReckoningParameters.entityAngularVelocity.z = 0
                                            
                                        #capability = pms.decoder.bds.bds17.cap17(hexstr)
                                        pdu.capabilities = 0#capability
                                                                                                            
                                        memoryStream = BytesIO()
                                        outputStream = DataOutputStream(memoryStream)
                                        pdu.serialize(outputStream)
                                        data = memoryStream.getvalue()
                                        pdu.length = len(data)
                                        #print ("data length is ", )
                                                    #print "pdu protocol version is ", pdu.protocolVersion
                                        memoryStream = BytesIO()
                                        outputStream = DataOutputStream(memoryStream)
                                        pdu.serialize(outputStream)
                                        data1 = memoryStream.getvalue()                 
                                        udpSocket.sendto(data1, (DESTINATION_ADDRESS, UDP_PORT))
                                                        
                                        #time.sleep(1)
                                        print ("message sent")
Exemplo n.º 21
0
 def handle_messages(self, messages):
     for msg, ts in messages:
         if all((len(msg) == 28, pms.df(msg) == 17, pms.crc(msg) == 0)):
             icao = pms.adsb.icao(msg)
             tc = pms.adsb.typecode(msg)
             self.process_msg(msg, ts, icao, tc)
Exemplo n.º 22
0
            if len(data_raw) == 18:
                short = data_raw[1:15]
                hexstr = short.decode('utf-8')
                icao = adsb.icao(hexstr)
                if icao != None:
                    print('short message', hexstr, icao)
                    get_entityID(icao)
                    mo = get_model_from_icao(icao)
                    if mo != False:
                        entyp = get_entity_type_from_model(mo)
                        last_position_msg(icao)

            elif len(data_raw) == 32:
                x = data_raw[1:29]
                hexstr = x.decode('utf-8')
                df = pms.df(hexstr)
                icao = adsb.icao(hexstr)
                if icao != None:
                    print('here', hexstr, icao)
                    tc = adsb.typecode(hexstr)
                    #print (hexstr,icao,df,tc)
                    msg_even = None
                    msg_odd = None
                    lat_ref = 47.6676454
                    lon_ref = 9.3847333

                    get_entityID(icao)
                    mo = get_model_from_icao(icao)
                    if mo != False:
                        entyp = get_entity_type_from_model(mo)
                        get_orientation(hexstr)
Exemplo n.º 23
0
  def _parse(self, msg_ascii):
    if not msg_ascii or msg_ascii[0] != '*':
      raise ValueError

    msg_hex = msg_ascii[1:].split(';', 1)[0]

    try:
      icao = adsb.icao(msg_hex).lower()
      downlink_format = df(msg_hex)
      type_code = adsb.typecode(msg_hex)
    except:
      raise ValueError

    # version 0 is assumed, so populate it on initialisation
    ac_data = self.positions.get(icao, {"version": 0})

    if downlink_format == 17 or downlink_format == 18:
      # An aircraft airborne position message has downlink format 17 (or 18) with
      # type code from 9 to 18 (baro altitude) or 20 to 22 (GNSS altitude)
      # ref https://mode-s.org/decode/adsb/airborne-position.html
      if ac_data.get("version", None) == 1 and ac_data.get("nic_s", None):
        ac_data["nic"] = adsb.nic_v1(msg_hex, ac_data["nic_s"])

      if (type_code >= 1 and type_code <= 4):
        # Slightly normalise the callsign - it's supposed to only be [0-9A-Z]
        # with space padding. PyModeS uses _ padding, which I think is an older
        # version of the spec.
        ac_data["callsign"] = adsb.callsign(msg_hex).upper().replace("_", " ")[:8]
        ac_data["emitter_category"] = adsb.category(msg_hex)
      elif (type_code >= 9 and type_code <= 18) or (type_code >= 20 and type_code <= 22):
        nuc_p = None
        if ac_data.get("version", None) == 0:
          # In ADSB version 0, the type code encodes the nuc_p (navigational
          # uncertianty category - position) value via this magic lookup table
          nuc_p_lookup = {
            9: 9,
            10: 8,
            11: 7,
            12: 6,
            13: 5,
            14: 4,
            15: 3,
            16: 2,
            17: 1,
            18: 0,
            20: 9,
            21: 8,
            22: 0,
          }
          ac_data["nuc_p"] = nuc_p_lookup.get(type_code, None)

        elif ac_data.get("version", None) == 2:
          ac_data["nic_b"] = adsb.nic_b(msg_hex)

        if ac_data.get("version", None) == 2 and "nic_a" in ac_data.keys() and "nic_c" in ac_data.keys():
          nic_a = ac_data["nic_a"]
          nic_c = ac_data["nic_c"]
          ac_data["nic"] = adsb.nic_v2(msg_hex, nic_a, nic_c)

        # Aircraft position
        if not self.gps.is_fresh():
          #print("aircraft: not updating {0} df={1} tc={2} as my GPS position is unknown ({3})".format(icao, downlink_format, type_code, msg_hex))
          raise ValueError

        # Use the known location of the receiver to calculate the aircraft position
        # from one messsage
        try:
          my_latitude, my_longitude = self.gps.position()
        except NoFixError:
          # For testing
          my_latitude, my_longitude = (51.519559, -0.114227)
          # a rare race condition
          #raise ValueError

        ac_lat, ac_lon = adsb.position_with_ref(msg_hex, my_latitude, my_longitude)
        #print("aircraft: update {0} df={1} tc={2} {3}, {4} ({5})".format(icao, downlink_format, type_code, ac_lat, ac_lon, msg_hex))

        ac_data["lat"] = ac_lat
        ac_data["lon"] = ac_lon

      elif type_code == 19:
        # From the docs: returns speed (kt) ground track or heading (degree),
        # rate of climb/descent (ft/min), speed type (‘GS’ for ground speed,
        # ‘AS’ for airspeed), direction source (‘true_north’ for ground track /
        # true north as refrence, ‘mag_north’ for magnetic north as reference),
        # rate of climb/descent source (‘Baro’ for barometer, ‘GNSS’ for GNSS
        # constellation).
        if ac_data.get("version", None) == 1 or ac_data.get("version", None) == 2:
          ac_data["nac_v"] = adsb.nac_v(msg_hex)

        try:
          (speed, track, climb, speed_source, track_source, climb_source) = adsb.velocity(msg_hex, rtn_sources=True)
          ac_data["speed_h"] = speed
          ac_data["track"] = track
          ac_data["speed_v"] = climb
          ac_data["speed_h_source"] = speed_source
          ac_data["track_source"] = track_source
          ac_data["speed_v_source"] = climb_source
        except TypeError:
          # adsb.velocity can return None
          raise ValueError

      elif type_code == 31:
        # Operational status
        version = adsb.version(msg_hex)
        nic_s = adsb.nic_s(msg_hex)

        # v0 nuc_p is determined by type_code above
        if version == 1:
          try:
            # Is this the right place for nucp? The docs say yes, but one error
            # I've received says 8d3c5ee6f81300000039283c21cf: Not a surface
            # position message (5<TC<8), airborne position message (8<TC<19),
            # or airborne position with GNSS height (20<TC<22)
            nuc_p = adsb.nuc_p(msg_hex)
            nuc_v = adsb.nuc_v(msg_hex)
          except RuntimeError as e:
            print("aircraft: error parsing v1 NUC: {}".format(e))
            raise ValueError

          ac_data["nic_s"] = nic_s
          ac_data["nuc_p"] = nuc_p
          ac_data["nuc_v"] = nuc_v
          ac_data["nac_p"] = adsb.nac_p(msg_hex)
          ac_data["sil"] = adsb.sil(msg_hex, version)
        elif version == 2:
          ac_data["nac_p"] = adsb.nac_p(msg_hex)
          (nic_a, nic_c) = adsb.nic_a_c(msg_hex)
          ac_data["nic_a"] = nic_a
          ac_data["nic_c"] = nic_c
          ac_data["sil"] = adsb.sil(msg_hex, version)

        ac_data["version"] = version
        ac_data["nic_s"] = nic_s
      else:
        raise ValueError

    elif downlink_format == 4 or downlink_format == 20:
      altitude = adsb_common.altcode(msg_hex)
      ac_data["altitude"] = altitude
    else:
      # unsupported message
      raise ValueError

    ac_data["updated"] = datetime.now()
    self.positions[icao] = ac_data
Exemplo n.º 24
0
    def read_beast_buffer(self):
        """Handle mode-s beast data type.

        <esc> "1" : 6 byte MLAT timestamp, 1 byte signal level,
            2 byte Mode-AC
        <esc> "2" : 6 byte MLAT timestamp, 1 byte signal level,
            7 byte Mode-S short frame
        <esc> "3" : 6 byte MLAT timestamp, 1 byte signal level,
            14 byte Mode-S long frame
        <esc> "4" : 6 byte MLAT timestamp, status data, DIP switch
            configuration settings (not on Mode-S Beast classic)
        <esc><esc>: true 0x1a
        <esc> is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33

        timestamp:
        wiki.modesbeast.com/Radarcape:Firmware_Versions#The_GPS_timestamp
        """
        messages_mlat = []
        msg = []
        i = 0

        # process the buffer until the last divider <esc> 0x1a
        # then, reset the self.buffer with the remainder

        while i < len(self.buffer):
            if self.buffer[i:i + 2] == [0x1A, 0x1A]:
                msg.append(0x1A)
                i += 1
            elif (i == len(self.buffer) - 1) and (self.buffer[i] == 0x1A):
                # special case where the last bit is 0x1a
                msg.append(0x1A)
            elif self.buffer[i] == 0x1A:
                if i == len(self.buffer) - 1:
                    # special case where the last bit is 0x1a
                    msg.append(0x1A)
                elif len(msg) > 0:
                    messages_mlat.append(msg)
                    msg = []
            else:
                msg.append(self.buffer[i])
            i += 1

        # save the reminder for next reading cycle, if not empty
        if len(msg) > 0:
            reminder = []
            for i, m in enumerate(msg):
                if (m == 0x1A) and (i < len(msg) - 1):
                    # rewind 0x1a, except when it is at the last bit
                    reminder.extend([m, m])
                else:
                    reminder.append(m)
            self.buffer = [0x1A] + msg
        else:
            self.buffer = []

        # extract messages
        messages = []
        for mm in messages_mlat:
            ts = time.time()

            msgtype = mm[0]
            # print(''.join('%02X' % i for i in mm))

            if msgtype == 0x32:
                # Mode-S Short Message, 7 byte, 14-len hexstr
                msg = "".join("%02X" % i for i in mm[8:15])
            elif msgtype == 0x33:
                # Mode-S Long Message, 14 byte, 28-len hexstr
                msg = "".join("%02X" % i for i in mm[8:22])
            else:
                # Other message tupe
                continue

            if len(msg) not in [14, 28]:
                continue

            df = pms.df(msg)

            # skip incomplete message
            if df in [0, 4, 5, 11] and len(msg) != 14:
                continue
            if df in [16, 17, 18, 19, 20, 21, 24] and len(msg) != 28:
                continue

            messages.append([msg, ts])
        return messages
Exemplo n.º 25
0
    async def run(self):
        self._logger.info("Running ADSBNetWorker for data_type='%s'",
                          self.data_type)

        self._reset_local_buffer()

        decoder = pyModeS.streamer.decode.Decode()
        net_client = pyModeS.streamer.source.NetSource("x", 1, self.data_type)

        while 1:
            messages = []
            received = await self.net_queue.get()
            if not received:
                continue

            net_client.buffer.extend(received)
            if "beast" in self.data_type:
                messages = net_client.read_beast_buffer()
            elif "raw" in self.data_type:
                messages = net_client.read_raw_buffer()
            elif "skysense" in self.data_type:
                messages = net_client.read_skysense_buffer()

            self._logger.debug("Received %s messages", len(messages))

            if not messages:
                continue
            else:
                for msg, t in messages:
                    if len(msg) != 28:  # wrong data length
                        continue

                    df = pms.df(msg)

                    if df != 17:  # not ADSB
                        continue

                    if pms.crc(msg) != 0:  # CRC fail
                        continue

                    icao = pms.adsb.icao(msg)
                    tc = pms.adsb.typecode(msg)

                    if df == 17 or df == 18:
                        self.local_buffer_adsb_msg.append(msg)
                        self.local_buffer_adsb_ts.append(t)
                    elif df == 20 or df == 21:
                        self.local_buffer_commb_msg.append(msg)
                        self.local_buffer_commb_ts.append(t)
                    else:
                        continue

                if len(self.local_buffer_adsb_msg) > 1:
                    decoder.process_raw(self.local_buffer_adsb_ts,
                                        self.local_buffer_adsb_msg,
                                        self.local_buffer_commb_ts,
                                        self.local_buffer_commb_msg)
                    self._reset_local_buffer()

                acs = decoder.get_aircraft()
                for k, v in acs.items():
                    # self._logger.debug("acs=%s", acs[k])
                    lat = v.get("lat")
                    lon = v.get("lon")
                    flight = v.get("call", k)
                    alt_geom = v.get("alt")
                    gs = v.get("gs")
                    if lat and lon and flight and alt_geom and gs:
                        aircraft = [{
                            "hex": k,
                            "lat": lat,
                            "lon": lon,
                            "flight": flight.replace("_", ""),
                            "alt_geom": alt_geom,
                            "gs": gs
                        }]
                        await self.handle_message(aircraft)
                    else:
                        continue
Exemplo n.º 26
0
    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        outmsg = OrderedDict()
        outmsg['stationid'] = self.station_id

        poscache = dict()

        while not self.stoprequest.isSet():
            # look for gps here to avoid flooding the reporter in the case of no lock
            loc = self.gpsp.get_current()
            if (loc == None) or (loc['lat'] == "0.0"
                                 and loc['lng'] == "0.0") or (loc['lat']
                                                              == "NaN"):
                print("[adsb] No GPS loc, waiting...")
                time.sleep(ERROR_SLEEP)
                continue

            msg = self.cmdpipe.stdout.readline().strip()

            if len(msg) == 0:
                continue

            if not msg.startswith('*') or not msg.endswith(';'):
                continue

            msg = msg[1:-1]
            if len(msg) != 28:
                continue

            crc = pms.util.hex2bin(msg[-6:])
            p = pms.util.crc(msg, encode=True)
            if p != crc:
                continue

            df = pms.df(msg)  # downlink format
            if df == 17:  # ads-b
                tc = pms.adsb.typecode(msg)  # type code
                if 1 <= tc <= 4:  # identification message
                    icao = pms.adsb.icao(msg)
                    callsign = pms.adsb.callsign(msg)

                    if self.settings['print_all']:
                        print("[adsb] (ID) ICAO: {}, Callsign: {}]".format(
                            icao, callsign))

                    outmsg['icao'] = icao
                    outmsg['callsign'] = callsign.strip('_')
                    outmsg['aircraft_lat'] = None
                    outmsg['aircraft_lng'] = None
                    outmsg['altitude'] = None
                    outmsg['heading'] = None
                    outmsg['updownrate'] = None
                    outmsg['speedtype'] = None
                    outmsg['speed'] = None

                elif 9 <= tc <= 18:  # airborne position
                    icao = pms.adsb.icao(msg)
                    altitude = pms.adsb.altitude(msg)

                    if icao in poscache.keys() and poscache[icao]:
                        (recent_tc, recent_msg, recent_time) = poscache[icao]
                        if recent_tc != tc:
                            poscache[icao] = None
                            continue

                        recent_odd = (pms.util.hex2bin(recent_msg)[53] == '1')
                        msg_odd = (pms.util.hex2bin(msg)[53] == '1')

                        if recent_odd != msg_odd:
                            if recent_odd:
                                oddmsg = recent_msg
                                evenmsg = msg
                                t_odd = recent_time
                                t_even = time.time()
                            else:
                                oddmsg = msg
                                evenmsg = recent_msg
                                t_odd = time.time()
                                t_even = recent_time

                            pos = pms.adsb.position(oddmsg, evenmsg, t_odd,
                                                    t_even)
                            if not pos:
                                continue
                            lat, lng = pos

                        else:
                            poscache[icao] = (tc, msg, time.time())
                            continue

                    else:
                        poscache[icao] = (tc, msg, time.time())
                        continue

                    if self.settings['print_all']:
                        print(
                            "[adsb] (POS) ICAO: {}, Lat: {}, Lng: {}, Alt: {}".
                            format(icao, lat, lng, altitude))

                    outmsg['icao'] = icao
                    outmsg['callsign'] = None
                    outmsg['aircraft_lat'] = lat
                    outmsg['aircraft_lng'] = lng
                    outmsg['altitude'] = altitude
                    outmsg['heading'] = None
                    outmsg['updownrate'] = None
                    outmsg['speedtype'] = None
                    outmsg['speed'] = None

                elif tc == 19:  # airborne velocities
                    icao = pms.adsb.icao(msg)
                    velocity = pms.adsb.velocity(msg)
                    speed, heading, updownrate, speedtype = velocity

                    if self.settings['print_all']:
                        print(
                            "[adsb] (VEL) ICAO: {}, Heading: {}, ClimbRate: {}, Speedtype: {}, Speed: {}"
                            .format(icao, heading, updownrate, speedtype,
                                    speed))

                    outmsg['icao'] = icao
                    outmsg['callsign'] = None
                    outmsg['aircraft_lat'] = None
                    outmsg['aircraft_lng'] = None
                    outmsg['altitude'] = None
                    outmsg['heading'] = heading
                    outmsg['updownrate'] = updownrate
                    outmsg['speedtype'] = speedtype
                    outmsg['speed'] = speed

                else:
                    continue

                outmsg['lat'] = float(loc['lat'])
                outmsg['lng'] = float(loc['lng'])
                outmsg['module'] = 'ad'

                outmsg['time'] = str(int(time.time()))
                m = md5()
                m.update(self.station_pass + outmsg['icao'] + outmsg['time'])
                outmsg['sign'] = m.hexdigest()[:12]

                try:
                    sock.sendto(json.dumps(outmsg),
                                (self.server_host, self.server_port))
                except Exception:
                    print("[adsb] Could not send to server, waiting...")
                    time.sleep(ERROR_SLEEP)
                    continue

        sock.close()
        self.cmdpipe.stdout.close()
        self.cmdpipe.kill()
        os.kill(self.cmdpipe.pid, 9)
        os.wait()

        return
Exemplo n.º 27
0
    def run(self):
        data = {}
        data['module'] = MODULE_ADSB
        data['protocol'] = PROTOCOL_VERSION

        poscache = {}

        while not self.stoprequest.isSet():
            msg = self.cmdpipe.stdout.readline().strip()
            if len(msg) == 0:
                continue

            msg = msg.decode('utf-8')
            if not msg.startswith('*') or not msg.endswith(';'):
                continue

            msg = msg[1:-1]
            if len(msg) != 28:
                continue

            crc = pms.util.hex2bin(msg[-6:])
            p = pms.util.crc(msg, encode=True)
            if p != crc:
                continue

            df = pms.df(msg)  # downlink format
            if df == 17:  # ads-b
                tc = pms.adsb.typecode(msg)  # type code
                if 1 <= tc <= 4:  # identification message
                    icao = pms.adsb.icao(msg)
                    callsign = pms.adsb.callsign(msg)

                    if self.settings['print_all']:
                        gammarf_util.console_message(
                            "(ID) ICAO: {}, Callsign: {}".format(
                                icao, callsign), MOD_NAME)

                    data['icao'] = icao
                    data['callsign'] = callsign.strip('_')
                    data['aircraft_lat'] = None
                    data['aircraft_lng'] = None
                    data['altitude'] = None
                    data['heading'] = None
                    data['updownrate'] = None
                    data['speedtype'] = None
                    data['speed'] = None

                elif 9 <= tc <= 18:  # airborne position
                    icao = pms.adsb.icao(msg)
                    altitude = pms.adsb.altitude(msg)

                    if icao in poscache and poscache[icao]:
                        (recent_tc, recent_msg, recent_time) = poscache[icao]
                        if recent_tc != tc:
                            poscache[icao] = None
                            continue

                        recent_odd = (pms.util.hex2bin(recent_msg)[53] == '1')
                        msg_odd = (pms.util.hex2bin(msg)[53] == '1')

                        if recent_odd != msg_odd:
                            if recent_odd:
                                oddmsg = recent_msg
                                evenmsg = msg
                                t_odd = recent_time
                                t_even = time.time()
                            else:
                                oddmsg = msg
                                evenmsg = recent_msg
                                t_odd = time.time()
                                t_even = recent_time

                            pos = pms.adsb.position(oddmsg, evenmsg, t_odd,
                                                    t_even)
                            if not pos:
                                continue
                            lat, lng = pos

                        else:
                            poscache[icao] = (tc, msg, time.time())
                            continue

                    else:
                        poscache[icao] = (tc, msg, time.time())
                        continue

                    if self.settings['print_all']:
                        gammarf_util.console_message(
                            "(POS) ICAO: {}, Lat: {}, Lng: {}, Alt: {}".format(
                                icao, lat, lng, altitude), MOD_NAME)

                    data['icao'] = icao
                    data['callsign'] = None
                    data['aircraft_lat'] = lat
                    data['aircraft_lng'] = lng
                    data['altitude'] = altitude
                    data['heading'] = None
                    data['updownrate'] = None
                    data['speedtype'] = None
                    data['speed'] = None

                elif tc == 19:  # airborne velocities
                    icao = pms.adsb.icao(msg)
                    velocity = pms.adsb.velocity(msg)
                    speed, heading, updownrate, speedtype = velocity

                    if self.settings['print_all']:
                        gammarf_util.console_message(
                                "[adsb] (VEL) ICAO: {}, Heading: {}, "\
                                "ClimbRate: {}, Speedtype: {}, Speed: {}"
                                .format(icao, heading, updownrate,
                                    speedtype, speed),
                                MOD_NAME)

                    data['icao'] = icao
                    data['callsign'] = None
                    data['aircraft_lat'] = None
                    data['aircraft_lng'] = None
                    data['altitude'] = None
                    data['heading'] = heading
                    data['updownrate'] = updownrate
                    data['speedtype'] = speedtype
                    data['speed'] = speed

                else:
                    continue

                self.connector.senddat(data)

        try:
            self.cmdpipe.stdout.close()
            self.cmdpipe.kill()
            os.kill(self.cmdpipe.pid, 9)
            os.wait()
        except:
            pass

        return