process packets from the MAVLink master
978093
def process_master(m):
    ''''''
    try:
        s = m.recv(16*1024)
    except Exception:
        time.sleep(0.1)
        return
    # prevent a dead serial port from causing the CPU to spin. The user hitting enter will
    # cause it to try and reconnect
    if len(s) == 0:
        time.sleep(0.1)
        return

    if (mpstate.settings.compdebug & 1) != 0:
        return

    if mpstate.logqueue_raw:
        mpstate.logqueue_raw.put(str(s))

    if mpstate.status.setup_mode:
        if mpstate.system == 'Windows':
           # strip nsh ansi codes
           s = s.replace("\033[K","")
        sys.stdout.write(str(s))
        sys.stdout.flush()
        return

    if m.first_byte and opts.auto_protocol:
        m.auto_mavlink_version(s)
    msgs = m.mav.parse_buffer(s)
    if msgs:
        for msg in msgs:
            sysid = msg.get_srcSystem()
            if sysid in mpstate.sysid_outputs:
                  # the message has been handled by a specialised handler for this system
                  continue
            if getattr(m, '_timestamp', None) is None:
                m.post_message(msg)
            if msg.get_type() == "BAD_DATA":
                if opts.show_errors:
                    mpstate.console.writeln("MAV error: %s" % msg)
                mpstate.status.mav_error += 1
37313
def process(filename):
    ''''''
    print("Processing %s" % filename)
    mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps,
                                      robust_parsing=args.robust)


    ext = os.path.splitext(filename)[1]
    isbin = ext in ['.bin', '.BIN']
    islog = ext in ['.log', '.LOG']
    output = None
    count = 1
    dirname = os.path.dirname(filename)

    if isbin or islog:
        extension = "bin"
    else:
        extension = "tlog"

    file_header = ''

    messages = []

    # we allow a list of modes that map to one mode number. This allows for --mode=AUTO,RTL and consider the RTL as part of AUTO
    modes = args.mode.upper().split(',')
    flightmode = None

    while True:
        m = mlog.recv_match()
        if m is None:
            break
        if args.link is not None and m._link != args.link:
            continue

        mtype = m.get_type()
        if mtype in messages:
            if older_message(m, messages[mtype]):
                continue

        # we don't use mlog.flightmode as that can be wrong if we are extracting a single link
        if mtype == 'HEARTBEAT' and m.get_srcComponent() != mavutil.mavlink.MAV_COMP_ID_GIMBAL and m.type != mavutil.mavlink.MAV_TYPE_GCS:
            flightmode = mavutil.mode_string_v10(m).upper()
        if mtype == 'MODE':
            flightmode = mlog.flightmode

        if (isbin or islog) and m.get_type() in ["FMT", "PARM", "CMD"]:
            file_header += m.get_msgbuf()
        if (isbin or islog) and m.get_type() == 'MSG' and m.Message.startswith("Ardu"):
            file_header += m.get_msgbuf()
        if m.get_type() in ['PARAM_VALUE','MISSION_ITEM']:
            timestamp = getattr(m, '_timestamp', None)
            file_header += struct.pack('>Q', timestamp*1.0e6) + m.get_msgbuf()

        if not mavutil.evaluate_condition(args.condition, mlog.messages):
            continue

        if flightmode in modes:
            if output is None:
                path = os.path.join(dirname, "%s%u.%s" % (modes[0], count, extension))
                count += 1
                print("Creating %s" % path)
                output = open(path, mode='wb')
                output.write(file_header)
        else:
            if output is not None:
                output.close()
                output = None

        if output and m.get_type() != 'BAD_DATA':
            timestamp = getattr(m, '_timestamp', None)
            if not isbin:
                output.write(struct.pack('>Q', timestamp*1.0e6))
            output.write(m.get_msgbuf())
468181
def _process(self, envelope, session, mode, **kwargs):
		
		if mode == WMessengerOnionPackerLayerProto.Mode.pack:
			return self.pack(envelope, session, **kwargs)
		else:  # mode == WMessengerOnionPackerLayerProto.Mode.unpack
			return self.unpack(envelope, session, **kwargs)
