watch a mavlink packet pattern
978628
def cmd_watch(args):
    ''''''
    if len(args) == 0:
        mpstate.status.watch = None
        return
    mpstate.status.watch = args
    print("Watching %s" % mpstate.status.watch)
603781
def show_link(self):
        ''''''
        for master in self.mpstate.mav_master:
            linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3
            if master.linkerror:
                print("link %u down" % (master.linknum+1))
            else:
                print("link %u OK (%u packets, %.2fs delay, %u lost, %.1f%% loss)" % (master.linknum+1,
                                                                                      self.status.counters['MasterIn'][master.linknum],
                                                                                      linkdelay,
                                                                                      master.mav_loss,
                                                                                      master.packet_loss()))
835908
def mavlink_packet(self, msg):
        ''''''
        msgType = msg.get_type()
        master = self.master       
        if msgType == 'HEARTBEAT':
            # Update state and mode information
            if type(master.motors_armed()) == type(True):
                self.armed = master.motors_armed()
                self.mode = master.flightmode
                # Send Flight State information down pipe
                self.msgList.append(FlightState(self.mode,self.armed))
        elif msgType == 'ATTITUDE':
            # Send attitude information down pipe
            self.msgList.append(Attitude(msg))
        elif msgType == 'VFR_HUD':
            # Send HUD information down pipe
            self.msgList.append(VFR_HUD(msg))
        elif msgType == 'GLOBAL_POSITION_INT':
            # Send altitude information down pipe
            self.msgList.append(Global_Position_INT(msg,time.time()))
        elif msgType == 'SYS_STATUS':
            # Mode and Arm State
            self.msgList.append(BatteryInfo(msg))
        elif msgType in ['WAYPOINT_CURRENT', 'MISSION_CURRENT']:
            # Waypoints
            self.currentWP = msg.seq
            self.finalWP = self.module('wp').wploader.count()
            self.msgList.append(WaypointInfo(self.currentWP,self.finalWP,self.currentDist,self.nextWPTime,self.wpBearing))
        elif msgType == 'NAV_CONTROLLER_OUTPUT':
            self.currentDist = msg.wp_dist
            self.speed = master.field('VFR_HUD', 'airspeed', 30)
            if self.speed > 1:
                self.nextWPTime = self.currentDist / self.speed
            else:
                self.nextWPTime = '-'
            self.wpBearing = msg.target_bearing
            self.msgList.append(WaypointInfo(self.currentWP,self.finalWP,self.currentDist,self.nextWPTime,self.wpBearing))
