INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
arm commands
def cmd_arm(self, args): '''arm commands''' usage = "usage: arm <check|uncheck|list|throttle|safetyon|safetyoff>" if len(args) <= 0: print(usage) return if args[0] == "check": if (len(args) < 2): print("usage: arm check " + self.checkables()) return arming_mask = int(self.get_mav_param("ARMING_CHECK",0)) name = args[1].lower() if name == 'all': for name in arming_masks.keys(): arming_mask |= arming_masks[name] elif name in arming_masks: arming_mask |= arming_masks[name] else: print("unrecognized arm check:", name) return self.param_set("ARMING_CHECK", arming_mask) return if args[0] == "uncheck": if (len(args) < 2): print("usage: arm uncheck " + self.checkables()) return arming_mask = int(self.get_mav_param("ARMING_CHECK",0)) name = args[1].lower() if name == 'all': arming_mask = 0 elif name in arming_masks: arming_mask &= ~arming_masks[name] else: print("unrecognized arm check:", args[1]) return self.param_set("ARMING_CHECK", arming_mask) return if args[0] == "list": arming_mask = int(self.get_mav_param("ARMING_CHECK",0)) if arming_mask == 0: print("NONE") for name in arming_masks.keys(): if arming_masks[name] & arming_mask: print(name) return if args[0] == "throttle": p2 = 0 if len(args) == 2 and args[1] == 'force': p2 = 2989 self.master.mav.command_long_send( self.target_system, # target_system self.target_component, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confirmation 1, # param1 (1 to indicate arm) p2, # param2 (all other params meaningless) 0, # param3 0, # param4 0, # param5 0, # param6 0) # param7 return if args[0] == "safetyon": self.master.mav.set_mode_send(self.target_system, mavutil.mavlink.MAV_MODE_FLAG_DECODE_POSITION_SAFETY, 1) return if args[0] == "safetyoff": self.master.mav.set_mode_send(self.target_system, mavutil.mavlink.MAV_MODE_FLAG_DECODE_POSITION_SAFETY, 0) return print(usage)
returns true if the UAV is skipping any arming checks
def all_checks_enabled(self): ''' returns true if the UAV is skipping any arming checks''' arming_mask = int(self.get_mav_param("ARMING_CHECK",0)) if arming_mask == 1: return True for bit in arming_masks.values(): if not arming_mask & bit and bit != 1: return False return True
special handling for the px4 style of PARAM_VALUE
def handle_px4_param_value(self, m): '''special handling for the px4 style of PARAM_VALUE''' if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_REAL32: # already right type return m.param_value is_px4_params = False if m.get_srcComponent() in [mavutil.mavlink.MAV_COMP_ID_UDP_BRIDGE]: # ESP8266 uses PX4 style parameters is_px4_params = True sysid = m.get_srcSystem() if self.autopilot_type_by_sysid.get(sysid,-1) in [mavutil.mavlink.MAV_AUTOPILOT_PX4]: is_px4_params = True if not is_px4_params: return m.param_value # try to extract px4 param value value = m.param_value try: v = struct.pack(">f", value) except Exception: return value if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT8: value, = struct.unpack(">B", v[3:]) elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT8: value, = struct.unpack(">b", v[3:]) elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT16: value, = struct.unpack(">H", v[2:]) elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT16: value, = struct.unpack(">h", v[2:]) elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT32: value, = struct.unpack(">I", v[0:]) elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT32: value, = struct.unpack(">i", v[0:]) # can't pack other types # remember type for param set self.param_types[m.param_id.upper()] = m.param_type return value
handle an incoming mavlink packet
def handle_mavlink_packet(self, master, m): '''handle an incoming mavlink packet''' 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
download XML files for parameters
def param_help_download(self): '''download XML files for parameters''' files = [] for vehicle in ['APMrover2', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']: url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle path = mp_util.dot_mavproxy("%s.xml" % vehicle) files.append((url, path)) url = 'http://autotest.ardupilot.org/%s-defaults.parm' % vehicle if vehicle != 'AntennaTracker': # defaults not generated for AntennaTracker ATM path = mp_util.dot_mavproxy("%s-defaults.parm" % vehicle) files.append((url, path)) try: child = multiproc.Process(target=mp_util.download_files, args=(files,)) child.start() except Exception as e: print(e)
return a "help tree", a map between a parameter and its metadata. May return None if help is not available
def param_help_tree(self): '''return a "help tree", a map between a parameter and its metadata. May return None if help is not available''' if self.xml_filepath is not None: print("param: using xml_filepath=%s" % self.xml_filepath) path = self.xml_filepath else: if self.vehicle_name is None: print("Unknown vehicle type") return None path = mp_util.dot_mavproxy("%s.xml" % self.vehicle_name) if not os.path.exists(path): print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name) return None if not os.path.exists(path): print("Param XML (%s) does not exist" % path) return None xml = open(path,'rb').read() from lxml import objectify objectify.enable_recursive_str() tree = objectify.fromstring(xml) htree = {} for p in tree.vehicles.parameters.param: n = p.get('name').split(':')[1] htree[n] = p for lib in tree.libraries.parameters: for p in lib.param: n = p.get('name') htree[n] = p return htree
search parameter help for a keyword, list those parameters
def param_apropos(self, args): '''search parameter help for a keyword, list those parameters''' if len(args) == 0: print("Usage: param apropos keyword") return htree = self.param_help_tree() if htree is None: return contains = {} for keyword in args: for param in htree.keys(): if str(htree[param]).find(keyword) != -1: contains[param] = True for param in contains.keys(): print("%s" % (param,))
show help on a parameter
def param_help(self, args): '''show help on a parameter''' if len(args) == 0: print("Usage: param help PARAMETER_NAME") return htree = self.param_help_tree() if htree is None: return for h in args: h = h.upper() if h in htree: help = htree[h] print("%s: %s\n" % (h, help.get('humanName'))) print(help.get('documentation')) try: print("\n") for f in help.field: print("%s : %s" % (f.get('name'), str(f))) except Exception as e: pass try: # The entry "values" has been blatted by a cython # function at this point, so we instead get the # "values" by offset rather than name. children = help.getchildren() vchild = children[0] values = vchild.getchildren() if len(values): print("\nValues: ") for v in values: print("\t%s : %s" % (v.get('code'), str(v))) except Exception as e: print("Caught exception %s" % repr(e)) pass else: print("Parameter '%s' not found in documentation" % h)
handle parameter commands
def handle_command(self, master, mpstate, args): '''handle parameter commands''' param_wildcard = "*" usage="Usage: param <fetch|save|set|show|load|preload|forceload|diff|download|help>" if len(args) < 1: print(usage) return if args[0] == "fetch": if len(args) == 1: master.param_fetch_all() self.mav_param_set = set() print("Requested parameter list") else: found = False pname = args[1].upper() for p in self.mav_param.keys(): if fnmatch.fnmatch(p, pname): master.param_fetch_one(p) if p not in self.fetch_one: self.fetch_one[p] = 0 self.fetch_one[p] += 1 found = True print("Requested parameter %s" % p) if not found and args[1].find('*') == -1: master.param_fetch_one(pname) if pname not in self.fetch_one: self.fetch_one[pname] = 0 self.fetch_one[pname] += 1 print("Requested parameter %s" % pname) elif args[0] == "save": if len(args) < 2: print("usage: param save <filename> [wildcard]") return if len(args) > 2: param_wildcard = args[2] else: param_wildcard = "*" self.mav_param.save(args[1], param_wildcard, verbose=True) elif args[0] == "diff": wildcard = '*' if len(args) < 2 or args[1].find('*') != -1: if self.vehicle_name is None: print("Unknown vehicle type") return filename = mp_util.dot_mavproxy("%s-defaults.parm" % self.vehicle_name) if not os.path.exists(filename): print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name) return if len(args) >= 2: wildcard = args[1] else: filename = args[1] if len(args) == 3: wildcard = args[2] print("%-16.16s %12.12s %12.12s" % ('Parameter', 'Defaults', 'Current')) self.mav_param.diff(filename, wildcard=wildcard) elif args[0] == "set": if len(args) < 2: print("Usage: param set PARMNAME VALUE") return if len(args) == 2: self.mav_param.show(args[1]) return param = args[1] value = args[2] if value.startswith('0x'): value = int(value, base=16) if not param.upper() in self.mav_param: print("Unable to find parameter '%s'" % param) return uname = param.upper() ptype = None if uname in self.param_types: ptype = self.param_types[uname] self.mav_param.mavset(master, uname, value, retries=3, parm_type=ptype) if (param.upper() == "WP_LOITER_RAD" or param.upper() == "LAND_BREAK_PATH"): #need to redraw rally points mpstate.module('rally').rallyloader.last_change = time.time() #need to redraw loiter points mpstate.module('wp').wploader.last_change = time.time() elif args[0] == "load": if len(args) < 2: print("Usage: param load <filename> [wildcard]") return if len(args) > 2: param_wildcard = args[2] else: param_wildcard = "*" self.mav_param.load(args[1], param_wildcard, master) elif args[0] == "preload": if len(args) < 2: print("Usage: param preload <filename>") return self.mav_param.load(args[1]) elif args[0] == "forceload": if len(args) < 2: print("Usage: param forceload <filename> [wildcard]") return if len(args) > 2: param_wildcard = args[2] else: param_wildcard = "*" self.mav_param.load(args[1], param_wildcard, master, check=False) elif args[0] == "download": self.param_help_download() elif args[0] == "apropos": self.param_apropos(args[1:]) elif args[0] == "help": self.param_help(args[1:]) elif args[0] == "set_xml_filepath": self.param_set_xml_filepath(args[1:]) elif args[0] == "show": if len(args) > 1: pattern = args[1] else: pattern = "*" self.mav_param.show(pattern) elif args[0] == "status": print("Have %u/%u params" % (len(self.mav_param_set), self.mav_param_count)) else: print(usage)
get list of component IDs with parameters for a given system ID
def get_component_id_list(self, system_id): '''get list of component IDs with parameters for a given system ID''' ret = [] for (s,c) in self.mpstate.mav_param_by_sysid.keys(): if s == system_id: ret.append(c) return ret
handle a new target_system
def add_new_target_system(self, sysid): '''handle a new target_system''' if sysid in self.pstate: return if not sysid in self.mpstate.mav_param_by_sysid: self.mpstate.mav_param_by_sysid[sysid] = mavparm.MAVParmDict() self.new_sysid_timestamp = time.time() fname = 'mav.parm' if sysid not in [(0,0),(1,1),(1,0)]: fname = 'mav_%u_%u.parm' % (sysid[0], sysid[1]) self.pstate[sysid] = ParamState(self.mpstate.mav_param_by_sysid[sysid], self.logdir, self.vehicle_name, fname) if self.continue_mode and self.logdir is not None: parmfile = os.path.join(self.logdir, fname) if os.path.exists(parmfile): mpstate.mav_param.load(parmfile) self.pstate[sysid].mav_param_set = set(self.mav_param.keys()) self.pstate[sysid].xml_filepath = self.xml_filepath
get sysid tuple to use for parameters
def get_sysid(self): '''get sysid tuple to use for parameters''' component = self.target_component if component == 0: component = 1 return (self.target_system, component)
handle a new target_system
def check_new_target_system(self): '''handle a new target_system''' sysid = self.get_sysid() if sysid in self.pstate: return self.add_new_target_system(sysid)
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' sysid = (m.get_srcSystem(),m.get_srcComponent()) self.add_new_target_system(sysid) self.pstate[sysid].handle_mavlink_packet(self.master, m)
handle missing parameters
def idle_task(self): '''handle missing parameters''' self.check_new_target_system() sysid = self.get_sysid() self.pstate[sysid].vehicle_name = self.vehicle_name self.pstate[sysid].fetch_check(self.master)
control parameters
def cmd_param(self, args): '''control parameters''' self.check_new_target_system() sysid = self.get_sysid() self.pstate[sysid].handle_command(self.master, self.mpstate, args)
Returns the tuple ( options, args ) options - a dictionary of option names and values args - a sequence of args
def getOptionsAndArgs( self ): '''Returns the tuple ( options, args ) options - a dictionary of option names and values args - a sequence of args''' option_values = self._getOptions() args = self._getArgs() return option_values, args
multiprocessing wrapper around _parse_args
def parse_args( self, args = None, values = None ): ''' multiprocessing wrapper around _parse_args ''' q = multiproc.Queue() p = multiproc.Process(target=self._parse_args, args=(q, args, values)) p.start() ret = q.get() p.join() return ret
This is the heart of it all - overrides optparse.OptionParser.parse_args @param arg is irrelevant and thus ignored, it is here only for interface compatibility
def _parse_args( self, q, args, values): ''' This is the heart of it all - overrides optparse.OptionParser.parse_args @param arg is irrelevant and thus ignored, it is here only for interface compatibility ''' if wx.GetApp() is None: self.app = wx.App( False ) # preprocess command line arguments and set to defaults option_values, args = self.SUPER.parse_args(self, args, values) for option in self.option_list: if option.dest and hasattr(option_values, option.dest): default = getattr(option_values, option.dest) if default is not None: option.default = default dlg = OptparseDialog( option_parser = self, title=self.get_description() ) if args: dlg.args_ctrl.Value = ' '.join(args) dlg_result = dlg.ShowModal() if wx.ID_OK != dlg_result: raise UserCancelledError( 'User has canceled' ) if values is None: values = self.get_default_values() option_values, args = dlg.getOptionsAndArgs() for option, value in option_values.iteritems(): if ( 'store_true' == option.action ) and ( value is False ): setattr( values, option.dest, False ) continue if ( 'store_false' == option.action ) and ( value is True ): setattr( values, option.dest, False ) continue if option.takes_value() is False: value = None option.process( option, value, values, self ) q.put((values, args))
get distance from a point
def distance_from(self, lat, lon): '''get distance from a point''' lat1 = self.pkt['I105']['Lat']['val'] lon1 = self.pkt['I105']['Lon']['val'] return mp_util.gps_distance(lat1, lon1, lat, lon)
random initial position
def randpos(self): '''random initial position''' self.setpos(gen_settings.home_lat, gen_settings.home_lon) self.move(random.uniform(0, 360), random.uniform(0, gen_settings.region_width))
return height above ground in feet
def ground_height(self): '''return height above ground in feet''' lat = self.pkt['I105']['Lat']['val'] lon = self.pkt['I105']['Lon']['val'] global ElevationMap ret = ElevationMap.GetElevation(lat, lon) ret -= gen_settings.wgs84_to_AMSL return ret * 3.2807
move position by bearing and distance
def move(self, bearing, distance): '''move position by bearing and distance''' lat = self.pkt['I105']['Lat']['val'] lon = self.pkt['I105']['Lon']['val'] (lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance) self.setpos(lat, lon)
fly a square circuit
def update(self, deltat=1.0): '''fly a square circuit''' DNFZ.update(self, deltat) self.dist_flown += self.speed * deltat if self.dist_flown > self.circuit_width: self.desired_heading = self.heading + 90 self.dist_flown = 0 if self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 2000: self.randpos() self.randalt()
fly circles, then dive
def update(self, deltat=1.0): '''fly circles, then dive''' DNFZ.update(self, deltat) self.time_circling += deltat self.setheading(self.heading + self.turn_rate * deltat) self.move(self.drift_heading, self.drift_speed) if self.getalt() > self.max_alt or self.getalt() < self.ground_height(): if self.getalt() > self.ground_height(): self.setclimbrate(self.dive_rate) else: self.setclimbrate(self.climb_rate) if self.getalt() < self.ground_height(): self.setalt(self.ground_height()) if self.distance_from_home() > gen_settings.region_width: self.randpos() self.randalt()
fly in long curves
def update(self, deltat=1.0): '''fly in long curves''' DNFZ.update(self, deltat) if (self.distance_from_home() > gen_settings.region_width or self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 1000): self.randpos() self.randalt()
straight lines, with short life
def update(self, deltat=1.0): '''straight lines, with short life''' DNFZ.update(self, deltat) self.lifetime -= deltat if self.lifetime <= 0: self.randpos() self.lifetime = random.uniform(300,600)
drop an object on the map
def cmd_dropobject(self, obj): '''drop an object on the map''' latlon = self.module('map').click_position if self.last_click is not None and self.last_click == latlon: return self.last_click = latlon if latlon is not None: obj.setpos(latlon[0], latlon[1]) self.aircraft.append(obj)
genobstacles command parser
def cmd_genobstacles(self, args): '''genobstacles command parser''' usage = "usage: genobstacles <start|stop|restart|clearall|status|set>" if len(args) == 0: print(usage) return if args[0] == "set": gen_settings.command(args[1:]) elif args[0] == "start": if self.have_home: self.start() else: self.pending_start = True elif args[0] == "stop": self.stop() self.pending_start = False elif args[0] == "restart": self.stop() self.start() elif args[0] == "status": print(self.status()) elif args[0] == "remove": latlon = self.module('map').click_position if self.last_click is not None and self.last_click == latlon: return self.last_click = latlon if latlon is not None: closest = None closest_distance = 1000 for a in self.aircraft: dist = a.distance_from(latlon[0], latlon[1]) if dist < closest_distance: closest_distance = dist closest = a if closest is not None: self.aircraft.remove(closest) else: print("No obstacle found at click point") elif args[0] == "dropcloud": self.cmd_dropobject(Weather()) elif args[0] == "dropeagle": self.cmd_dropobject(BirdOfPrey()) elif args[0] == "dropbird": self.cmd_dropobject(BirdMigrating()) elif args[0] == "dropplane": self.cmd_dropobject(Aircraft()) elif args[0] == "clearall": self.clearall() else: print(usage)
start sending packets
def start(self): '''start sending packets''' if self.sock is not None: self.sock.close() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.connect(('', gen_settings.port)) global track_count self.aircraft = [] track_count = 0 self.last_t = 0 # some fixed wing aircraft for i in range(gen_settings.num_aircraft): self.aircraft.append(Aircraft(random.uniform(10, 100), 2000.0)) # some birds of prey for i in range(gen_settings.num_bird_prey): self.aircraft.append(BirdOfPrey()) # some migrating birds for i in range(gen_settings.num_bird_migratory): self.aircraft.append(BirdMigrating()) # some weather systems for i in range(gen_settings.num_weather): self.aircraft.append(Weather()) print("Started on port %u" % gen_settings.port)
trigger sends from ATTITUDE packets
def mavlink_packet(self, m): '''trigger sends from ATTITUDE packets''' 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)
update the threat state
def update(self, state, tnow): '''update the threat state''' self.state = state self.update_time = tnow
adsb command parser
def cmd_ADSB(self, args): '''adsb command parser''' usage = "usage: adsb <set>" if len(args) == 0: print(usage) return if args[0] == "status": print("total threat count: %u active threat count: %u" % (len(self.threat_vehicles), len(self.active_threat_ids))) for id in self.threat_vehicles.keys(): print("id: %s distance: %.2f m callsign: %s alt: %.2f" % (id, self.threat_vehicles[id].distance, self.threat_vehicles[id].state['callsign'], self.threat_vehicles[id].state['altitude'])) elif args[0] == "set": self.ADSB_settings.command(args[1:]) else: print(usage)
determine threats
def perform_threat_detection(self): '''determine threats''' # TODO: perform more advanced threat detection threat_radius_clear = self.ADSB_settings.threat_radius * \ self.ADSB_settings.threat_radius_clear_multiplier for id in self.threat_vehicles.keys(): if self.threat_vehicles[id].distance is not None: if self.threat_vehicles[id].distance <= self.ADSB_settings.threat_radius and not self.threat_vehicles[id].is_evading_threat: # if the threat is in the threat radius and not currently # known to the module... # set flag to action threat self.threat_vehicles[id].is_evading_threat = True if self.threat_vehicles[id].distance > threat_radius_clear and self.threat_vehicles[id].is_evading_threat: # if the threat is known to the module and outside the # threat clear radius... # clear flag to action threat self.threat_vehicles[id].is_evading_threat = False self.active_threat_ids = [id for id in self.threat_vehicles.keys( ) if self.threat_vehicles[id].is_evading_threat]
update the distance between threats and vehicle
def update_threat_distances(self, latlonalt): '''update the distance between threats and vehicle''' for id in self.threat_vehicles.keys(): threat_latlonalt = (self.threat_vehicles[id].state['lat'] * 1e-7, self.threat_vehicles[id].state['lon'] * 1e-7, self.threat_vehicles[id].state['altitude']) self.threat_vehicles[id].h_distance = self.get_h_distance(latlonalt, threat_latlonalt) self.threat_vehicles[id].v_distance = self.get_v_distance(latlonalt, threat_latlonalt) # calculate and set the total distance between threat and vehicle self.threat_vehicles[id].distance = sqrt( self.threat_vehicles[id].h_distance**2 + (self.threat_vehicles[id].v_distance)**2)
get the horizontal distance between threat and vehicle
def get_h_distance(self, latlonalt1, latlonalt2): '''get the horizontal distance between threat and vehicle''' (lat1, lon1, alt1) = latlonalt1 (lat2, lon2, alt2) = latlonalt2 lat1 = radians(lat1) lon1 = radians(lon1) lat2 = radians(lat2) lon2 = radians(lon2) dLat = lat2 - lat1 dLon = lon2 - lon1 # math as per mavextra.distance_two() a = sin(0.5 * dLat)**2 + sin(0.5 * dLon)**2 * cos(lat1) * cos(lat2) c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a)) return 6371 * 1000 * c
get the horizontal distance between threat and vehicle
def get_v_distance(self, latlonalt1, latlonalt2): '''get the horizontal distance between threat and vehicle''' (lat1, lon1, alt1) = latlonalt1 (lat2, lon2, alt2) = latlonalt2 return alt2 - alt1
check and handle threat time out
def check_threat_timeout(self): '''check and handle threat time out''' for id in self.threat_vehicles.keys(): if self.threat_vehicles[id].update_time == 0: self.threat_vehicles[id].update_time = self.get_time() dt = self.get_time() - self.threat_vehicles[id].update_time if dt > self.ADSB_settings.timeout: # if the threat has timed out... del self.threat_vehicles[id] # remove the threat from the dict for mp in self.module_matching('map*'): # remove the threat from the map mp.map.remove_object(id) mp.map.remove_object(id+":circle") # we've modified the dict we're iterating over, so # we'll get any more timed-out threats next time we're # called: return
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' 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))
called on idle
def idle_task(self): '''called on idle''' if self.threat_timeout_timer.trigger(): self.check_threat_timeout() if self.threat_detection_timer.trigger(): self.perform_threat_detection()
handle an incoming mavlink packet
def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' if not isinstance(self.checklist, mp_checklist.CheckUI): return if not self.checklist.is_alive(): return type = msg.get_type() master = self.master if type == 'HEARTBEAT': '''beforeEngineList - APM booted''' if self.mpstate.status.heartbeat_error == True: self.checklist.set_check("Pixhawk Booted", 0) else: self.checklist.set_check("Pixhawk Booted", 1) '''beforeEngineList - Flight mode MANUAL''' if self.mpstate.status.flightmode == "MANUAL": self.checklist.set_check("Flight mode MANUAL", 1) else: self.checklist.set_check("Flight mode MANUAL", 0) if type in [ 'GPS_RAW', 'GPS_RAW_INT' ]: '''beforeEngineList - GPS lock''' if ((msg.fix_type >= 3 and master.mavlink10()) or (msg.fix_type == 2 and not master.mavlink10())): self.checklist.set_check("GPS lock", 1) else: self.checklist.set_check("GPS lock", 0) '''beforeEngineList - Radio Links > 6db margin TODO: figure out how to read db levels''' if type in ['RADIO', 'RADIO_STATUS']: if msg.rssi < msg.noise+6 or msg.remrssi < msg.remnoise+6: self.checklist.set_check("Radio links > 6db margin", 0) else: self.checklist.set_check("Radio Links > 6db margin", 0) if type == 'HWSTATUS': '''beforeEngineList - Avionics Battery''' if msg.Vcc >= 4600 and msg.Vcc <= 5300: self.checklist.set_check("Avionics Power", 1) else: self.checklist.set_check("Avionics Power", 0) if type == 'POWER_STATUS': '''beforeEngineList - Servo Power''' if msg.Vservo >= 4900 and msg.Vservo <= 6500: self.checklist.set_check("Servo Power", 1) else: self.checklist.set_check("Servo Power", 0) '''beforeEngineList - Waypoints Loaded''' if type == 'HEARTBEAT': if self.module('wp').wploader.count() == 0: self.checklist.set_check("Waypoints Loaded", 0) else: self.checklist.set_check("Waypoints Loaded", 1) '''beforeTakeoffList - Compass active''' if type == 'GPS_RAW': if math.fabs(msg.hdg - master.field('VFR_HUD', 'heading', '-')) < 10 or math.fabs(msg.hdg - master.field('VFR_HUD', 'heading', '-')) > 355: self.checklist.set_check("Compass active", 1) else: self.checklist.set_check("Compass active", 0) '''beforeCruiseList - Airspeed > 10 m/s , Altitude > 30 m''' if type == 'VFR_HUD': rel_alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 1.0e-3 if rel_alt > 30: self.checklist.set_check("Altitude > 30 m", 1) else: self.checklist.set_check("Altitude > 30 m", 0) if msg.airspeed > 10 or msg.groundspeed > 10: self.checklist.set_check("Airspeed > 10 m/s", 1) else: self.checklist.set_check("Airspeed > 10 m/s", 0) '''beforeEngineList - IMU''' if type in ['SYS_STATUS']: sensors = { 'AS' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE, 'MAG' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_MAG, 'INS' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_ACCEL | mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_GYRO, 'AHRS' : mavutil.mavlink.MAV_SYS_STATUS_AHRS} bits = sensors['INS'] present = ((msg.onboard_control_sensors_enabled & bits) == bits) healthy = ((msg.onboard_control_sensors_health & bits) == bits) if not present or not healthy: self.checklist.set_check("IMU Check", 1) else: self.checklist.set_check("IMU Check", 0)
gopro commands
def cmd_gopro(self, args): '''gopro commands''' usage = "status, shutter <start|stop>, mode <video|camera>, power <on|off>" mav = self.master.mav if args[0] == "status": self.cmd_gopro_status(args[1:]) return if args[0] == "shutter": name = args[1].lower() if name == 'start': mav.gopro_set_request_send(0, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_SHUTTER, 1) return elif name == 'stop': mav.gopro_set_request_send(0, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_SHUTTER, 0) return else: print("unrecognized") return if args[0] == "mode": name = args[1].lower() if name == 'video': mav.gopro_set_request_send(0, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_CAPTURE_MODE, 0) return elif name == 'camera': mav.gopro_set_request_send(0, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_CAPTURE_MODE, 1) return else: print("unrecognized") return if args[0] == "power": name = args[1].lower() if name == 'on': mav.gopro_set_request_send(0, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_POWER, 1) return elif name == 'off': mav.gopro_set_request_send(0, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_POWER, 0) return else: print("unrecognized") return print(usage)
show gopro status
def cmd_gopro_status(self, args): '''show gopro status''' master = self.master if 'GOPRO_HEARTBEAT' in master.messages: print(master.messages['GOPRO_HEARTBEAT']) else: print("No GOPRO_HEARTBEAT messages")
Returns the altitude (m ASL) of a given lat/long pair, or None if unknown
def GetElevation(self, latitude, longitude, timeout=0): '''Returns the altitude (m ASL) of a given lat/long pair, or None if unknown''' if latitude is None or longitude is None: return None if self.database == 'srtm': TileID = (numpy.floor(latitude), numpy.floor(longitude)) if TileID in self.tileDict: alt = self.tileDict[TileID].getAltitudeFromLatLon(latitude, longitude) else: tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude)) if tile == 0: if timeout > 0: t0 = time.time() while time.time() < t0+timeout and tile == 0: tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude)) if tile == 0: time.sleep(0.1) if tile == 0: return None self.tileDict[TileID] = tile alt = tile.getAltitudeFromLatLon(latitude, longitude) if self.database == 'geoscience': alt = self.mappy.getAltitudeAtPoint(latitude, longitude) return alt
handle double clicks on URL text
def on_text_url(self, event): '''handle double clicks on URL text''' try: import webbrowser except ImportError: return mouse_event = event.GetMouseEvent() if mouse_event.LeftDClick(): url_start = event.GetURLStart() url_end = event.GetURLEnd() url = self.control.GetRange(url_start, url_end) try: # attempt to use google-chrome browser_controller = webbrowser.get('google-chrome') browser_controller.open_new_tab(url) except webbrowser.Error: # use the system configured default browser webbrowser.open_new_tab(url)
handle an incoming mavlink packet
def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' type = msg.get_type() master = self.master # add some status fields if type in [ 'RC_CHANNELS' ]: ilock = self.get_rc_input(msg, self.interlock_channel) if ilock <= 0: self.console.set_status('ILOCK', 'ILOCK:--', fg='grey', row=4) elif ilock >= 1800: self.console.set_status('ILOCK', 'ILOCK:ON', fg='red', row=4) else: self.console.set_status('ILOCK', 'ILOCK:OFF', fg='green', row=4) override = self.get_rc_input(msg, self.override_channel) if override <= 0: self.console.set_status('OVR', 'OVR:--', fg='grey', row=4) elif override >= 1800: self.console.set_status('OVR', 'OVR:ON', fg='red', row=4) else: self.console.set_status('OVR', 'OVR:OFF', fg='green', row=4) zeroi = self.get_rc_input(msg, self.zero_I_channel) if zeroi <= 0: self.console.set_status('ZEROI', 'ZEROI:--', fg='grey', row=4) elif zeroi >= 1800: self.console.set_status('ZEROI', 'ZEROI:ON', fg='red', row=4) else: self.console.set_status('ZEROI', 'ZEROI:OFF', fg='green', row=4) novtol = self.get_rc_input(msg, self.no_vtol_channel) if novtol <= 0: self.console.set_status('NOVTOL', 'NOVTOL:--', fg='grey', row=4) elif novtol >= 1800: self.console.set_status('NOVTOL', 'NOVTOL:ON', fg='red', row=4) else: self.console.set_status('NOVTOL', 'NOVTOL:OFF', fg='green', row=4) if type in [ 'SERVO_OUTPUT_RAW' ]: rsc = self.get_pwm_output(msg, self.rsc_out_channel) if rsc <= 0: self.console.set_status('RSC', 'RSC:--', fg='grey', row=4) elif rsc <= 1200: self.console.set_status('RSC', 'RSC:%u' % rsc, fg='red', row=4) elif rsc <= 1600: self.console.set_status('RSC', 'RSC:%u' % rsc, fg='orange', row=4) else: self.console.set_status('RSC', 'RSC:%u' % rsc, fg='green', row=4) thr = self.get_pwm_output(msg, self.fwd_thr_channel) if thr <= 0: self.console.set_status('FTHR', 'FTHR:--', fg='grey', row=4) elif thr <= 1100: self.console.set_status('FTHR', 'FTHR:%u' % thr, fg='red', row=4) elif thr <= 1500: self.console.set_status('FTHR', 'FTHR:%u' % thr, fg='orange', row=4) else: self.console.set_status('FTHR', 'FTHR:%u' % thr, fg='green', row=4) if type in [ 'RPM' ]: rpm = msg.rpm1 if rpm < 1000: rpm_colour = 'red' elif rpm < 2000: rpm_colour = 'orange' else: rpm_colour = 'green' self.console.set_status('RPM', 'RPM: %u' % rpm, fg=rpm_colour, row=4)
update which channels provide input
def update_channels(self): '''update which channels provide input''' self.interlock_channel = -1 self.override_channel = -1 self.zero_I_channel = -1 self.no_vtol_channel = -1 # output channels self.rsc_out_channel = 9 self.fwd_thr_channel = 10 for ch in range(1,16): option = self.get_mav_param("RC%u_OPTION" % ch, 0) if option == 32: self.interlock_channel = ch; elif option == 63: self.override_channel = ch; elif option == 64: self.zero_I_channel = ch; elif option == 65: self.override_channel = ch; elif option == 66: self.no_vtol_channel = ch; function = self.get_mav_param("SERVO%u_FUNCTION" % ch, 0) if function == 32: self.rsc_out_channel = ch if function == 70: self.fwd_thr_channel = ch
run periodic tasks
def idle_task(self): '''run periodic tasks''' now = time.time() if now - self.last_chan_check >= 1: self.last_chan_check = now self.update_channels()
rally loader by system ID
def rallyloader(self): '''rally loader by system ID''' if not self.target_system in self.rallyloader_by_sysid: self.rallyloader_by_sysid[self.target_system] = mavwp.MAVRallyLoader(self.settings.target_system, self.settings.target_component) return self.rallyloader_by_sysid[self.target_system]
called in idle time
def idle_task(self): '''called in idle time''' try: data = self.port.recv(1024) # Attempt to read up to 1024 bytes. except socket.error as e: if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]: return raise try: self.send_rtcm_msg(data) except Exception as e: print("DGPS: GPS Inject Failed:", e)
fps command
def fpsInformation(self,args): '''fps command''' invalidStr = 'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.' if len(args)>0: if args[0] == "get": '''Get the current framerate.''' if (self.fps == 0.0): print('Horizon Framerate: Unrestricted') else: print("Horizon Framerate: " + str(self.fps)) elif args[0] == "set": if len(args)==2: self.fps = float(args[1]) if (self.fps != 0): self.sendDelay = 1.0/self.fps else: self.sendDelay = 0.0 self.msgList.append(FPS(self.fps)) if (self.fps == 0.0): print('Horizon Framerate: Unrestricted') else: print("Horizon Framerate: " + str(self.fps)) else: print(invalidStr) else: print(invalidStr) else: print(invalidStr)
handle an incoming mavlink packet
def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' 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))
help commands
def cmd_help(self, args): '''help commands''' if len(args) < 1: self.print_usage() return if args[0] == "about": print(self.about_string()) elif args[0] == "site": print("See http://ardupilot.github.io/MAVProxy/ for documentation") else: self.print_usage()
set the image to be displayed
def set_image(self, img): '''set the image to be displayed''' with warnings.catch_warnings(): warnings.simplefilter('ignore') if hasattr(img, 'shape'): (width, height) = (img.shape[1], img.shape[0]) self._bmp = wx.BitmapFromBuffer(width, height, np.uint8(img)) # http://stackoverflow.com/a/16866833/2559632 elif hasattr(img, 'GetHeight'): self._bmp = wx.BitmapFromImage(img) else: print("Unsupported image type: %s" % type(img)) return self.SetMinSize((self._bmp.GetWidth(), self._bmp.GetHeight()))
returns information about module
def status(self): '''returns information about module''' if self.download is None: return "Not started" transferred = self.download - self.prev_download self.prev_download = self.download now = time.time() interval = now - self.last_status_time self.last_status_time = now return("DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s " "Block:%(block_cnt)d Missing:%(missing)d Fixed:%(fixed)d " "Abandoned:%(abandoned)d" % {"interval": interval, "rate": transferred/(interval*1000), "block_cnt": self.last_seqno, "missing": len(self.missing_blocks), "fixed": self.missing_found, "abandoned": self.abandoned, "state": "Inactive" if self.stopped else "Active"})
print out statistics every 10 seconds from idle loop
def idle_print_status(self): '''print out statistics every 10 seconds from idle loop''' now = time.time() if (now - self.last_idle_status_printed_time) >= 10: print(self.status()) self.last_idle_status_printed_time = now
Send packets to UAV in idle loop
def idle_send_acks_and_nacks(self): '''Send packets to UAV in idle loop''' max_blocks_to_send = 10 blocks_sent = 0 i = 0 now = time.time() while (i < len(self.blocks_to_ack_and_nack) and blocks_sent < max_blocks_to_send): # print("ACKLIST: %s" % # ([x[1] for x in self.blocks_to_ack_and_nack],)) stuff = self.blocks_to_ack_and_nack[i] [master, block, status, first_sent, last_sent] = stuff if status == 1: # print("DFLogger: ACKing block (%d)" % (block,)) mavstatus = mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_ACK (target_sys, target_comp) = self.sender self.master.mav.remote_log_block_status_send(target_sys, target_comp, block, mavstatus) blocks_sent += 1 del self.acking_blocks[block] del self.blocks_to_ack_and_nack[i] continue if block not in self.missing_blocks: # we've received this block now del self.blocks_to_ack_and_nack[i] continue # give up on packet if we have seen one with a much higher # number (or after 60 seconds): if (self.last_seqno - block > 200) or (now - first_sent > 60): if self.log_settings.verbose: print("DFLogger: Abandoning block (%d)" % (block,)) del self.blocks_to_ack_and_nack[i] del self.missing_blocks[block] self.abandoned += 1 continue i += 1 # only send each nack every-so-often: if last_sent is not None: if now - last_sent < 0.1: continue if self.log_settings.verbose: print("DFLogger: Asking for block (%d)" % (block,)) mavstatus = mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_NACK (target_sys, target_comp) = self.sender self.master.mav.remote_log_block_status_send(target_sys, target_comp, block, mavstatus) blocks_sent += 1 stuff[4] = now
send a stop packet (if we haven't sent one in the last second)
def tell_sender_to_stop(self, m): '''send a stop packet (if we haven't sent one in the last second)''' now = time.time() if now - self.time_last_stop_packet_sent < 1: return if self.log_settings.verbose: print("DFLogger: Sending stop packet") self.time_last_stop_packet_sent = now self.master.mav.remote_log_block_status_send( m.get_srcSystem(), m.get_srcComponent(), mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_STOP, 1)
send a start packet (if we haven't sent one in the last second)
def tell_sender_to_start(self): '''send a start packet (if we haven't sent one in the last second)''' now = time.time() if now - self.time_last_start_packet_sent < 1: return self.time_last_start_packet_sent = now if self.log_settings.verbose: print("DFLogger: Sending start packet") target_sys = self.log_settings.df_target_system target_comp = self.log_settings.df_target_component self.master.mav.remote_log_block_status_send( target_sys, target_comp, mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_START, 1)
returns true if this packet is appropriately addressed
def packet_is_for_me(self, m): '''returns true if this packet is appropriately addressed''' if m.target_system != self.master.mav.srcSystem: return False if m.target_component != self.master.mav.srcComponent: return False # if have a sender we can also check the source address: if self.sender is not None: if (m.get_srcSystem(), m.get_srcComponent()) != self.sender: return False return True
handle mavlink packets
def mavlink_packet(self, m): '''handle mavlink packets''' if m.get_type() == 'REMOTE_LOG_DATA_BLOCK': if not self.packet_is_for_me(m): self.dropped += 1 return if self.sender is None and m.seqno == 0: if self.log_settings.verbose: print("DFLogger: Received data packet - starting new log") self.start_new_log() self.sender = (m.get_srcSystem(), m.get_srcComponent()) if self.sender is None: # No connection right now, and this packet did not start one return if self.stopped: # send a stop packet @1Hz until the other end gets the idea: self.tell_sender_to_stop(m) return if self.sender is not None: size = len(m.data) data = ''.join(str(chr(x)) for x in m.data[:size]) ofs = size*(m.seqno) self.logfile.seek(ofs) self.logfile.write(data) if m.seqno in self.missing_blocks: if self.log_settings.verbose: print("DFLogger: Got missing block: %d" % (m.seqno,)) del self.missing_blocks[m.seqno] self.missing_found += 1 self.blocks_to_ack_and_nack.append( [self.master, m.seqno, 1, time.time(), None] ) self.acking_blocks[m.seqno] = 1 # print("DFLogger: missing: %s" % # (str(self.missing_blocks),)) else: self.do_ack_block(m.seqno) if self.last_seqno < m.seqno: self.last_seqno = m.seqno self.download += size
Create a new figure manager instance for the given figure.
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ frame = FigureFrameWxAgg(num, figure) figmgr = frame.get_figure_manager() if matplotlib.is_interactive(): figmgr.frame.Show() return figmgr
Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance.
def _convert_agg_to_wx_image(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgb -> image image = wx.EmptyImage(int(agg.width), int(agg.height)) image.SetData(agg.tostring_rgb()) return image else: # agg => rgba buffer -> bitmap => clipped bitmap => image return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox))
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance.
def _convert_agg_to_wx_bitmap(agg, bbox): """ Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance. """ if bbox is None: # agg => rgba buffer -> bitmap return wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height), agg.buffer_rgba()) else: # agg => rgba buffer -> bitmap => clipped bitmap return _WX28_clipped_agg_as_bitmap(agg, bbox)
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap. Note: agg must be a backend_agg.RendererAgg instance.
def _WX28_clipped_agg_as_bitmap(agg, bbox): """ Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap. Note: agg must be a backend_agg.RendererAgg instance. """ l, b, width, height = bbox.bounds r = l + width t = b + height srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height), agg.buffer_rgba()) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destBmp = wx.EmptyBitmap(int(width), int(height)) destDC = wx.MemoryDC() destDC.SelectObject(destBmp) destDC.BeginDrawing() x = int(l) y = int(int(agg.height) - t) destDC.Blit(0, 0, int(width), int(height), srcDC, x, y) destDC.EndDrawing() srcDC.SelectObject(wx.NullBitmap) destDC.SelectObject(wx.NullBitmap) return destBmp
Render the figure using agg.
def draw(self, drawDC=None): """ Render the figure using agg. """ DEBUG_MSG("draw()", 1, self) FigureCanvasAgg.draw(self) self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self._isDrawn = True self.gui_repaint(drawDC=drawDC)
Transfer the region of the agg buffer defined by bbox to the display. If bbox is None, the entire buffer is transferred.
def blit(self, bbox=None): """ Transfer the region of the agg buffer defined by bbox to the display. If bbox is None, the entire buffer is transferred. """ if bbox is None: self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None) self.gui_repaint() return l, b, w, h = bbox.bounds r = l + w t = b + h x = int(l) y = int(self.bitmap.GetHeight() - t) srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None) srcDC = wx.MemoryDC() srcDC.SelectObject(srcBmp) destDC = wx.MemoryDC() destDC.SelectObject(self.bitmap) destDC.BeginDrawing() destDC.Blit(x, y, int(w), int(h), srcDC, x, y) destDC.EndDrawing() destDC.SelectObject(wx.NullBitmap) srcDC.SelectObject(wx.NullBitmap) self.gui_repaint()
write to the console
def write(self, text, fg='black', bg='white'): '''write to the console''' if isinstance(text, str): sys.stdout.write(text) else: sys.stdout.write(str(text)) sys.stdout.flush()
set gcs location
def cmd_antenna(self, args): '''set gcs location''' if len(args) != 2: if self.gcs_location is None: print("GCS location not set") else: print("GCS location %s" % str(self.gcs_location)) return self.gcs_location = (float(args[0]), float(args[1]))
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' 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))
start/stop RC calibration
def cmd_rccal(self, args): '''start/stop RC calibration''' if len(args) < 1: self.print_cal_usage() return if (args[0] == "start"): if len(args) > 1: self.num_channels = int(args[1]) print("Calibrating %u channels" % self.num_channels) print("WARNING: remove propellers from electric planes!!") print("Push return when ready to calibrate.") raw_input() self.clear_rc_cal() self.calibrating = True elif (args[0] == "done"): self.calibrating = False self.apply_rc_cal() else: self.print_cal_usage()
set RCx_TRIM
def cmd_rctrim(self, args): '''set RCx_TRIM''' if not 'RC_CHANNELS_RAW' in self.status.msgs: print("No RC_CHANNELS_RAW to trim with") return m = self.status.msgs['RC_CHANNELS_RAW'] for ch in range(1,5): self.param_set('RC%u_TRIM' % ch, getattr(m, 'chan%u_raw' % ch))
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' #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))
handle link commands
def cmd_signing(self, args): '''handle link commands''' usage = "signing: <setup|remove|disable|key> passphrase" if len(args) == 0: print(usage) elif args[0] == 'setup': self.cmd_signing_setup(args[1:]) elif args[0] == 'key': self.cmd_signing_key(args[1:]) elif args[0] == 'disable': self.cmd_signing_disable(args[1:]) elif args[0] == 'remove': self.cmd_signing_remove(args[1:]) else: print(usage)
convert a passphrase to a 32 byte key
def passphrase_to_key(self, passphrase): '''convert a passphrase to a 32 byte key''' import hashlib h = hashlib.new('sha256') h.update(passphrase) return h.digest()
setup signing key on board
def cmd_signing_setup(self, args): '''setup signing key on board''' if len(args) == 0: print("usage: signing setup passphrase") return if not self.master.mavlink20(): print("You must be using MAVLink2 for signing") return passphrase = args[0] key = self.passphrase_to_key(passphrase) secret_key = [] for b in key: secret_key.append(ord(b)) epoch_offset = 1420070400 now = max(time.time(), epoch_offset) initial_timestamp = int((now - epoch_offset)*1e5) self.master.mav.setup_signing_send(self.target_system, self.target_component, secret_key, initial_timestamp) print("Sent secret_key") self.cmd_signing_key([passphrase])
see if an unsigned packet should be allowed
def allow_unsigned(self, mav, msgId): '''see if an unsigned packet should be allowed''' if self.allow is None: self.allow = { mavutil.mavlink.MAVLINK_MSG_ID_RADIO : True, mavutil.mavlink.MAVLINK_MSG_ID_RADIO_STATUS : True } if msgId in self.allow: return True if self.settings.allow_unsigned: return True return False
set signing key on connection
def cmd_signing_key(self, args): '''set signing key on connection''' if len(args) == 0: print("usage: signing setup passphrase") return if not self.master.mavlink20(): print("You must be using MAVLink2 for signing") return passphrase = args[0] key = self.passphrase_to_key(passphrase) self.master.setup_signing(key, sign_outgoing=True, allow_unsigned_callback=self.allow_unsigned) print("Setup signing key")
remove signing from server
def cmd_signing_remove(self, args): '''remove signing from server''' if not self.master.mavlink20(): print("You must be using MAVLink2 for signing") return self.master.mav.setup_signing_send(self.target_system, self.target_component, [0]*32, 0) self.master.disable_signing() print("Removed signing")
#another drawing routine #(taken from src/generic/renderg.cpp) #Could port this later for animating the button when clicking const wxCoord x = rect.x, y = rect.y, w = rect.width, h = rect.height; dc.SetBrush(*wxTRANSPARENT_BRUSH); wxPen pen(*wxBLACK, 1); dc.SetPen(pen); dc.DrawLine( x+w, y, x+w, y+h ); // right (outer) dc.DrawRectangle( x, y+h, w+1, 1 ); // bottom (outer) pen.SetColour(wxColour(wxT("DARK GREY"))); dc.SetPen(pen); dc.DrawLine( x+w-1, y, x+w-1, y+h ); // right (inner) dc.DrawRectangle( x+1, y+h-1, w-2, 1 ); // bottom (inner) pen.SetColour(*wxWHITE); dc.SetPen(pen); dc.DrawRectangle( x, y, w, 1 ); // top (outer) dc.DrawRectangle( x, y, 1, h ); // left (outer) dc.DrawLine( x, y+h-1, x+1, y+h-1 ); dc.DrawLine( x+w-1, y, x+w-1, y+1 );
def Draw(self, grid, attr, dc, rect, row, col, isSelected): dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNFACE))) dc.DrawRectangle( rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight()) #draw a shaded rectangle to emulate a button #(taken from src/generic/renderg.cpp) strength = 1 pen1 = wx.Pen(wx.WHITE, strength) dc.SetPen(pen1) dc.DrawLine(rect.GetLeft()+strength-1, rect.GetTop()+strength-1, rect.GetLeft()+strength-1, rect.GetBottom()-strength+1) dc.DrawLine(rect.GetLeft()+strength-1, rect.GetTop()+strength-1, rect.GetRight()-strength, rect.GetTop()+strength-1) pen2 = wx.Pen(wx.BLACK, strength) dc.SetPen(pen2) dc.DrawLine(rect.GetRight()-strength, rect.GetTop(), rect.GetRight()-strength, rect.GetBottom()); dc.DrawLine(rect.GetLeft(), rect.GetBottom(), rect.GetRight() - strength, rect.GetBottom()); ''' #another drawing routine #(taken from src/generic/renderg.cpp) #Could port this later for animating the button when clicking const wxCoord x = rect.x, y = rect.y, w = rect.width, h = rect.height; dc.SetBrush(*wxTRANSPARENT_BRUSH); wxPen pen(*wxBLACK, 1); dc.SetPen(pen); dc.DrawLine( x+w, y, x+w, y+h ); // right (outer) dc.DrawRectangle( x, y+h, w+1, 1 ); // bottom (outer) pen.SetColour(wxColour(wxT("DARK GREY"))); dc.SetPen(pen); dc.DrawLine( x+w-1, y, x+w-1, y+h ); // right (inner) dc.DrawRectangle( x+1, y+h-1, w-2, 1 ); // bottom (inner) pen.SetColour(*wxWHITE); dc.SetPen(pen); dc.DrawRectangle( x, y, w, 1 ); // top (outer) dc.DrawRectangle( x, y, 1, h ); // left (outer) dc.DrawLine( x, y+h-1, x+1, y+h-1 ); dc.DrawLine( x+w-1, y, x+w-1, y+1 ); ''' # draw the button-label dc.SetBackgroundMode(wx.TRANSPARENT ) dc.SetTextForeground(attr.GetTextColour() ) dc.SetFont( attr.GetFont() ) #dc.DrawLabel( wxT("Delete"), rect, dc.DrawLabel( self.label, rect, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
handle output commands
def cmd_output(self, args): '''handle output commands''' if len(args) < 1 or args[0] == "list": self.cmd_output_list() elif args[0] == "add": if len(args) != 2: print("Usage: output add OUTPUT") return self.cmd_output_add(args[1:]) elif args[0] == "remove": if len(args) != 2: print("Usage: output remove OUTPUT") return self.cmd_output_remove(args[1:]) elif args[0] == "sysid": if len(args) != 3: print("Usage: output sysid SYSID OUTPUT") return self.cmd_output_sysid(args[1:]) else: print("usage: output <list|add|remove|sysid>")
list outputs
def cmd_output_list(self): '''list outputs''' print("%u outputs" % len(self.mpstate.mav_outputs)) for i in range(len(self.mpstate.mav_outputs)): conn = self.mpstate.mav_outputs[i] print("%u: %s" % (i, conn.address)) if len(self.mpstate.sysid_outputs) > 0: print("%u sysid outputs" % len(self.mpstate.sysid_outputs)) for sysid in self.mpstate.sysid_outputs: conn = self.mpstate.sysid_outputs[sysid] print("%u: %s" % (sysid, conn.address))
add new output
def cmd_output_add(self, args): '''add new output''' device = args[0] print("Adding output %s" % device) try: conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system) conn.mav.srcComponent = self.settings.source_component except Exception: print("Failed to connect to %s" % device) return self.mpstate.mav_outputs.append(conn) try: mp_util.child_fd_list_add(conn.port.fileno()) except Exception: pass
add new output for a specific MAVLink sysID
def cmd_output_sysid(self, args): '''add new output for a specific MAVLink sysID''' sysid = int(args[0]) device = args[1] print("Adding output %s for sysid %u" % (device, sysid)) try: conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system) conn.mav.srcComponent = self.settings.source_component except Exception: print("Failed to connect to %s" % device) return try: mp_util.child_fd_list_add(conn.port.fileno()) except Exception: pass if sysid in self.mpstate.sysid_outputs: self.mpstate.sysid_outputs[sysid].close() self.mpstate.sysid_outputs[sysid] = conn
remove an output
def cmd_output_remove(self, args): '''remove an output''' device = args[0] for i in range(len(self.mpstate.mav_outputs)): conn = self.mpstate.mav_outputs[i] if str(i) == device or conn.address == device: print("Removing output %s" % conn.address) try: mp_util.child_fd_list_add(conn.port.fileno()) except Exception: pass conn.close() self.mpstate.mav_outputs.pop(i) return
called on idle
def idle_task(self): '''called on idle''' for m in self.mpstate.mav_outputs: m.source_system = self.settings.source_system m.mav.srcSystem = m.source_system m.mav.srcComponent = self.settings.source_component
child process - this holds all the GUI elements
def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx from MAVProxy.modules.mavproxy_map.mp_slipmap_ui import MPSlipMapFrame state = self self.mt = mp_tile.MPTile(download=self.download, service=self.service, tile_delay=self.tile_delay, debug=self.debug, max_zoom=self.max_zoom) state.layers = {} state.info = {} state.need_redraw = True self.app = wx.App(False) self.app.SetExitOnFrameDelete(True) self.app.frame = MPSlipMapFrame(state=self) self.app.frame.Show() self.app.MainLoop()
set center of view
def set_center(self, lat, lon): '''set center of view''' self.object_queue.put(SlipCenter((lat,lon)))
set follow on/off on an object
def set_follow_object(self, key, enable): '''set follow on/off on an object''' self.object_queue.put(SlipFollowObject(key, enable))
return next event or None
def get_event(self): '''return next event or None''' if self.event_queue.qsize() == 0: return None evt = self.event_queue.get() while isinstance(evt, win_layout.WinLayout): win_layout.set_layout(evt, self.set_layout) if self.event_queue.qsize() == 0: return None evt = self.event_queue.get() return evt
handle layout command
def cmd_layout(self, args): '''handle layout command''' from MAVProxy.modules.lib import win_layout if len(args) < 1: print("usage: layout <save|load>") return if args[0] == "load": win_layout.load_layout(self.mpstate.settings.vehicle_name) elif args[0] == "save": win_layout.save_layout(self.mpstate.settings.vehicle_name)
convert a PIL Image to a wx image
def PILTowx(pimg): '''convert a PIL Image to a wx image''' from MAVProxy.modules.lib.wx_loader import wx wimg = wx.EmptyImage(pimg.size[0], pimg.size[1]) try: wimg.SetData(pimg.convert('RGB').tobytes()) except NotImplementedError: # old, removed method: wimg.SetData(pimg.convert('RGB').tostring()) return wimg
return a path to store mavproxy data
def dot_mavproxy(name=None): '''return a path to store mavproxy data''' if 'HOME' not in os.environ: dir = os.path.join(os.environ['LOCALAPPDATA'], '.mavproxy') else: dir = os.path.join(os.environ['HOME'], '.mavproxy') mkdir_p(dir) if name is None: return dir return os.path.join(dir, name)
download a URL and return the content
def download_url(url): '''download a URL and return the content''' if sys.version_info.major < 3: from urllib2 import urlopen as url_open from urllib2 import URLError as url_error else: from urllib.request import urlopen as url_open from urllib.error import URLError as url_error try: resp = url_open(url) headers = resp.info() except url_error as e: print('Error downloading %s' % url) return None return resp.read()
download an array of files
def download_files(files): '''download an array of files''' for (url, file) in files: print("Downloading %s as %s" % (url, file)) data = download_url(url) if data is None: continue try: open(file, mode='wb').write(data) except Exception as e: print("Failed to save to %s : %s" % (file, e))
null terminate a string for py3
def null_term(str): '''null terminate a string for py3''' if sys.version_info.major < 3: return str if isinstance(str, bytes): str = str.decode("utf-8") idx = str.find("\0") if idx != -1: str = str[:idx] return str
decode one device ID. Used for 'devid' command in mavproxy and MAVExplorer
def decode_devid(devid, pname): '''decode one device ID. Used for 'devid' command in mavproxy and MAVExplorer''' devid = int(devid) if devid == 0: return bus_type=devid & 0x07 bus=(devid>>3) & 0x1F address=(devid>>8)&0xFF devtype=(devid>>16) bustypes = { 1: "I2C", 2: "SPI", 3: "UAVCAN", 4: "SITL" } compass_types = { 0x01 : "DEVTYPE_HMC5883_OLD", 0x07 : "DEVTYPE_HMC5883", 0x02 : "DEVTYPE_LSM303D", 0x04 : "DEVTYPE_AK8963 ", 0x05 : "DEVTYPE_BMM150 ", 0x06 : "DEVTYPE_LSM9DS1", 0x08 : "DEVTYPE_LIS3MDL", 0x09 : "DEVTYPE_AK09916", 0x0A : "DEVTYPE_IST8310", 0x0B : "DEVTYPE_ICM20948", 0x0C : "DEVTYPE_MMC3416", 0x0D : "DEVTYPE_QMC5883L", 0x0E : "DEVTYPE_MAG3110", 0x0F : "DEVTYPE_SITL", 0x10 : "DEVTYPE_IST8308", 0x11 : "DEVTYPE_RM3100", } imu_types = { 0x09 : "DEVTYPE_BMI160", 0x10 : "DEVTYPE_L3G4200D", 0x11 : "DEVTYPE_ACC_LSM303D", 0x12 : "DEVTYPE_ACC_BMA180", 0x13 : "DEVTYPE_ACC_MPU6000", 0x16 : "DEVTYPE_ACC_MPU9250", 0x17 : "DEVTYPE_ACC_IIS328DQ", 0x21 : "DEVTYPE_GYR_MPU6000", 0x22 : "DEVTYPE_GYR_L3GD20", 0x24 : "DEVTYPE_GYR_MPU9250", 0x25 : "DEVTYPE_GYR_I3G4250D", 0x26 : "DEVTYPE_GYR_LSM9DS1", 0x27 : "DEVTYPE_INS_ICM20789", 0x28 : "DEVTYPE_INS_ICM20689", 0x29 : "DEVTYPE_INS_BMI055", 0x2A : "DEVTYPE_SITL", 0x2B : "DEVTYPE_INS_BMI088", 0x2C : "DEVTYPE_INS_ICM20948", 0x2D : "DEVTYPE_INS_ICM20648", 0x2E : "DEVTYPE_INS_ICM20649", 0x2F : "DEVTYPE_INS_ICM20602", } decoded_devname = "" if pname.startswith("COMPASS"): decoded_devname = compass_types.get(devtype, "UNKNOWN") if pname.startswith("INS"): decoded_devname = imu_types.get(devtype, "UNKNOWN") print("%s: bus_type:%s(%u) bus:%u address:%u(0x%x) devtype:%u(0x%x) %s" % ( pname, bustypes.get(bus_type,"UNKNOWN"), bus_type, bus, address, address, devtype, devtype, decoded_devname))
This must return a (User, built) 2-tuple for the given LDAP user. username is the Django-friendly username of the user. ldap_user.dn is the user's DN and ldap_user.attrs contains all of their LDAP attributes. The returned User object may be an unsaved model instance.
def get_or_build_user(self, username, ldap_user): """ This must return a (User, built) 2-tuple for the given LDAP user. username is the Django-friendly username of the user. ldap_user.dn is the user's DN and ldap_user.attrs contains all of their LDAP attributes. The returned User object may be an unsaved model instance. """ model = self.get_user_model() if self.settings.USER_QUERY_FIELD: query_field = self.settings.USER_QUERY_FIELD query_value = ldap_user.attrs[self.settings.USER_ATTR_MAP[query_field]][0] lookup = query_field else: query_field = model.USERNAME_FIELD query_value = username.lower() lookup = "{}__iexact".format(query_field) try: user = model.objects.get(**{lookup: query_value}) except model.DoesNotExist: user = model(**{query_field: query_value}) built = True else: built = False return (user, built)
Populates the Django user object using the default bind credentials.
def populate_user(self): """ Populates the Django user object using the default bind credentials. """ user = None try: # self.attrs will only be non-None if we were able to load this user # from the LDAP directory, so this filters out nonexistent users. if self.attrs is not None: self._get_or_create_user(force_populate=True) user = self._user except ldap.LDAPError as e: results = ldap_error.send( self.backend.__class__, context="populate_user", user=self._user, exception=e, ) if len(results) == 0: logger.warning( "Caught LDAPError while authenticating {}: {}".format( self._username, pprint.pformat(e) ) ) except Exception as e: logger.warning("{} while authenticating {}".format(e, self._username)) raise return user
Binds to the LDAP server with the user's DN and password. Raises AuthenticationFailed on failure.
def _authenticate_user_dn(self, password): """ Binds to the LDAP server with the user's DN and password. Raises AuthenticationFailed on failure. """ if self.dn is None: raise self.AuthenticationFailed("failed to map the username to a DN.") try: sticky = self.settings.BIND_AS_AUTHENTICATING_USER self._bind_as(self.dn, password, sticky=sticky) except ldap.INVALID_CREDENTIALS: raise self.AuthenticationFailed("user DN/password rejected by LDAP server.")