441132
def mavlink_packet(self, m):
        ''''''
        mtype = m.get_type()
        if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']:
            if self.wp_op is None:
                self.console.error("No waypoint load started")
            else:
                self.wploader.clear()
                self.wploader.expected_count = m.count
                self.console.writeln("Requesting %u waypoints t=%s now=%s" % (m.count,
                                                                                 time.asctime(time.localtime(m._timestamp)),
                                                                                 time.asctime()))
                self.master.waypoint_request_send(0)

        elif mtype in ['WAYPOINT', 'MISSION_ITEM'] and self.wp_op != None:
            if m.seq > self.wploader.count():
                self.console.writeln("Unexpected waypoint number %u - expected %u" % (m.seq, self.wploader.count()))
            elif m.seq < self.wploader.count():
                # a duplicate
                pass
            else:
                self.wploader.add(m)
            if m.seq+1 < self.wploader.expected_count:
                self.master.waypoint_request_send(m.seq+1)
            else:
                if self.wp_op == 'list':
                    for i in range(self.wploader.count()):
                        w = self.wploader.wp(i)
                        print("%u %u %.10f %.10f %f p1=%.1f p2=%.1f p3=%.1f p4=%.1f cur=%u auto=%u" % (
                            w.command, w.frame, w.x, w.y, w.z,
                            w.param1, w.param2, w.param3, w.param4,
                            w.current, w.autocontinue))
                    if self.logdir != None:
                        waytxt = os.path.join(self.logdir, 'way.txt')
                        self.save_waypoints(waytxt)
                        print("Saved waypoints to %s" % waytxt)
                elif self.wp_op == "save":
                    self.save_waypoints(self.wp_save_filename)
                self.wp_op = None

        elif mtype in ["WAYPOINT_REQUEST", "MISSION_REQUEST"]:
            self.process_waypoint_request(m, self.master)

        elif mtype in ["WAYPOINT_CURRENT", "MISSION_CURRENT"]:
            if m.seq != self.last_waypoint:
                self.last_waypoint = m.seq
                if self.settings.wpupdates:
                    self.say("waypoint %u" % m.seq,priority='message')
240771
def mavlink_packet(self, msg):
        ''''''
        type = msg.get_type()
        master = self.master
        # add some status fields
        if type == 'TERRAIN_REQUEST':
            self.current_request = msg
            self.sent_mask = 0
            self.requests_received += 1
        elif type == 'TERRAIN_REPORT':
            if (msg.lat == self.check_lat and
                msg.lon == self.check_lon and
                (self.check_lat != 0 or self.check_lon != 0)):
                print(msg)
                self.check_lat = 0
                self.check_lon = 0
1169964
def _process_actions(self, actions, inport, packet):
        '''
        
        '''
        second_stage = []
        for a in actions:
            fn = a(packet=packet, net=self._switchyard_net, controllers=self._controller_connections, inport=inport)
            if (fn):
                second_stage.append(fn)
        for fn in second_stage:
            fn()
1330922
def mavlink_packet(self, m):
        """"""
        mtype = m.get_type()
        if mtype == 'GPS_RAW':
            (self.lat, self.lon) = (m.lat, m.lon)
        elif mtype == 'GPS_RAW_INT':
            (self.lat, self.lon) = (m.lat / 1.0e7, m.lon / 1.0e7)
        elif mtype == "VFR_HUD":
            self.heading = m.heading
            self.alt = m.alt
            self.airspeed = m.airspeed
            self.groundspeed = m.groundspeed
1278962
def master(self):
        ''''''
        if len(self.mav_master) == 0:
              return None
        if self.settings.link > len(self.mav_master):
            self.settings.link = 1
        # try to use one with no link error
        if not self.mav_master[self.settings.link-1].linkerror:
            return self.mav_master[self.settings.link-1]
        for m in self.mav_master:
            if not m.linkerror:
                return m
        return self.mav_master[self.settings.link-1]