581774
def _recv(self):
                ''''''
                from . import mavutil
                start_time = time.time()
                while time.time() < start_time + self.timeout:
                        m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
                                                type='SERIAL_CONTROL', blocking=False, timeout=0)
                        if m is not None and m.count != 0:
                                break
                        self.mav.mav.serial_control_send(self.port,
                                                         mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |
                                                         mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,
                                                         0,
                                                         0,
                                                         0, [0]*70)
                        m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
                                                type='SERIAL_CONTROL', blocking=True, timeout=0.01)
                        if m is not None and m.count != 0:
                                break
                if m is not None:
                        if self._debug > 2:
                                print(m)
                        data = m.data[:m.count]
                        self.buf += ''.join(str(chr(x)) for x in data)
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)
937694
def mavflightview_mav(mlog, options=None, title=None):
    ''''''
    if not title:
        title='MAVFlightView'
    wp = mavwp.MAVWPLoader()
    if options.mission is not None:
        wp.load(options.mission)
    fen = mavwp.MAVFenceLoader()
    if options.fence is not None:
        fen.load(options.fence)
    path = [[]]
    instances = {}
    ekf_counter = 0
    types = ['MISSION_ITEM','CMD']
    if options.types is not None:
        types.extend(options.types.split(','))
    else:
        types.extend(['GPS','GLOBAL_POSITION_INT'])
        if options.rawgps or options.dualgps:
            types.extend(['GPS', 'GPS_RAW_INT'])
        if options.rawgps2 or options.dualgps:
            types.extend(['GPS2_RAW','GPS2'])
        if options.ekf:
            types.extend(['EKF1', 'GPS'])
        if options.ahr2:
            types.extend(['AHR2', 'AHRS2', 'GPS'])
    print("Looking for types %s" % str(types))

    last_timestamps = {}

    while True:
        try:
            m = mlog.recv_match(type=types)
            if m is None:
                break
        except Exception:
            break

        type = m.get_type()
        
        if type == 'MISSION_ITEM':
            try:
                while m.seq > wp.count():
                    print("Adding dummy WP %u" % wp.count())
                    wp.set(m, wp.count())
                wp.set(m, m.seq)
            except Exception:
                pass
            continue
        if type == 'CMD':
            m = mavutil.mavlink.MAVLink_mission_item_message(0,
                                                             0,
                                                             m.CNum,
                                                             mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
                                                             m.CId,
                                                             0, 1,
                                                             m.Prm1, m.Prm2, m.Prm3, m.Prm4,
                                                             m.Lat, m.Lng, m.Alt)
            try:
                while m.seq > wp.count():
                    print("Adding dummy WP %u" % wp.count())
                    wp.set(m, wp.count())
                wp.set(m, m.seq)
            except Exception:
                pass
            continue
        if not mlog.check_condition(options.condition):
            continue
        if options.mode is not None and mlog.flightmode.lower() != options.mode.lower():
            continue
        if type in ['GPS','GPS2']:
            status = getattr(m, 'Status', None)
            if status is None:
                status = getattr(m, 'FixType', None)
                if status is None:
                    print("Can't find status on GPS message")
                    print(m)
                    break
            if status < 2:
                continue
            # flash log
            lat = m.Lat
            lng = getattr(m, 'Lng', None)
            if lng is None:
                lng = getattr(m, 'Lon', None)
                if lng is None:
                    print("Can't find longitude on GPS message")
                    print(m)
                    break                    
        elif type in ['EKF1', 'ANU1']:
            pos = mavextra.ekf1_pos(m)
            if pos is None:
                continue
            ekf_counter += 1
            if ekf_counter % options.ekf_sample != 0:
                continue
            (lat, lng) = pos            
        elif type in ['ANU5']:
            (lat, lng) = (m.Alat*1.0e-7, m.Alng*1.0e-7)
        elif type in ['AHR2', 'POS', 'CHEK']:
            (lat, lng) = (m.Lat, m.Lng)
        elif type == 'AHRS2':
            (lat, lng) = (m.lat*1.0e-7, m.lng*1.0e-7)
        else:
            lat = m.lat * 1.0e-7
            lng = m.lon * 1.0e-7

        # automatically add new types to instances
        if type not in instances:
            instances[type] = len(instances)
            while len(instances) >= len(path):
                path.append([])
        instance = instances[type]

        if abs(lat)>0.01 or abs(lng)>0.01:
            fmode = getattr(mlog, 'flightmode','')
            if fmode in colourmap:
                colour = colourmap[fmode]
            else:
                colour = colourmap['UNKNOWN']
            (r,g,b) = colour
            (r,g,b) = (r+instance*80,g+instance*50,b+instance*70)
            if r > 255:
                r = 205
            if g > 255:
                g = 205
            if g < 0:
                g = 0
            if b > 255:
                b = 205
            colour = (r,g,b)
            point = (lat, lng, colour)

            if options.rate == 0 or not type in last_timestamps or m._timestamp - last_timestamps[type] > 1.0/options.rate:
                last_timestamps[type] = m._timestamp
                path[instance].append(point)
    if len(path[0]) == 0:
        print("No points to plot")
        return
    bounds = mp_util.polygon_bounds(path[0])
    (lat, lon) = (bounds[0]+bounds[2], bounds[1])
    (lat, lon) = mp_util.gps_newpos(lat, lon, -45, 50)
    ground_width = mp_util.gps_distance(lat, lon, lat-bounds[2], lon+bounds[3])
    while (mp_util.gps_distance(lat, lon, bounds[0], bounds[1]) >= ground_width-20 or
           mp_util.gps_distance(lat, lon, lat, bounds[1]+bounds[3]) >= ground_width-20):
        ground_width += 10

    path_objs = []
    for i in range(len(path)):
        if len(path[i]) != 0:
            path_objs.append(mp_slipmap.SlipPolygon('FlightPath[%u]-%s' % (i,title), path[i], layer='FlightPath',
                                                    linewidth=2, colour=(255,0,180)))
    plist = wp.polygon_list()
    mission_obj = None
    if len(plist) > 0:
        mission_obj = []
        for i in range(len(plist)):
            mission_obj.append(mp_slipmap.SlipPolygon('Mission-%s-%u' % (title,i), plist[i], layer='Mission',
                                                      linewidth=2, colour=(255,255,255)))
    else:
        mission_obj = None

    fence = fen.polygon()
    if len(fence) > 1:
        fence_obj = mp_slipmap.SlipPolygon('Fence-%s' % title, fen.polygon(), layer='Fence',
                                           linewidth=2, colour=(0,255,0))
    else:
        fence_obj = None

    if options.imagefile:
        create_imagefile(options, options.imagefile, (lat,lon), ground_width, path_objs, mission_obj, fence_obj)
    else:
        global multi_map
        if options.multi and multi_map is not None:
            map = multi_map
        else:
            map = mp_slipmap.MPSlipMap(title=title,
                                       service=options.service,
                                       elevation=True,
                                       width=600,
                                       height=600,
                                       ground_width=ground_width,
                                       lat=lat, lon=lon,
                                       debug=options.debug)
        if options.multi:
            multi_map = map
        for path_obj in path_objs:
            map.add_object(path_obj)
        if mission_obj is not None:
            display_waypoints(wp, map)
        if fence_obj is not None:
            map.add_object(fence_obj)

        for flag in options.flag:
            a = flag.split(',')
            lat = a[0]
            lon = a[1]
            icon = 'flag.png'
            if len(a) > 2:
                icon = a[2] + '.png'
            icon = map.icon(icon)
            map.add_object(mp_slipmap.SlipIcon('icon - %s' % str(flag), (float(lat),float(lon)), icon, layer=3, rotation=0, follow=False))
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
582751
def socket_monitor_loop(self):
        '''  '''
        try:
            while True:
                gevent.socket.wait_read(self.socket.fileno())

                self._handle_log_rotations()
                self.capture_packet()
        finally:
            self.clean_up()
1177182
def watch(ctx):
    
    vcs = ctx.obj['vcs']

    event_handler = TestsEventHandler(vcs)

    observer = Observer()
    observer.schedule(event_handler, vcs.path, recursive=True)
    observer.start()
    click.echo('Watching directory `{path}`. Use ctrl-c to stop.'.format(path=vcs.path))
    while observer.isAlive():
        observer.join(timeout=1)
814764
def mav_to_gpx(infilename, outfilename):
    ''''''

    mlog = mavutil.mavlink_connection(infilename)
    outf = open(outfilename, mode='w')

    def process_packet(timestamp, lat, lon, alt, hdg, v):
        t = time.localtime(timestamp)
        outf.write('''<trkpt lat="%s" lon="%s">
  <ele>%s</ele>
  <time>%s</time>
  <course>%s</course>
  <speed>%s</speed>
  <fix>3d</fix>
</trkpt>
''' % (lat, lon, alt,
       time.strftime("%Y-%m-%dT%H:%M:%SZ", t),
       hdg, v))

    def add_header():
        outf.write('''<?xml version="1.0" encoding="UTF-8"?>
<gpx
  version="1.0"
  creator="pymavlink"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.topografix.com/GPX/1/0"
  xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">
<trk>
<trkseg>
''')

    def add_footer():
        outf.write('''</trkseg>
</trk>
</gpx>
''')

    add_header()

    count=0
    lat=0
    lon=0
    fix=0
    while True:
        m = mlog.recv_match(type=['GPS_RAW', 'GPS_RAW_INT', 'GPS', 'GPS2'], condition=args.condition)
        if m is None:
            break
        if m.get_type() == 'GPS_RAW_INT':
            lat = m.lat/1.0e7
            lon = m.lon/1.0e7
            alt = m.alt/1.0e3
            v = m.vel/100.0
            hdg = m.cog/100.0
            timestamp = m._timestamp
            fix = m.fix_type
        elif m.get_type() == 'GPS_RAW':
            lat = m.lat
            lon = m.lon
            alt = m.alt
            v = m.v
            hdg = m.hdg
            timestamp = m._timestamp
            fix = m.fix_type
        elif m.get_type() == 'GPS' or m.get_type() == 'GPS2':
            lat = m.Lat
            lon = m.Lng
            alt = m.Alt
            v = m.Spd
            hdg = m.GCrs
            timestamp = m._timestamp
            fix = m.Status
        else:
	    pass

        if fix < 2 and not args.nofixcheck:
            continue
        if lat == 0.0 or lon == 0.0:
            continue
        process_packet(timestamp, lat, lon, alt, hdg, v)
        count += 1
    add_footer()
    print("Created %s with %u points" % (outfilename, count))
283384
def tcp_traceflow(packet, *, count=NotImplemented):
    """"""
    if 'TCP' in packet:
        ip = packet['IP'] if 'IP' in packet else packet['IPv6']
        tcp = packet['TCP']
        data = dict(
            protocol=LINKTYPE.get(packet.name.upper()),     # data link type from global header
            index=count,                                    # frame number
            frame=packet2dict(packet),                      # extracted packet
            syn=bool(tcp.flags.S),                          # TCP synchronise (SYN) flag
            fin=bool(tcp.flags.F),                          # TCP finish (FIN) flag
            src=ipaddress.ip_address(ip.src),               # source IP
            dst=ipaddress.ip_address(ip.dst),               # destination IP
            srcport=tcp.sport,                              # TCP source port
            dstport=tcp.dport,                              # TCP destination port
            timestamp=time.time(),                          # timestamp
        )
        return True, data
    return False, None