284471
def handle(self, pkt, raddress, rport):
        """"""
        log.debug("In TftpStateServerStart.handle")
        if isinstance(pkt, TftpPacketRRQ):
            log.debug("Handling an RRQ packet")
            return TftpStateServerRecvRRQ(self.context).handle(pkt,
                                                               raddress,
                                                               rport)
        elif isinstance(pkt, TftpPacketWRQ):
            log.debug("Handling a WRQ packet")
            return TftpStateServerRecvWRQ(self.context).handle(pkt,
                                                               raddress,
                                                               rport)
        else:
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Invalid packet to begin up/download: %s" % pkt)
1129891
def mavlink_packet(self, msg):
        ''''''
        type = msg.get_type()

        master = self.master

        # add some status fields
        if type in [ 'RC_CHANNELS_RAW' ]:
            rc6 = msg.chan6_raw
            if rc6 > 1500:
                ign_colour = 'green'
            else:
                ign_colour = 'red'
            self.console.set_status('IGN', 'IGN', fg=ign_colour, row=4)

        if type in [ 'SERVO_OUTPUT_RAW' ]:
            rc8 = msg.servo8_raw
            if rc8 < 1200:
                thr_colour = 'red'
            elif rc8 < 1300:
                thr_colour = 'orange'
            else:
                thr_colour = 'green'
            self.console.set_status('THR', 'THR', fg=thr_colour, row=4)

        if type in [ 'RPM' ]:
            rpm = msg.rpm1
            if rpm < 3000:
                rpm_colour = 'red'
            elif rpm < 10000:
                rpm_colour = 'orange'
            else:
                rpm_colour = 'green'
            self.console.set_status('RPM', 'RPM: %u' % rpm, fg=rpm_colour, row=4)
595800
def handle_packet(self, packet):
        """"""

        if not isinstance(packet, RTMPPacket):
            raise ValueError("A RTMPPacket argument is required")

        return librtmp.RTMP_ClientPacket(self.rtmp, packet.packet)
1123607
def master_send_callback(self, m, master):
        ''''''
        if self.status.watch is not None:
            for msg_type in self.status.watch:
                if fnmatch.fnmatch(m.get_type().upper(), msg_type.upper()):
                    self.mpstate.console.writeln('> '+ str(m))
                    break

        mtype = m.get_type()
        if mtype != 'BAD_DATA' and self.mpstate.logqueue:
            usec = self.get_usec()
            usec = (usec & ~3) | 3 # linknum 3
            self.mpstate.logqueue.put(bytearray(struct.pack('>Q', usec) + m.get_msgbuf()))
1333411
def mavlink_packet(self, m):
        ''''''
        #do nothing if not caibrating
        if (self.calibrating == False):
            return

        if m.get_type() == 'RC_CHANNELS_RAW':
            for i in range(1,self.num_channels+1):
                v = getattr(m, 'chan%u_raw' % i)

                if self.get_cal_min(i) > v:
                    self.set_cal_min(i,v)
                    self.console.writeln("Calibrating: RC%u_MIN=%u" % (i, v))
                if self.get_cal_max(i) < v:
                    self.set_cal_max(i,v)
                    self.console.writeln("Calibrating: RC%u_MAX=%u" % (i, v))