108676
def handle_mavlink_packet(self, master, m):
        ''''''
        if m.get_type() == 'PARAM_VALUE':
            value = self.handle_px4_param_value(m)
            param_id = "%.16s" % m.param_id
            # Note: the xml specifies param_index is a uint16, so -1 in that field will show as 65535
            # We accept both -1 and 65535 as 'unknown index' to future proof us against someday having that
            # xml fixed.
            if self.fetch_set is not None:
                self.fetch_set.discard(m.param_index)
            if m.param_index != -1 and m.param_index != 65535 and m.param_index not in self.mav_param_set:
                added_new_parameter = True
                self.mav_param_set.add(m.param_index)
            else:
                added_new_parameter = False
            if m.param_count != -1:
                self.mav_param_count = m.param_count
            self.mav_param[str(param_id)] = value
            if param_id in self.fetch_one and self.fetch_one[param_id] > 0:
                self.fetch_one[param_id] -= 1
                if isinstance(value, float):
                    print("%s = %.7f" % (param_id, value))
                else:
                    print("%s = %s" % (param_id, str(value)))
            if added_new_parameter and len(self.mav_param_set) == m.param_count:
                print("Received %u parameters" % m.param_count)
                if self.logdir is not None:
                    self.mav_param.save(os.path.join(self.logdir, self.parm_file), '*', verbose=True)
                self.fetch_set = None
            if self.fetch_set is not None and len(self.fetch_set) == 0:
                self.fetch_check(master, force=True)
        elif m.get_type() == 'HEARTBEAT':
            if m.get_srcComponent() == 1:
                # remember autopilot types so we can handle PX4 parameters
                self.autopilot_type_by_sysid[m.get_srcSystem()] = m.autopilot
953169
def mavlink_packet(self, m):
        ''''''
        if m.get_type() in ['GLOBAL_POSITION_INT', 'SCALED_PRESSURE']:
            connection = self.find_connection()
            if not connection:
                return
            if m.get_srcSystem() != connection.target_system:
                connection.mav.send(m)
1074975
def watch(self):
        """"""
        return bool(lib.EnvGetDefmessageHandlerWatch(
            self._env, self._cls, self._idx))
1025754
def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4=None, filter=None, timeout=2, verbose=None, **kargs):  # noqa: E501
    
    if verbose is None:
        verbose = conf.verb
    if filter is None:
        # we only consider ICMP error packets and TCP packets with at
        # least the ACK flag set *and* either the SYN or the RST flag
        # set
        filter = "(icmp and (icmp[0]=3 or icmp[0]=4 or icmp[0]=5 or icmp[0]=11 or icmp[0]=12)) or (tcp and (tcp[13] & 0x16 > 0x10))"  # noqa: E501
    if l4 is None:
        a, b = sr(IP(dst=target, id=RandShort(), ttl=(minttl, maxttl)) / TCP(seq=RandInt(), sport=sport, dport=dport),  # noqa: E501
                  timeout=timeout, filter=filter, verbose=verbose, **kargs)
    else:
        # this should always work
        filter = "ip"
        a, b = sr(IP(dst=target, id=RandShort(), ttl=(minttl, maxttl)) / l4,
                  timeout=timeout, filter=filter, verbose=verbose, **kargs)

    a = TracerouteResult(a.res)
    if verbose:
        a.show()
    return a, b
1286864
function watch(sourcePath, patterns, commands) {
  var isBusy = false;
  var isPending = false;
  var runnable = function() {
    if (isBusy) return (isPending = true);
    isBusy = true;
    run(commands, function(err) {
      if (err) console.error(err.stack || err);
      isBusy = false;
      if (isPending) runnable(isPending = false);
    });
  };
  chokidar.watch(patterns, {
    cwd: sourcePath,
    ignoreInitial: true
  }).on('add', runnable).on('change', runnable).on('unlink', runnable);
}
797416
def idle_task(self):
        ''''''
        if not self.started:
            return
        now = time.time()
        if now - self.last_packet < 1:
            timeout = 0.05
        else:
            timeout = 0.2
        if now - self.last_check > timeout:
            self.last_check = now
            mav = self.master.mav
            flags = mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND
            flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_MULTI
            flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
            mav.serial_control_send(self.serial_settings.port,
                                    flags,
                                    0, self.serial_settings.baudrate,
                                    0, [0]*70)