952387
def mavlink_packet(self, m):
        ''''''
        if m.get_type() == "ADSB_VEHICLE":
            id = 'ADSB-' + str(m.ICAO_address)
            if id not in self.threat_vehicles.keys():  # check to see if the vehicle is in the dict
                # if not then add it
                self.threat_vehicles[id] = ADSBVehicle(id=id, state=m.to_dict())
                for mp in self.module_matching('map*'):
                    from MAVProxy.modules.lib import mp_menu
                    from MAVProxy.modules.mavproxy_map import mp_slipmap
                    self.threat_vehicles[id].menu_item = mp_menu.MPMenuItem(name=id, returnkey=None)
                    if m.emitter_type >= 100 and m.emitter_type-100 in obc_icons:
                        icon = mp.map.icon(obc_icons[m.emitter_type-100])
                        threat_radius = get_threat_radius(m.emitter_type-100)
                    else:
                        icon = mp.map.icon(self.threat_vehicles[id].icon)
                        threat_radius = 0
                    popup = mp_menu.MPMenuSubMenu('ADSB', items=[self.threat_vehicles[id].menu_item])
                    # draw the vehicle on the map
                    mp.map.add_object(mp_slipmap.SlipIcon(id, (m.lat * 1e-7, m.lon * 1e-7),
                                                                    icon, layer=3, rotation=m.heading*0.01, follow=False,
                                                                    trail=mp_slipmap.SlipTrail(colour=(0, 255, 255)),
                                                                    popup_menu=popup))
                    if threat_radius > 0:
                        mp.map.add_object(mp_slipmap.SlipCircle(id+":circle", 3,
                                                    (m.lat * 1e-7, m.lon * 1e-7),
                                                    threat_radius, (0, 255, 255), linewidth=1))
            else:  # the vehicle is in the dict
                # update the dict entry
                self.threat_vehicles[id].update(m.to_dict(), self.get_time())
                for mp in self.module_matching('map*'):
                    # update the map
                    ground_alt = mp.ElevationMap.GetElevation(m.lat*1e-7, m.lon*1e-7)
                    alt_amsl = m.altitude * 0.001
                    if alt_amsl > 0:
                        alt = int(alt_amsl - ground_alt)
                        label = str(alt) + "m"
                    else:
                        label = None
                    mp.map.set_position(id, (m.lat * 1e-7, m.lon * 1e-7), rotation=m.heading*0.01, label=label, colour=(0,250,250))
                    mp.map.set_position(id+":circle", (m.lat * 1e-7, m.lon * 1e-7))
1050994
def mavlink_packet(self, m):
        ''''''
        if self.gcs_location is None and self.module('wp').wploader.count() > 0:
            home = self.module('wp').get_home()
            self.gcs_location = (home.x, home.y)
            print("Antenna home set")
        if self.gcs_location is None:
            return
        if m.get_type() == 'GPS_RAW' and self.gcs_location is not None:
            (gcs_lat, gcs_lon) = self.gcs_location
            bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
        elif m.get_type() == 'GPS_RAW_INT' and self.gcs_location is not None:
            (gcs_lat, gcs_lon) = self.gcs_location
            bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat / 1.0e7, m.lon / 1.0e7)
        else:
            return
        self.console.set_status('Antenna', 'Antenna %.0f' % bearing, row=0)
        if abs(bearing - self.last_bearing) > 5 and (time.time() - self.last_announce) > 15:
            self.last_bearing = bearing
            self.last_announce = time.time()
            self.say("Antenna %u" % int(bearing + 0.5))
978444
def start_capture(self, port_number, output_file, data_link_type="DLT_EN10MB"):
        

        if port_number not in self._mappings:
            raise DynamipsError("Port {} is not allocated".format(port_number))

        nio = self._mappings[port_number]

        data_link_type = data_link_type.lower()
        if data_link_type.startswith("dlt_"):
            data_link_type = data_link_type[4:]

        if nio.input_filter[0] is not None and nio.output_filter[0] is not None:
            raise DynamipsError("Port {} has already a filter applied".format(port_number))

        yield from nio.bind_filter("both", "capture")
        yield from nio.setup_filter("both", '{} "{}"'.format(data_link_type, output_file))

        log.info('Ethernet hub "{name}" [{id}]: starting packet capture on port {port}'.format(name=self._name,
                                                                                               id=self._id,
                                                                                               port=port_number))
143129
def mavlink_packet(self, m):
        ''''''
        if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3:
            gen_settings.home_lat = m.lat * 1.0e-7
            gen_settings.home_lon = m.lon * 1.0e-7
            self.have_home = True
            if self.pending_start:
                self.start()
        if m.get_type() != 'ATTITUDE':
            return
        t = self.get_time()
        dt = t - self.last_t
        if dt < 0 or dt > 10:
            self.last_t = t
            return
        if dt > 10 or dt < 0.9:
            return
        self.last_t = t
        for a in self.aircraft:
            if not gen_settings.stop:
                a.update(1.0)
                self.pkt_queue.append(a.pickled())
                while len(self.pkt_queue) > len(self.aircraft)*2:
                    self.pkt_queue.pop(0)
                    
        if self.module('map') is not None and not self.menu_added_map:
            self.menu_added_map = True
            self.module('map').add_menu(self.menu)