INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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_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)
check starter settings
def valid_starter_settings(self): '''check starter settings''' if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8: print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan) return False if self.gasheli_settings.starter_chan <= 0 or self.gasheli_settings.starter_chan > 14: print("Invalid starter channel %d" % self.gasheli_settings.starter_chan) return False return True
run periodic tasks
def idle_task(self): '''run periodic tasks''' if self.starting_motor: if self.gasheli_settings.ignition_disable_time > 0: elapsed = time.time() - self.motor_t1 if elapsed >= self.gasheli_settings.ignition_disable_time: self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, self.old_override) self.starting_motor = False if self.stopping_motor: elapsed = time.time() - self.motor_t1 if elapsed >= self.gasheli_settings.ignition_stop_time: # hand back control to RC self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, self.old_override) self.stopping_motor = False
start motor
def start_motor(self): '''start motor''' if not self.valid_starter_settings(): return self.motor_t1 = time.time() self.stopping_motor = False if self.gasheli_settings.ignition_disable_time > 0: self.old_override = self.module('rc').get_override_chan(self.gasheli_settings.ignition_chan-1) self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, 1000) self.starting_motor = True else: # nothing more to do self.starting_motor = False # setup starter run self.master.mav.command_long_send(self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_DO_REPEAT_SERVO, 0, self.gasheli_settings.starter_chan, self.gasheli_settings.starter_pwm_on, 1, self.gasheli_settings.starter_time*2, 0, 0, 0) print("Starting motor")
stop motor
def stop_motor(self): '''stop motor''' if not self.valid_starter_settings(): return self.motor_t1 = time.time() self.starting_motor = False self.stopping_motor = True self.old_override = self.module('rc').get_override_chan(self.gasheli_settings.ignition_chan-1) self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, 1000) print("Stopping motor")
gas help commands
def cmd_gasheli(self, args): '''gas help commands''' usage = "Usage: gasheli <start|stop|set>" if len(args) < 1: print(usage) return if args[0] == "start": self.start_motor() elif args[0] == "stop": self.stop_motor() elif args[0] == "set": self.gasheli_settings.command(args[1:]) else: print(usage)
per-sysid wploader
def wploader(self): '''per-sysid wploader''' if self.target_system not in self.wploader_by_sysid: self.wploader_by_sysid[self.target_system] = mavwp.MAVWPLoader() return self.wploader_by_sysid[self.target_system]
send some more WP requests
def send_wp_requests(self, wps=None): '''send some more WP requests''' if wps is None: wps = self.missing_wps_to_request() tnow = time.time() for seq in wps: #print("REQUESTING %u/%u (%u)" % (seq, self.wploader.expected_count, i)) self.wp_requested[seq] = tnow self.master.waypoint_request_send(seq)
show status of wp download
def wp_status(self): '''show status of wp download''' try: print("Have %u of %u waypoints" % (self.wploader.count()+len(self.wp_received), self.wploader.expected_count)) except Exception: print("Have %u waypoints" % (self.wploader.count()+len(self.wp_received)))
show slope of waypoints
def wp_slope(self): '''show slope of waypoints''' last_w = None for i in range(1, self.wploader.count()): w = self.wploader.wp(i) if w.command not in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_LAND]: continue if last_w is not None: if last_w.frame != w.frame: print("WARNING: frame change %u -> %u at %u" % (last_w.frame, w.frame, i)) delta_alt = last_w.z - w.z if delta_alt == 0: slope = "Level" else: delta_xy = mp_util.gps_distance(w.x, w.y, last_w.x, last_w.y) slope = "%.1f" % (delta_xy / delta_alt) print("WP%u: slope %s" % (i, slope)) last_w = w
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']: self.wploader.expected_count = m.count if self.wp_op is None: #self.console.error("No waypoint load started") pass else: self.wploader.clear() self.console.writeln("Requesting %u waypoints t=%s now=%s" % (m.count, time.asctime(time.localtime(m._timestamp)), time.asctime())) self.send_wp_requests() elif mtype in ['WAYPOINT', 'MISSION_ITEM'] and self.wp_op is not None: if m.seq < self.wploader.count(): #print("DUPLICATE %u" % m.seq) return if m.seq+1 > self.wploader.expected_count: self.console.writeln("Unexpected waypoint number %u - expected %u" % (m.seq, self.wploader.count())) self.wp_received[m.seq] = m next_seq = self.wploader.count() while next_seq in self.wp_received: m = self.wp_received.pop(next_seq) self.wploader.add(m) next_seq += 1 if self.wploader.count() != self.wploader.expected_count: #print("m.seq=%u expected_count=%u" % (m.seq, self.wploader.expected_count)) self.send_wp_requests() return 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 is not None: fname = 'way.txt' if m.get_srcSystem() != 1: fname = 'way_%u.txt' % m.get_srcSystem() waytxt = os.path.join(self.logdir, fname) self.save_waypoints(waytxt) print("Saved waypoints to %s" % waytxt) self.loading_waypoints = False elif self.wp_op == "save": self.save_waypoints(self.wp_save_filename) self.wp_op = None self.wp_requested = {} self.wp_received = {} 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') elif mtype == "MISSION_ITEM_REACHED": wp = self.wploader.wp(m.seq) if wp is None: # should we spit out a warning?! # self.say("No waypoints") pass else: if wp.command == mavutil.mavlink.MAV_CMD_DO_LAND_START: alt_offset = self.get_mav_param('ALT_OFFSET', 0) if alt_offset > 0.005: self.say("ALT OFFSET IS NOT ZERO passing DO_LAND_START")
handle missing waypoints
def idle_task(self): '''handle missing waypoints''' if self.wp_period.trigger(): # cope with packet loss fetching mission if self.master is not None and self.master.time_since('MISSION_ITEM') >= 2 and self.wploader.count() < getattr(self.wploader,'expected_count',0): wps = self.missing_wps_to_request(); print("re-requesting WPs %s" % str(wps)) self.send_wp_requests(wps) if self.module('console') is not None and not self.menu_added_console: self.menu_added_console = True self.module('console').add_menu(self.menu) 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)
save waypoints to a file
def save_waypoints(self, filename): '''save waypoints to a file''' try: #need to remove the leading and trailing quotes in filename self.wploader.save(filename.strip('"')) except Exception as msg: print("Failed to save %s - %s" % (filename, msg)) return print("Saved %u waypoints to %s" % (self.wploader.count(), filename))
save waypoints to a file in a human readable CSV file
def save_waypoints_csv(self, filename): '''save waypoints to a file in a human readable CSV file''' try: #need to remove the leading and trailing quotes in filename self.wploader.savecsv(filename.strip('"')) except Exception as msg: print("Failed to save %s - %s" % (filename, msg)) return print("Saved %u waypoints to CSV %s" % (self.wploader.count(), filename))
get home location
def get_home(self): '''get home location''' if 'HOME_POSITION' in self.master.messages: h = self.master.messages['HOME_POSITION'] return mavutil.mavlink.MAVLink_mission_item_message(self.target_system, self.target_component, 0, 0, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, h.latitude*1.0e-7, h.longitude*1.0e-7, h.altitude*1.0e-3) if self.wploader.count() > 0: return self.wploader.wp(0) return None
add a square flight exclusion zone
def nofly_add(self): '''add a square flight exclusion zone''' try: latlon = self.module('map').click_position except Exception: print("No position chosen") return loader = self.wploader (center_lat, center_lon) = latlon points = [] points.append(mp_util.gps_offset(center_lat, center_lon, -25, 25)) points.append(mp_util.gps_offset(center_lat, center_lon, 25, 25)) points.append(mp_util.gps_offset(center_lat, center_lon, 25, -25)) points.append(mp_util.gps_offset(center_lat, center_lon, -25, -25)) start_idx = loader.count() for p in points: wp = mavutil.mavlink.MAVLink_mission_item_message(0, 0, 0, 0, mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION, 0, 1, 4, 0, 0, 0, p[0], p[1], 0) loader.add(wp) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, start_idx, start_idx+4) print("Added nofly zone")
handle wp change target alt of multiple waypoints
def cmd_wp_changealt(self, args): '''handle wp change target alt of multiple waypoints''' if len(args) < 2: print("usage: wp changealt WPNUM NEWALT <NUMWP>") return idx = int(args[0]) if idx < 1 or idx > self.wploader.count(): print("Invalid wp number %u" % idx) return newalt = float(args[1]) if len(args) >= 3: count = int(args[2]) else: count = 1 for wpnum in range(idx, idx+count): wp = self.wploader.wp(wpnum) if not self.wploader.is_location_command(wp.command): continue wp.z = newalt wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, wpnum) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, idx, idx+count) print("Changed alt for WPs %u:%u to %f" % (idx, idx+(count-1), newalt))
fix up jumps when we add/remove rows
def fix_jumps(self, idx, delta): '''fix up jumps when we add/remove rows''' numrows = self.wploader.count() for row in range(numrows): wp = self.wploader.wp(row) jump_cmds = [mavutil.mavlink.MAV_CMD_DO_JUMP] if hasattr(mavutil.mavlink, "MAV_CMD_DO_CONDITION_JUMP"): jump_cmds.append(mavutil.mavlink.MAV_CMD_DO_CONDITION_JUMP) if wp.command in jump_cmds: p1 = int(wp.param1) if p1 > idx and p1+delta>0: wp.param1 = float(p1+delta) self.wploader.set(wp, row)
handle wp remove
def cmd_wp_remove(self, args): '''handle wp remove''' if len(args) != 1: print("usage: wp remove WPNUM") return idx = int(args[0]) if idx < 0 or idx >= self.wploader.count(): print("Invalid wp number %u" % idx) return wp = self.wploader.wp(idx) # setup for undo self.undo_wp = copy.copy(wp) self.undo_wp_idx = idx self.undo_type = "remove" self.wploader.remove(wp) self.fix_jumps(idx, -1) self.send_all_waypoints() print("Removed WP %u" % idx)
handle wp undo
def cmd_wp_undo(self): '''handle wp undo''' if self.undo_wp_idx == -1 or self.undo_wp is None: print("No undo information") return wp = self.undo_wp if self.undo_type == 'move': wp.target_system = self.target_system wp.target_component = self.target_component self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send(self.target_system, self.target_component, self.undo_wp_idx, self.undo_wp_idx) self.wploader.set(wp, self.undo_wp_idx) print("Undid WP move") elif self.undo_type == 'remove': self.wploader.insert(self.undo_wp_idx, wp) self.fix_jumps(self.undo_wp_idx, 1) self.send_all_waypoints() print("Undid WP remove") else: print("bad undo type") self.undo_wp = None self.undo_wp_idx = -1
waypoint commands
def cmd_wp(self, args): '''waypoint commands''' usage = "usage: wp <editor|list|load|update|save|set|clear|loop|remove|move|movemulti|changealt>" if len(args) < 1: print(usage) return if args[0] == "load": if len(args) != 2: print("usage: wp load <filename>") return self.load_waypoints(args[1]) elif args[0] == "update": if len(args) < 2: print("usage: wp update <filename> <wpnum>") return if len(args) == 3: wpnum = int(args[2]) else: wpnum = -1 self.update_waypoints(args[1], wpnum) elif args[0] == "list": self.wp_op = "list" self.master.waypoint_request_list_send() elif args[0] == "save": if len(args) != 2: print("usage: wp save <filename>") return self.wp_save_filename = args[1] self.wp_op = "save" self.master.waypoint_request_list_send() elif args[0] == "savecsv": if len(args) != 2: print("usage: wp savecsv <filename.csv>") return self.savecsv(args[1]) elif args[0] == "savelocal": if len(args) != 2: print("usage: wp savelocal <filename>") return self.wploader.save(args[1]) elif args[0] == "show": if len(args) != 2: print("usage: wp show <filename>") return self.wploader.load(args[1]) elif args[0] == "move": self.cmd_wp_move(args[1:]) elif args[0] == "movemulti": self.cmd_wp_movemulti(args[1:], None) elif args[0] == "changealt": self.cmd_wp_changealt(args[1:]) elif args[0] == "param": self.cmd_wp_param(args[1:]) elif args[0] == "remove": self.cmd_wp_remove(args[1:]) elif args[0] == "undo": self.cmd_wp_undo() elif args[0] == "set": if len(args) != 2: print("usage: wp set <wpindex>") return self.master.waypoint_set_current_send(int(args[1])) elif args[0] == "clear": self.master.waypoint_clear_all_send() self.wploader.clear() elif args[0] == "editor": if self.module('misseditor'): self.mpstate.functions.process_stdin("module reload misseditor", immediate=True) else: self.mpstate.functions.process_stdin("module load misseditor", immediate=True) elif args[0] == "draw": if not 'draw_lines' in self.mpstate.map_functions: print("No map drawing available") return if self.get_home() is None: print("Need home location - please run gethome") return if len(args) > 1: self.settings.wpalt = int(args[1]) self.mpstate.map_functions['draw_lines'](self.wp_draw_callback) print("Drawing waypoints on map at altitude %d" % self.settings.wpalt) elif args[0] == "sethome": self.set_home_location() elif args[0] == "loop": self.wp_loop() elif args[0] == "noflyadd": self.nofly_add() elif args[0] == "status": self.wp_status() elif args[0] == "slope": self.wp_slope() else: print(usage)
turn a list of values into a CSV line
def csv_line(self, line): '''turn a list of values into a CSV line''' self.csv_sep = "," return self.csv_sep.join(['"' + str(x) + '"' for x in line])
save waypoints to a file in human-readable CSV file
def savecsv(self, filename): '''save waypoints to a file in human-readable CSV file''' f = open(filename, mode='w') headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"] print(self.csv_line(headers)) f.write(self.csv_line(headers) + "\n") for w in self.wploader.wpoints: if getattr(w, 'comment', None): # f.write("# %s\n" % w.comment) pass out_list = [ w.seq, self.pretty_enum_value('MAV_FRAME', w.frame), self.pretty_enum_value('MAV_CMD', w.command), self.pretty_parameter_value(w.param1), self.pretty_parameter_value(w.param2), self.pretty_parameter_value(w.param3), self.pretty_parameter_value(w.param4), self.pretty_parameter_value(w.x), self.pretty_parameter_value(w.y), self.pretty_parameter_value(w.z), ] print(self.csv_line(out_list)) f.write(self.csv_line(out_list) + "\n") f.close()
Print a list of available joysticks
def list_joysticks(): '''Print a list of available joysticks''' print('Available joysticks:') print() for jid in range(pygame.joystick.get_count()): j = pygame.joystick.Joystick(jid) print('({}) {}'.format(jid, j.get_name()))
Allow user to select a joystick from a menu
def select_joystick(): '''Allow user to select a joystick from a menu''' list_joysticks() while True: print('Select a joystick (L to list, Q to quit)'), choice = sys.stdin.readline().strip() if choice.lower() == 'l': list_joysticks() elif choice.lower() == 'q': return elif choice.isdigit(): jid = int(choice) if jid not in range(pygame.joystick.get_count()): print('Invalid joystick.') continue break else: print('What?') return jid
Search for a wxPython installation that matches version. If one is found then sys.path is modified so that version will be imported with a 'import wx', otherwise a VersionError exception is raised. This function should only be called once at the beginning of the application before wxPython is imported. :param versions: Specifies the version to look for, it can either be a string or a list of strings. Each string is compared to the installed wxPythons and the best match is inserted into the sys.path, allowing an 'import wx' to find that version. The version string is composed of the dotted version number (at least 2 of the 4 components) optionally followed by hyphen ('-') separated options (wx port, unicode/ansi, flavour, etc.) A match is determined by how much of the installed version matches what is given in the version parameter. If the version number components don't match then the score is zero, otherwise the score is increased for every specified optional component that is specified and that matches. Please note, however, that it is possible for a match to be selected that doesn't exactly match the versions requested. The only component that is required to be matched is the version number. If you need to require a match on the other components as well, then please use the optional ``optionsRequired`` parameter described next. :param optionsRequired: Allows you to specify that the other components of the version string (such as the port name or character type) are also required to be present for an installed version to be considered a match. Using this parameter allows you to change the selection from a soft, as close as possible match to a hard, exact match.
def select(versions, optionsRequired=False): """ Search for a wxPython installation that matches version. If one is found then sys.path is modified so that version will be imported with a 'import wx', otherwise a VersionError exception is raised. This function should only be called once at the beginning of the application before wxPython is imported. :param versions: Specifies the version to look for, it can either be a string or a list of strings. Each string is compared to the installed wxPythons and the best match is inserted into the sys.path, allowing an 'import wx' to find that version. The version string is composed of the dotted version number (at least 2 of the 4 components) optionally followed by hyphen ('-') separated options (wx port, unicode/ansi, flavour, etc.) A match is determined by how much of the installed version matches what is given in the version parameter. If the version number components don't match then the score is zero, otherwise the score is increased for every specified optional component that is specified and that matches. Please note, however, that it is possible for a match to be selected that doesn't exactly match the versions requested. The only component that is required to be matched is the version number. If you need to require a match on the other components as well, then please use the optional ``optionsRequired`` parameter described next. :param optionsRequired: Allows you to specify that the other components of the version string (such as the port name or character type) are also required to be present for an installed version to be considered a match. Using this parameter allows you to change the selection from a soft, as close as possible match to a hard, exact match. """ if type(versions) == str: versions = [versions] global _selected if _selected is not None: # A version was previously selected, ensure that it matches # this new request for ver in versions: if _selected.Score(_wxPackageInfo(ver), optionsRequired) > 0: return # otherwise, raise an exception raise VersionError("A previously selected wx version does not match the new request.") # If we get here then this is the first time wxversion is used, # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise AlreadyImportedError("wxversion.select() must be called before wxPython is imported") # Look for a matching version and manipulate the sys.path as # needed to allow it to be imported. installed = _find_installed(True) bestMatch = _get_best_match(installed, versions, optionsRequired) if bestMatch is None: raise VersionError("Requested version of wxPython not found") sys.path.insert(0, bestMatch.pathname) # q.v. Bug #1409256 path64 = re.sub('/lib/','/lib64/',bestMatch.pathname) if os.path.isdir(path64): sys.path.insert(0, path64) _selected = bestMatch
Checks to see if the default version of wxPython is greater-than or equal to `minVersion`. If not then it will try to find an installed version that is >= minVersion. If none are available then a message is displayed that will inform the user and will offer to open their web browser to the wxPython downloads page, and will then exit the application.
def ensureMinimal(minVersion, optionsRequired=False): """ Checks to see if the default version of wxPython is greater-than or equal to `minVersion`. If not then it will try to find an installed version that is >= minVersion. If none are available then a message is displayed that will inform the user and will offer to open their web browser to the wxPython downloads page, and will then exit the application. """ assert type(minVersion) == str # ensure that wxPython hasn't been imported yet. if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'): raise AlreadyImportedError("wxversion.ensureMinimal() must be called before wxPython is imported") bestMatch = None minv = _wxPackageInfo(minVersion) # check the default version first defaultPath = _find_default() if defaultPath: defv = _wxPackageInfo(defaultPath, True) if defv >= minv and minv.CheckOptions(defv, optionsRequired): bestMatch = defv # if still no match then check look at all installed versions if bestMatch is None: installed = _find_installed() # The list is in reverse sorted order, so find the first # one that is big enough and optionally matches the # options for inst in installed: if inst >= minv and minv.CheckOptions(inst, optionsRequired): bestMatch = inst break # if still no match then prompt the user if bestMatch is None: if _EM_DEBUG: # We'll do it this way just for the test code below raise VersionError("Requested version of wxPython not found") import wx, webbrowser versions = "\n".join([" "+ver for ver in getInstalled()]) app = wx.App() result = wx.MessageBox("This application requires a version of wxPython " "greater than or equal to %s, but a matching version " "was not found.\n\n" "You currently have these version(s) installed:\n%s\n\n" "Would you like to download a new version of wxPython?\n" % (minVersion, versions), "wxPython Upgrade Needed", style=wx.YES_NO) if result == wx.YES: webbrowser.open(UPDATE_URL) app.MainLoop() sys.exit() sys.path.insert(0, bestMatch.pathname) # q.v. Bug #1409256 path64 = re.sub('/lib/','/lib64/',bestMatch.pathname) if os.path.isdir(path64): sys.path.insert(0, path64) global _selected _selected = bestMatch
Check if there is a version of wxPython installed that matches one of the versions given. Returns True if so, False if not. This can be used to determine if calling `select` will succeed or not. :param versions: Same as in `select`, either a string or a list of strings specifying the version(s) to check for. :param optionsRequired: Same as in `select`.
def checkInstalled(versions, optionsRequired=False): """ Check if there is a version of wxPython installed that matches one of the versions given. Returns True if so, False if not. This can be used to determine if calling `select` will succeed or not. :param versions: Same as in `select`, either a string or a list of strings specifying the version(s) to check for. :param optionsRequired: Same as in `select`. """ if type(versions) == str: versions = [versions] installed = _find_installed() bestMatch = _get_best_match(installed, versions, optionsRequired) return bestMatch is not None
Returns a list of strings representing the installed wxPython versions that are found on the system.
def getInstalled(): """ Returns a list of strings representing the installed wxPython versions that are found on the system. """ installed = _find_installed() return [os.path.basename(p.pathname)[3:] for p in installed]
called on menu selection
def menu_callback(m): '''called on menu selection''' if m.returnkey.startswith('# '): cmd = m.returnkey[2:] if m.handler is not None: if m.handler_result is None: return cmd += m.handler_result process_stdin(cmd) elif m.returnkey == 'menuSettings': wxsettings.WXSettings(mestate.settings) elif m.returnkey.startswith("mode-"): idx = int(m.returnkey[5:]) mestate.flightmode_selections[idx] = m.IsChecked() elif m.returnkey.startswith("loadLog"): print("File: " + m.returnkey[8:]) elif m.returnkey == 'quit': mestate.console.close() mestate.exit = True print("Exited. Press Enter to continue.") sys.exit(0) else: print('Unknown menu selection: %s' % m.returnkey)
construct flightmode menu
def flightmode_menu(): '''construct flightmode menu''' global flightmodes ret = [] idx = 0 for (mode,t1,t2) in flightmodes: modestr = "%s %us" % (mode, (t2-t1)) ret.append(MPMenuCheckbox(modestr, modestr, 'mode-%u' % idx)) idx += 1 mestate.flightmode_selections.append(False) return ret
setup console menus
def setup_menus(): '''setup console menus''' global TopMenu TopMenu.add(MPMenuSubMenu('Display', items=[MPMenuItem('Map', 'Map', '# map'), MPMenuItem('Save Graph', 'Save', '# save'), MPMenuItem('Reload Graphs', 'Reload', '# reload'), MPMenuItem('FFT', 'FFT', '# fft')])) TopMenu.add(graph_menus()) TopMenu.add(MPMenuSubMenu('FlightMode', items=flightmode_menu())) mestate.console.set_menu(TopMenu, menu_callback)
load graphs from mavgraphs.xml
def load_graphs(): '''load graphs from mavgraphs.xml''' mestate.graphs = [] gfiles = ['mavgraphs.xml'] if 'HOME' in os.environ: for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")): for filename in filenames: if filename.lower().endswith('.xml'): gfiles.append(os.path.join(dirname, filename)) elif 'LOCALAPPDATA' in os.environ: for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['LOCALAPPDATA'], "MAVProxy")): for filename in filenames: if filename.lower().endswith('.xml'): gfiles.append(os.path.join(dirname, filename)) for file in gfiles: if not os.path.exists(file): continue graphs = load_graph_xml(open(file).read(), file) if graphs: mestate.graphs.extend(graphs) mestate.console.writeln("Loaded %s" % file) # also load the built in graphs try: dlist = pkg_resources.resource_listdir("MAVProxy", "tools/graphs") for f in dlist: raw = pkg_resources.resource_stream("MAVProxy", "tools/graphs/%s" % f).read() graphs = load_graph_xml(raw, None) if graphs: mestate.graphs.extend(graphs) mestate.console.writeln("Loaded %s" % f) except Exception: #we're in a Windows exe, where pkg_resources doesn't work import pkgutil for f in ["ekf3Graphs.xml", "ekfGraphs.xml", "mavgraphs.xml", "mavgraphs2.xml"]: raw = pkgutil.get_data( 'MAVProxy', 'tools//graphs//' + f) graphs = load_graph_xml(raw, None) if graphs: mestate.graphs.extend(graphs) mestate.console.writeln("Loaded %s" % f) mestate.graphs = sorted(mestate.graphs, key=lambda g: g.name)
graph command
def cmd_graph(args): '''graph command''' usage = "usage: graph <FIELD...>" if len(args) < 1: print(usage) return if args[0][0] == ':': i = int(args[0][1:]) g = mestate.graphs[i] expression = g.expression args = expression.split() mestate.console.write("Added graph: %s\n" % g.name) if g.description: mestate.console.write("%s\n" % g.description, fg='blue') mestate.rl.add_history("graph %s" % ' '.join(expression.split())) mestate.last_graph = g else: expression = ' '.join(args) mestate.last_graph = GraphDefinition(mestate.settings.title, expression, '', [expression], None) grui.append(Graph_UI(mestate)) grui[-1].display_graph(mestate.last_graph, flightmode_colours()) global last_xlim if last_xlim is not None and mestate.settings.sync_xzoom: #print("initial: ", last_xlim) grui[-1].set_xlim(last_xlim)
return mapping of flight mode to colours
def flightmode_colours(): '''return mapping of flight mode to colours''' from MAVProxy.modules.lib.grapher import flightmode_colours mapping = {} idx = 0 for (mode,t0,t1) in flightmodes: if not mode in mapping: mapping[mode] = flightmode_colours[idx] idx += 1 if idx >= len(flightmode_colours): idx = 0 return mapping
map command
def cmd_map(args): '''map command''' import mavflightview #mestate.mlog.reduce_by_flightmodes(mestate.flightmode_selections) #setup and process the map options = mavflightview.mavflightview_options() options.condition = mestate.settings.condition options._flightmodes = mestate.mlog._flightmodes options.show_flightmode_legend = mestate.settings.show_flightmode if len(args) > 0: options.types = ','.join(args) [path, wp, fen, used_flightmodes, mav_type] = mavflightview.mavflightview_mav(mestate.mlog, options, mestate.flightmode_selections) child = multiproc.Process(target=mavflightview.mavflightview_show, args=[path, wp, fen, used_flightmodes, mav_type, options]) child.start() mestate.mlog.rewind()
display fft from log
def cmd_fft(args): '''display fft from log''' from MAVProxy.modules.lib import mav_fft if len(args) > 0: condition = args[0] else: condition = None child = multiproc.Process(target=mav_fft.mavfft_display, args=[mestate.filename,condition]) child.start()
save a graph as XML
def save_graph(graphdef): '''save a graph as XML''' if graphdef.filename is None: if 'HOME' in os.environ: dname = os.path.join(os.environ['HOME'], '.mavproxy') if os.path.exists(dname): mp_util.mkdir_p(dname) graphdef.filename = os.path.join(dname, 'mavgraphs.xml') elif 'LOCALAPPDATA' in os.environ: dname = os.path.join(os.environ['LOCALAPPDATA'], 'MAVProxy') if os.path.exists(dname): mp_util.mkdir_p(dname) graphdef.filename = os.path.join(dname, 'mavgraphs.xml') else: graphdef.filename = 'mavgraphs.xml' if graphdef.filename is None: print("No file to save graph to") return try: graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True) except Exception: graphs = [] found_name = False for i in range(len(graphs)): if graphs[i].name == graphdef.name: graphs[i] = graphdef found_name = True break if not found_name: graphs.append(graphdef) pipe_console_input.send("Saving %u graphs to %s" % (len(graphs), graphdef.filename)) f = open(graphdef.filename, "w") f.write("<graphs>\n\n") for g in graphs: f.write(" <graph name='%s'>\n" % g.name.strip()) if g.description is None: g.description = '' f.write(" <description>%s</description>\n" % g.description.strip()) for e in g.expressions: f.write(" <expression>%s</expression>\n" % e.strip()) f.write(" </graph>\n\n") f.write("</graphs>\n") f.close()
callback from save thread
def save_callback(operation, graphdef): '''callback from save thread''' if operation == 'test': for e in graphdef.expressions: if expression_ok(e, msgs): graphdef.expression = e pipe_graph_input.send('graph ' + graphdef.expression) return pipe_console_input.send('Invalid graph expressions') return if operation == 'save': save_graph(graphdef)
process for saving a graph
def save_process(MAVExpLastGraph, child_pipe_console_input, child_pipe_graph_input, statusMsgs): '''process for saving a graph''' from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx from MAVProxy.modules.lib.wxgrapheditor import GraphDialog #This pipe is used to send text to the console global pipe_console_input pipe_console_input = child_pipe_console_input #This pipe is used to send graph commands global pipe_graph_input pipe_graph_input = child_pipe_graph_input #The valid expression messages, required to #validate the expression in the dialog box global msgs msgs = statusMsgs app = wx.App(False) if MAVExpLastGraph.description is None: MAVExpLastGraph.description = '' frame = GraphDialog('Graph Editor', MAVExpLastGraph, save_callback) frame.ShowModal() frame.Destroy()
save a graph
def cmd_save(args): '''save a graph''' child = multiproc.Process(target=save_process, args=[mestate.last_graph, mestate.child_pipe_send_console, mestate.child_pipe_send_graph, mestate.status.msgs]) child.start()
show messages
def cmd_messages(args): '''show messages''' if len(args) > 0: wildcard = args[0] if wildcard.find('*') == -1 and wildcard.find('?') == -1: wildcard = "*" + wildcard + "*" else: wildcard = '*' mestate.mlog.rewind() types = set(['MSG','STATUSTEXT']) while True: m = mestate.mlog.recv_match(type=types, condition=mestate.settings.condition) if m is None: break if m.get_type() == 'MSG': mstr = m.Message else: mstr = m.text if fnmatch.fnmatch(mstr.upper(), wildcard.upper()): tstr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(m._timestamp)) print("%s %s" % (tstr, mstr)) mestate.mlog.rewind()
show parameters
def cmd_devid(args): '''show parameters''' params = mestate.mlog.params k = sorted(params.keys()) for p in k: if p.startswith('COMPASS_DEV_ID'): mp_util.decode_devid(params[p], p) if p.startswith('INS_') and p.endswith('_ID'): mp_util.decode_devid(params[p], p)
callback from menu to load a log file
def cmd_loadfile(args): '''callback from menu to load a log file''' if len(args) != 1: fileargs = " ".join(args) else: fileargs = args[0] if not os.path.exists(fileargs): print("Error loading file ", fileargs); return if os.name == 'nt': #convert slashes in Windows fileargs = fileargs.replace("\\", "/") loadfile(fileargs.strip('"'))
load a log file (path given by arg)
def loadfile(args): '''load a log file (path given by arg)''' mestate.console.write("Loading %s...\n" % args) t0 = time.time() mlog = mavutil.mavlink_connection(args, notimestamps=False, zero_time_base=False, progress_callback=progress_bar) mestate.filename = args mestate.mlog = mlog mestate.status.msgs = mlog.messages t1 = time.time() mestate.console.write("\ndone (%u messages in %.1fs)\n" % (mestate.mlog._count, t1-t0)) global flightmodes flightmodes = mlog.flightmode_list() load_graphs() setup_menus()
handle commands from user
def process_stdin(line): '''handle commands from user''' if line is None: sys.exit(0) line = line.strip() if not line: return args = shlex.split(line) cmd = args[0] if cmd == 'help': k = command_map.keys() k.sort() for cmd in k: (fn, help) = command_map[cmd] print("%-15s : %s" % (cmd, help)) return if cmd == 'exit': mestate.exit = True return if not cmd in command_map: print("Unknown command '%s'" % line) return (fn, help) = command_map[cmd] try: fn(args[1:]) except Exception as e: print("ERROR in command %s: %s" % (args[1:], str(e)))
wait for user input
def input_loop(): '''wait for user input''' while mestate.exit != True: try: if mestate.exit != True: line = input(mestate.rl.prompt) except EOFError: mestate.exit = True sys.exit(1) mestate.input_queue.put(line)
main processing loop, display graphs and maps
def main_loop(): '''main processing loop, display graphs and maps''' global grui, last_xlim while True: if mestate is None or mestate.exit: return while not mestate.input_queue.empty(): line = mestate.input_queue.get() cmds = line.split(';') for c in cmds: process_stdin(c) for i in range(0, len(grui)): xlim = grui[i].check_xlim_change() if xlim is not None and mestate.settings.sync_xzoom: remlist = [] for j in range(0, len(grui)): #print("set_xlim: ", j, xlim) if not grui[j].set_xlim(xlim): remlist.append(j) last_xlim = xlim if len(remlist) > 0: # remove stale graphs new_grui = [] for j in range(0, len(grui)): if j not in remlist: new_grui.append(grui[j]) grui = new_grui break time.sleep(0.1)
watch for piped data from save dialog
def pipeRecvConsole(self): '''watch for piped data from save dialog''' try: while True: console_msg = self.parent_pipe_recv_console.recv() if console_msg is not None: self.console.writeln(console_msg) time.sleep(0.1) except EOFError: pass
watch for piped data from save dialog
def pipeRecvGraph(self): '''watch for piped data from save dialog''' try: while True: graph_rec = self.parent_pipe_recv_graph.recv() if graph_rec is not None: mestate.input_queue.put(graph_rec) time.sleep(0.1) except EOFError: pass
handle a mavlink packet
def mavlink_packet(self, m): '''handle a mavlink packet''' mtype = m.get_type() if mtype == "GLOBAL_POSITION_INT": for cam in self.camera_list: cam.boSet_GPS(m) if mtype == "ATTITUDE": for cam in self.camera_list: cam.boSet_Attitude(m) if mtype == "CAMERA_STATUS": print ("Got Message camera_status") if mtype == "CAMERA_FEEDBACK": print ("Got Message camera_feedback") '''self.__vCmdCamTrigger(m)''' if mtype == "COMMAND_LONG": if m.command == mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONFIGURE: print ("Got Message Digicam_configure") self.__vDecodeDIGICAMConfigure(m) elif m.command == mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL: print ("Got Message Digicam_control") self.__vDecodeDIGICAMControl(m)
called in idle time
def idle_task(self): '''called in idle time''' try: datagram = self.port.recvfrom(self.BUFFER_SIZE) data = json.loads(datagram[0]) except socket.error as e: if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]: return raise for key in data.keys(): self.data[key] = data[key] try: self.master.mav.gps_input_send( self.data['time_usec'], self.data['gps_id'], self.data['ignore_flags'], self.data['time_week_ms'], self.data['time_week'], self.data['fix_type'], self.data['lat'], self.data['lon'], self.data['alt'], self.data['hdop'], self.data['vdop'], self.data['vn'], self.data['ve'], self.data['vd'], self.data['speed_accuracy'], self.data['horiz_accuracy'], self.data['vert_accuracy'], self.data['satellites_visible']) except Exception as e: print("GPS Input Failed:", e)
handle port selection
def cmd_port(self, args): 'handle port selection' if len(args) != 1: print("Usage: port <number>") return self.port.close() self.portnum = int(args[0]) self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.port.bind((self.ip, self.portnum)) self.port.setblocking(0) mavutil.set_close_on_exec(self.port.fileno()) print("Listening for GPS INPUT packets on UDP://%s:%s" % (self.ip, self.portnum))
substitute variables in a string
def substitute(self, text, subvars={}, checkmissing=None): '''substitute variables in a string''' if checkmissing is None: checkmissing = self.checkmissing while True: idx = text.find(self.start_var_token) if idx == -1: return text endidx = text[idx:].find(self.end_var_token) if endidx == -1: raise MAVSubstituteError('missing end of variable: %s' % text[idx:idx+10]) varname = text[idx+2:idx+endidx] fullvar = varname # allow default value after a : def_value = None colon = varname.find(':') if colon != -1: def_value = varname[colon+1:] varname = varname[:colon] if varname in subvars: value = subvars[varname] elif def_value is not None: value = def_value elif checkmissing: raise MAVSubstituteError("unknown variable in '%s%s%s'" % ( self.start_var_token, varname, self.end_var_token)) else: return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, checkmissing=False) text = text.replace("%s%s%s" % (self.start_var_token, fullvar, self.end_var_token), str(value)) return text
Actuate on the vehicle through a script. The script is a sequence of commands. Each command is a sequence with the first element as the command name and the remaining values as parameters. The script is executed asynchronously by a timer with a period of 0.1 seconds. At each timer tick, the next command is executed if it's ready for execution. If a command name starts with '.', then the remaining characters are a method name and the arguments are passed to the method call. For example, the command ('.SetEuler', 0, math.pi / 2, 0) sets the vehicle nose up. The methods available for that type of command are in the class property script_available_methods. The other possible commands are: - wait(sec): wait for sec seconds. Because of the timer period, some inaccuracy is expected depending on the value of sec. - restart: go back to the first command. Example:: vehicle.RunScript(( ('.SetEuler', 0, 0, 0), # Set vehicle level ('wait', 2), # Wait for 2 seconds # Rotate continuously on the x-axis at a rate of 90 degrees per # second ('.SetAngvel', (1, 0, 0), math.pi / 2), ('wait', 5), # Let the vehicle rotating for 5 seconds ('restart',), # Restart the script ))
def RunScript(self, script): ''' Actuate on the vehicle through a script. The script is a sequence of commands. Each command is a sequence with the first element as the command name and the remaining values as parameters. The script is executed asynchronously by a timer with a period of 0.1 seconds. At each timer tick, the next command is executed if it's ready for execution. If a command name starts with '.', then the remaining characters are a method name and the arguments are passed to the method call. For example, the command ('.SetEuler', 0, math.pi / 2, 0) sets the vehicle nose up. The methods available for that type of command are in the class property script_available_methods. The other possible commands are: - wait(sec): wait for sec seconds. Because of the timer period, some inaccuracy is expected depending on the value of sec. - restart: go back to the first command. Example:: vehicle.RunScript(( ('.SetEuler', 0, 0, 0), # Set vehicle level ('wait', 2), # Wait for 2 seconds # Rotate continuously on the x-axis at a rate of 90 degrees per # second ('.SetAngvel', (1, 0, 0), math.pi / 2), ('wait', 5), # Let the vehicle rotating for 5 seconds ('restart',), # Restart the script )) ''' self.script = script self.script_command = 0 self.script_command_start_time = 0 self.script_command_state = 'ready' self.script_timer.Start(100) self.script_wait_time = 0
called from main select loop in mavproxy when the pppd child sends us some data
def ppp_read(self, ppp_fd): '''called from main select loop in mavproxy when the pppd child sends us some data''' buf = os.read(ppp_fd, 100) if len(buf) == 0: # EOF on the child fd self.stop_ppp_link() return print("ppp packet len=%u" % len(buf)) master = self.master master.mav.ppp_send(len(buf), buf)
startup the link
def start_ppp_link(self): '''startup the link''' cmd = ['pppd'] cmd.extend(self.command) (self.pid, self.ppp_fd) = pty.fork() if self.pid == 0: os.execvp("pppd", cmd) raise RuntimeError("pppd exited") if self.ppp_fd == -1: print("Failed to create link fd") return # ensure fd is non-blocking fcntl.fcntl(self.ppp_fd, fcntl.F_SETFL, fcntl.fcntl(self.ppp_fd, fcntl.F_GETFL) | os.O_NONBLOCK) self.byte_count = 0 self.packet_count = 0 # ask mavproxy to add us to the select loop self.mpself.select_extra[self.ppp_fd] = (self.ppp_read, self.ppp_fd)
stop the link
def stop_ppp_link(self): '''stop the link''' if self.ppp_fd == -1: return try: self.mpself.select_extra.pop(self.ppp_fd) os.close(self.ppp_fd) os.waitpid(self.pid, 0) except Exception: pass self.pid = -1 self.ppp_fd = -1 print("stopped ppp link")
set ppp parameters and start link
def cmd_ppp(self, args): '''set ppp parameters and start link''' usage = "ppp <command|start|stop>" if len(args) == 0: print(usage) return if args[0] == "command": if len(args) == 1: print("ppp.command=%s" % " ".join(self.command)) else: self.command = args[1:] elif args[0] == "start": self.start_ppp_link() elif args[0] == "stop": self.stop_ppp_link() elif args[0] == "status": self.console.writeln("%u packets %u bytes" % (self.packet_count, self.byte_count))
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if m.get_type() == 'PPP' and self.ppp_fd != -1: print("got ppp mavlink pkt len=%u" % m.length) os.write(self.ppp_fd, m.data[:m.length])
Find a list of modules matching a wildcard pattern
def module_matching(self, name): '''Find a list of modules matching a wildcard pattern''' import fnmatch ret = [] for mname in self.mpstate.public_modules.keys(): if fnmatch.fnmatch(mname, name): ret.append(self.mpstate.public_modules[mname]) return ret
get time, using ATTITUDE.time_boot_ms if in SITL with SIM_SPEEDUP != 1
def get_time(self): '''get time, using ATTITUDE.time_boot_ms if in SITL with SIM_SPEEDUP != 1''' systime = time.time() - self.mpstate.start_time_s if not self.mpstate.is_sitl: return systime try: speedup = int(self.get_mav_param('SIM_SPEEDUP',1)) except Exception: return systime if speedup != 1: return self.mpstate.attitude_time_s return systime
return a distance as a string
def dist_string(self, val_meters): '''return a distance as a string''' if self.settings.dist_unit == 'nm': return "%.1fnm" % (val_meters * 0.000539957) if self.settings.dist_unit == 'miles': return "%.1fmiles" % (val_meters * 0.000621371) return "%um" % val_meters
return a speed in configured units
def speed_convert_units(self, val_ms): '''return a speed in configured units''' if self.settings.speed_unit == 'knots': return val_ms * 1.94384 elif self.settings.speed_unit == 'mph': return val_ms * 2.23694 return val_ms
set prompt for command line
def set_prompt(self, prompt): '''set prompt for command line''' if prompt and self.settings.vehicle_name: # add in optional vehicle name prompt = self.settings.vehicle_name + ':' + prompt self.mpstate.rl.set_prompt(prompt)
return a link label as a string
def link_label(link): '''return a link label as a string''' if hasattr(link, 'label'): label = link.label else: label = str(link.linknum+1) return label
see if a msg is from our primary vehicle
def is_primary_vehicle(self, msg): '''see if a msg is from our primary vehicle''' sysid = msg.get_srcSystem() if self.target_system == 0 or self.target_system == sysid: return True return False
allocate a colour to be used for a flight mode
def next_flightmode_colour(self): '''allocate a colour to be used for a flight mode''' if self.flightmode_colour_index > len(flightmode_colours): print("Out of colours; reusing") self.flightmode_colour_index = 0 ret = flightmode_colours[self.flightmode_colour_index] self.flightmode_colour_index += 1 return ret
return colour to be used for rendering a flight mode background
def flightmode_colour(self, flightmode): '''return colour to be used for rendering a flight mode background''' if flightmode not in self.flightmode_colourmap: self.flightmode_colourmap[flightmode] = self.next_flightmode_colour() return self.flightmode_colourmap[flightmode]
setup plotting ticks on x axis
def setup_xrange(self, xrange): '''setup plotting ticks on x axis''' if self.xaxis: return xrange *= 24 * 60 * 60 interval = 1 intervals = [ 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600, 900, 1800, 3600, 7200, 5*3600, 10*3600, 24*3600 ] for interval in intervals: if xrange / interval < 12: break self.locator = matplotlib.dates.SecondLocator(interval=interval) self.ax1.xaxis.set_major_locator(self.locator)
called when x limits are changed
def xlim_changed(self, axsubplot): '''called when x limits are changed''' xrange = axsubplot.get_xbound() xlim = axsubplot.get_xlim() self.setup_xrange(xrange[1] - xrange[0]) if self.draw_events == 0: # ignore limit change before first draw event return if self.xlim_pipe is not None and axsubplot == self.ax1 and xlim != self.xlim: self.xlim = xlim #print('send', self.graph_num, xlim) self.xlim_pipe[1].send(xlim)
plot a set of graphs using date for x axis
def plotit(self, x, y, fields, colors=[], title=None): '''plot a set of graphs using date for x axis''' pylab.ion() self.fig = pylab.figure(num=1, figsize=(12,6)) self.ax1 = self.fig.gca() ax2 = None for i in range(0, len(fields)): if len(x[i]) == 0: continue if self.lowest_x is None or x[i][0] < self.lowest_x: self.lowest_x = x[i][0] if self.highest_x is None or x[i][-1] > self.highest_x: self.highest_x = x[i][-1] if self.highest_x is None or self.lowest_x is None: return self.formatter = matplotlib.dates.DateFormatter('%H:%M:%S') if not self.xaxis: self.setup_xrange(self.highest_x - self.lowest_x) self.ax1.xaxis.set_major_formatter(self.formatter) self.ax1.callbacks.connect('xlim_changed', self.xlim_changed) self.fig.canvas.mpl_connect('draw_event', self.draw_event) empty = True ax1_labels = [] ax2_labels = [] for i in range(0, len(fields)): if len(x[i]) == 0: #print("Failed to find any values for field %s" % fields[i]) continue if i < len(colors): color = colors[i] else: color = 'red' (tz, tzdst) = time.tzname if self.axes[i] == 2: if ax2 is None: ax2 = self.ax1.twinx() ax2.format_coord = self.make_format(ax2, self.ax1) ax = ax2 if not self.xaxis: ax2.xaxis.set_major_locator(self.locator) ax2.xaxis.set_major_formatter(self.formatter) label = fields[i] if label.endswith(":2"): label = label[:-2] ax2_labels.append(label) else: ax1_labels.append(fields[i]) ax = self.ax1 if self.xaxis: if self.marker is not None: marker = self.marker else: marker = '+' if self.linestyle is not None: linestyle = self.linestyle else: linestyle = 'None' ax.plot(x[i], y[i], color=color, label=fields[i], linestyle=linestyle, marker=marker) else: if self.marker is not None: marker = self.marker else: marker = 'None' if self.linestyle is not None: linestyle = self.linestyle else: linestyle = '-' if len(y[i]) > 0 and isinstance(y[i][0],str): # assume this is a piece of text to be rendered at a point in time last_text_time = -1 last_text = None for n in range(0, len(x[i])): this_text_time = round(x[i][n], 6) this_text = y[i][n] if last_text is None: last_text = "[y" + this_text + "]" last_text_time = this_text_time elif this_text_time == last_text_time: last_text += ("[x" + this_text + "]") else: ax.text(last_text_time, 10, last_text, rotation=90, alpha=0.3, verticalalignment='baseline') last_text = this_text last_text_time = this_text_time if last_text is not None: ax.text(last_text_time, 10, last_text, rotation=90, alpha=0.3, verticalalignment='baseline') else: ax.plot_date(x[i], y[i], color=color, label=fields[i], linestyle=linestyle, marker=marker, tz=None) empty = False if self.show_flightmode: alpha = 0.3 xlim = self.ax1.get_xlim() for i in range(len(self.flightmode_list)): (mode_name,t0,t1) = self.flightmode_list[i] c = self.flightmode_colour(mode_name) tday0 = self.timestamp_to_days(t0) tday1 = self.timestamp_to_days(t1) if tday0 > xlim[1] or tday1 < xlim[0]: continue tday0 = max(tday0, xlim[0]) tday1 = min(tday1, xlim[1]) self.ax1.axvspan(tday0, tday1, fc=c, ec=edge_colour, alpha=alpha) self.modes_plotted[mode_name] = (c, alpha) if empty: print("No data to graph") return if title is not None: pylab.title(title) if self.show_flightmode: mode_patches = [] for mode in self.modes_plotted.keys(): (color, alpha) = self.modes_plotted[mode] mode_patches.append(matplotlib.patches.Patch(color=color, label=mode, alpha=alpha*1.5)) labels = [patch.get_label() for patch in mode_patches] if ax1_labels != []: patches_legend = matplotlib.pyplot.legend(mode_patches, labels, loc=self.legend_flightmode) self.fig.gca().add_artist(patches_legend) else: pylab.legend(mode_patches, labels) if ax1_labels != []: self.ax1.legend(ax1_labels,loc=self.legend) if ax2_labels != []: ax2.legend(ax2_labels,loc=self.legend2)
add some data
def add_data(self, t, msg, vars): '''add some data''' mtype = msg.get_type() for i in range(0, len(self.fields)): if mtype not in self.field_types[i]: continue f = self.fields[i] simple = self.simple_field[i] if simple is not None: v = getattr(vars[simple[0]], simple[1]) else: v = mavutil.evaluate_expression(f, vars) if v is None: continue if self.xaxis is None: xv = t else: xv = mavutil.evaluate_expression(self.xaxis, vars) if xv is None: continue try: v_f = float(v) xv_f = float(xv) except Exception: continue self.y[i].append(v_f) self.x[i].append(xv_f)
convert log timestamp to days
def timestamp_to_days(self, timestamp): '''convert log timestamp to days''' if self.tday_base is None: try: self.tday_base = matplotlib.dates.date2num(datetime.datetime.fromtimestamp(timestamp+self.timeshift)) self.tday_basetime = timestamp except ValueError: # this can happen if the log is corrupt # ValueError: year is out of range return 0 sec_to_days = 1.0 / (60*60*24) return self.tday_base + (timestamp - self.tday_basetime) * sec_to_days
process one file
def process_mav(self, mlog, flightmode_selections): '''process one file''' self.vars = {} idx = 0 all_false = True for s in flightmode_selections: if s: all_false = False # pre-calc right/left axes self.num_fields = len(self.fields) for i in range(0, self.num_fields): f = self.fields[i] if f.endswith(":2"): self.axes[i] = 2 f = f[:-2] if f.endswith(":1"): self.first_only[i] = True f = f[:-2] self.fields[i] = f # see which fields are simple self.simple_field = [] for i in range(0, self.num_fields): f = self.fields[i] m = re.match('^([A-Z][A-Z0-9_]*)[.]([A-Za-z_][A-Za-z0-9_]*)$', f) if m is None: self.simple_field.append(None) else: self.simple_field.append((m.group(1),m.group(2))) if len(self.flightmode_list) > 0: # prime the timestamp conversion self.timestamp_to_days(self.flightmode_list[0][1]) while True: msg = mlog.recv_match(type=self.msg_types) if msg is None: break if msg.get_type() not in self.msg_types: continue if self.condition: if not mavutil.evaluate_condition(self.condition, mlog.messages): continue tdays = self.timestamp_to_days(msg._timestamp) if all_false or len(flightmode_selections) == 0: self.add_data(tdays, msg, mlog.messages) else: if idx < len(self.flightmode_list) and msg._timestamp >= self.flightmode_list[idx][2]: idx += 1 elif (idx < len(flightmode_selections) and flightmode_selections[idx]): self.add_data(tdays, msg, mlog.messages)
handle xlim change requests from queue
def xlim_change_check(self, idx): '''handle xlim change requests from queue''' if not self.xlim_pipe[1].poll(): return xlim = self.xlim_pipe[1].recv() if xlim is None: return #print("recv: ", self.graph_num, xlim) if self.ax1 is not None and xlim != self.xlim: self.xlim = xlim self.fig.canvas.toolbar.push_current() #print("setting: ", self.graph_num, xlim) self.ax1.set_xlim(xlim) # trigger the timer, this allows us to setup a v slow animation, # which saves a lot of CPU self.ani.event_source._on_timer()
process and display graph
def process(self, flightmode_selections, _flightmodes, block=True): '''process and display graph''' self.msg_types = set() self.multiplier = [] self.field_types = [] self.xlim = None self.flightmode_list = _flightmodes # work out msg types we are interested in self.x = [] self.y = [] self.modes = [] self.axes = [] self.first_only = [] re_caps = re.compile('[A-Z_][A-Z0-9_]+') for f in self.fields: caps = set(re.findall(re_caps, f)) self.msg_types = self.msg_types.union(caps) self.field_types.append(caps) self.y.append([]) self.x.append([]) self.axes.append(1) self.first_only.append(False) timeshift = self.timeshift for fi in range(0, len(self.mav_list)): mlog = self.mav_list[fi] self.process_mav(mlog, flightmode_selections)
show graph
def show(self, lenmavlist, block=True, xlim_pipe=None): '''show graph''' if xlim_pipe is not None: xlim_pipe[0].close() self.xlim_pipe = xlim_pipe if self.labels is not None: labels = self.labels.split(',') if len(labels) != len(fields)*lenmavlist: print("Number of labels (%u) must match number of fields (%u)" % ( len(labels), len(fields)*lenmavlist)) return else: labels = None for fi in range(0, lenmavlist): timeshift = 0 for i in range(0, len(self.x)): if self.first_only[i] and fi != 0: self.x[i] = [] self.y[i] = [] if labels: lab = labels[fi*len(self.fields):(fi+1)*len(self.fields)] else: lab = self.fields[:] if self.multi: col = colors[:] else: col = colors[fi*len(self.fields):] self.plotit(self.x, self.y, lab, colors=col, title=self.title) for i in range(0, len(self.x)): self.x[i] = [] self.y[i] = [] if self.xlim_pipe is not None: import matplotlib.animation self.ani = matplotlib.animation.FuncAnimation(self.fig, self.xlim_change_check, frames=10, interval=20000, repeat=True, blit=False) threading.Timer(0.1, self.xlim_timer).start() pylab.draw() pylab.show(block=block)
control behaviour of the module
def cmd_ublox(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.cmd_status()) elif args[0] == "set": self.ublox_settings.command(args[1:]) elif args[0] == "reset": self.cmd_ublox_reset(args[1:]) elif args[0] == "mga": self.cmd_ublox_mga(args[1:]) else: print(self.usage())
attempts to cold-reboot (factory-reboot) gps module
def cmd_ublox_reset(self, args): '''attempts to cold-reboot (factory-reboot) gps module''' print("Sending uBlox reset") msg = struct.pack("<HBB", 0xFFFF, 0x0, 0) self.master.mav.gps_inject_data_send( self.target_system, self.target_component, len(msg), bytearray(msg.ljust(110, '\0')))
called rapidly by mavproxy
def idle_task(self): '''called rapidly by mavproxy''' if self.fix_type >= 3: # don't do anything if we have a fix return if self.mpstate.status.armed: # do not upload data over telemetry link if we are armed # perhaps we should just limit rate instead. return now = time.time() if self.auto: if now-self.last_auto > 2: self.last_auto = now print("Doing auto things") if self.idle_upload_mga_dbd(): self.auto_status = "DBD uploaded" if not self.idle_upload_mga_online(): self.auto_status = "Online uploaded" if not self.idle_upload_mga_offline(): self.auto_status = "Offline uploaded"
handle mavlink packets
def mavlink_packet(self, m): '''handle mavlink packets''' # can't use status.msgs as we need this filtered to our target system if (self.settings.target_system != 0 and self.settings.target_system != m.get_srcSystem()): return if m.get_type() == 'GPS_RAW_INT': self.fix_type = m.fix_type if m.get_type() == 'SYSTEM_TIME': self.time_boot_ms = m.time_boot_ms
reboot autopilot
def cmd_reboot(self, args): '''reboot autopilot''' if len(args) > 0 and args[0] == 'bootloader': self.master.reboot_autopilot(True) else: self.master.reboot_autopilot()
lockup autopilot for watchdog testing
def cmd_lockup_autopilot(self, args): '''lockup autopilot for watchdog testing''' if len(args) > 0 and args[0] == 'IREALLYMEANIT': print("Sending lockup command") self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, 42, 24, 71, 93, 0, 0, 0) else: print("Invalid lockup command")
get home position
def cmd_gethome(self, args): '''get home position''' self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_GET_HOME_POSITION, 0, 0, 0, 0, 0, 0, 0, 0)
send LED pattern as override
def cmd_led(self, args): '''send LED pattern as override''' if len(args) < 3: print("Usage: led RED GREEN BLUE <RATE>") return pattern = [0] * 24 pattern[0] = int(args[0]) pattern[1] = int(args[1]) pattern[2] = int(args[2]) if len(args) == 4: plen = 4 pattern[3] = int(args[3]) else: plen = 3 self.master.mav.led_control_send(self.settings.target_system, self.settings.target_component, 0, 0, plen, pattern)
send LED pattern as override, using OreoLED conventions
def cmd_oreoled(self, args): '''send LED pattern as override, using OreoLED conventions''' if len(args) < 4: print("Usage: oreoled LEDNUM RED GREEN BLUE <RATE>") return lednum = int(args[0]) pattern = [0] * 24 pattern[0] = ord('R') pattern[1] = ord('G') pattern[2] = ord('B') pattern[3] = ord('0') pattern[4] = 0 pattern[5] = int(args[1]) pattern[6] = int(args[2]) pattern[7] = int(args[3]) self.master.mav.led_control_send(self.settings.target_system, self.settings.target_component, lednum, 255, 8, pattern)
flash bootloader
def cmd_flashbootloader(self, args): '''flash bootloader''' self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_FLASH_BOOTLOADER, 0, 0, 0, 0, 0, 290876, 0, 0)
send PLAY_TUNE message
def cmd_playtune(self, args): '''send PLAY_TUNE message''' if len(args) < 1: print("Usage: playtune TUNE") return tune = args[0] str1 = tune[0:30] str2 = tune[30:] if sys.version_info.major >= 3 and not isinstance(str1, bytes): str1 = bytes(str1, "ascii") if sys.version_info.major >= 3 and not isinstance(str2, bytes): str2 = bytes(str2, "ascii") self.master.mav.play_tune_send(self.settings.target_system, self.settings.target_component, str1, str2)
decode device IDs from parameters
def cmd_devid(self, args): '''decode device IDs from parameters''' for p in self.mav_param.keys(): if p.startswith('COMPASS_DEV_ID'): mp_util.decode_devid(self.mav_param[p], p) if p.startswith('INS_') and p.endswith('_ID'): mp_util.decode_devid(self.mav_param[p], p)
add to the default popup menu
def add_menu(self, menu): '''add to the default popup menu''' from MAVProxy.modules.mavproxy_map import mp_slipmap self.default_popup.add(menu) self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))
map commands
def cmd_map(self, args): '''map commands''' from MAVProxy.modules.mavproxy_map import mp_slipmap if len(args) < 1: print("usage: map <icon|set>") elif args[0] == "icon": if len(args) < 3: print("Usage: map icon <lat> <lon> <icon>") else: lat = args[1] lon = args[2] flag = 'flag.png' if len(args) > 3: flag = args[3] + '.png' icon = self.map.icon(flag) self.map.add_object(mp_slipmap.SlipIcon('icon - %s [%u]' % (str(flag),self.icon_counter), (float(lat),float(lon)), icon, layer=3, rotation=0, follow=False)) self.icon_counter += 1 elif args[0] == "set": self.map_settings.command(args[1:]) self.map.add_object(mp_slipmap.SlipBrightness(self.map_settings.brightness)) elif args[0] == "sethome": self.cmd_set_home(args) elif args[0] == "sethomepos": self.cmd_set_homepos(args) elif args[0] == "setorigin": self.cmd_set_origin(args) elif args[0] == "setoriginpos": self.cmd_set_originpos(args) elif args[0] == "zoom": self.cmd_zoom(args) elif args[0] == "center": self.cmd_center(args) elif args[0] == "follow": self.cmd_follow(args) else: print("usage: map <icon|set>")
return a tuple describing the colour a waypoint should appear on the map
def colour_for_wp(self, wp_num): '''return a tuple describing the colour a waypoint should appear on the map''' wp = self.module('wp').wploader.wp(wp_num) command = wp.command return self._colour_for_wp_command.get(command, (0,255,0))
return the label the waypoint which should appear on the map
def label_for_waypoint(self, wp_num): '''return the label the waypoint which should appear on the map''' wp = self.module('wp').wploader.wp(wp_num) command = wp.command if command not in self._label_suffix_for_wp_command: return str(wp_num) return str(wp_num) + "(" + self._label_suffix_for_wp_command[command] + ")"
display the waypoints
def display_waypoints(self): '''display the waypoints''' from MAVProxy.modules.mavproxy_map import mp_slipmap self.mission_list = self.module('wp').wploader.view_list() polygons = self.module('wp').wploader.polygon_list() self.map.add_object(mp_slipmap.SlipClearLayer('Mission')) for i in range(len(polygons)): p = polygons[i] if len(p) > 1: items = [MPMenuItem('Set', returnkey='popupMissionSet'), MPMenuItem('WP Remove', returnkey='popupMissionRemove'), MPMenuItem('WP Move', returnkey='popupMissionMove'), MPMenuItem('Remove NoFly', returnkey='popupMissionRemoveNoFly'), ] popup = MPMenuSubMenu('Popup', items) self.map.add_object(mp_slipmap.SlipPolygon('mission %u' % i, p, layer='Mission', linewidth=2, colour=(255,255,255), arrow = self.map_settings.showdirection, popup_menu=popup)) labeled_wps = {} self.map.add_object(mp_slipmap.SlipClearLayer('LoiterCircles')) for i in range(len(self.mission_list)): next_list = self.mission_list[i] for j in range(len(next_list)): #label already printed for this wp? if (next_list[j] not in labeled_wps): label = self.label_for_waypoint(next_list[j]) colour = self.colour_for_wp(next_list[j]) self.map.add_object(mp_slipmap.SlipLabel( 'miss_cmd %u/%u' % (i,j), polygons[i][j], label, 'Mission', colour=colour)) if (self.map_settings.loitercircle and self.module('wp').wploader.wp_is_loiter(next_list[j])): wp = self.module('wp').wploader.wp(next_list[j]) if wp.command != mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT and wp.param3 != 0: # wp radius and direction is defined by the mission loiter_rad = wp.param3 elif wp.command == mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT and wp.param2 != 0: # wp radius and direction is defined by the mission loiter_rad = wp.param2 else: # wp radius and direction is defined by the parameter loiter_rad = self.get_mav_param('WP_LOITER_RAD') self.map.add_object(mp_slipmap.SlipCircle('Loiter Circle %u' % (next_list[j] + 1), 'LoiterCircles', polygons[i][j], loiter_rad, (255, 255, 255), 2, arrow = self.map_settings.showdirection)) labeled_wps[next_list[j]] = (i,j)
remove a mission nofly polygon
def remove_mission_nofly(self, key, selection_index): '''remove a mission nofly polygon''' if not self.validate_nofly(): print("NoFly invalid") return print("NoFly valid") idx = self.selection_index_to_idx(key, selection_index) wploader = self.module('wp').wploader if idx < 0 or idx >= wploader.count(): print("Invalid wp number %u" % idx) return wp = wploader.wp(idx) if wp.command != mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION: print("Not an exclusion point (%u)" % idx) return # we know the list is valid. Search for the start of the sequence to delete tmp_idx = idx while tmp_idx > 0: tmp = wploader.wp(tmp_idx-1) if (tmp.command != wp.command or tmp.param1 != wp.param1): break tmp_idx -= 1 start_idx_to_delete = idx - ((idx-tmp_idx)%int(wp.param1)) for i in range(int(start_idx_to_delete+wp.param1)-1,start_idx_to_delete-1,-1): # remove in reverse order as wploader.remove re-indexes print("Removing at %u" % i) deadun = wploader.wp(i) wploader.remove(deadun) self.module('wp').send_all_waypoints()
handle a popup menu event from the map
def handle_menu_event(self, obj): '''handle a popup menu event from the map''' menuitem = obj.menuitem if menuitem.returnkey.startswith('# '): cmd = menuitem.returnkey[2:] if menuitem.handler is not None: if menuitem.handler_result is None: return cmd += menuitem.handler_result self.mpstate.functions.process_stdin(cmd) elif menuitem.returnkey == 'popupRallyRemove': self.remove_rally(obj.selected[0].objkey) elif menuitem.returnkey == 'popupRallyMove': self.move_rally(obj.selected[0].objkey) elif menuitem.returnkey == 'popupMissionSet': self.set_mission(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'popupMissionRemoveNoFly': self.remove_mission_nofly(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'popupMissionRemove': self.remove_mission(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'popupMissionMove': self.move_mission(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'popupFenceRemove': self.remove_fencepoint(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'popupFenceMove': self.move_fencepoint(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'showPosition': self.show_position()
called when an event happens on the slipmap
def map_callback(self, obj): '''called when an event happens on the slipmap''' from MAVProxy.modules.mavproxy_map import mp_slipmap if isinstance(obj, mp_slipmap.SlipMenuEvent): self.handle_menu_event(obj) return if not isinstance(obj, mp_slipmap.SlipMouseEvent): return if obj.event.leftIsDown and self.moving_rally is not None: self.click_position = obj.latlon self.click_time = time.time() self.mpstate.functions.process_stdin("rally move %u" % self.moving_rally) self.moving_rally = None return if obj.event.rightIsDown and self.moving_rally is not None: print("Cancelled rally move") self.moving_rally = None return if obj.event.leftIsDown and self.moving_wp is not None: self.click_position = obj.latlon self.click_time = time.time() self.mpstate.functions.process_stdin("wp move %u" % self.moving_wp) self.moving_wp = None return if obj.event.leftIsDown and self.moving_fencepoint is not None: self.click_position = obj.latlon self.click_time = time.time() self.mpstate.functions.process_stdin("fence move %u" % (self.moving_fencepoint+1)) self.moving_fencepoint = None return if obj.event.rightIsDown and self.moving_wp is not None: print("Cancelled wp move") self.moving_wp = None return if obj.event.rightIsDown and self.moving_fencepoint is not None: print("Cancelled fence move") self.moving_fencepoint = None return elif obj.event.leftIsDown: if time.time() - self.click_time > 0.1: self.click_position = obj.latlon self.click_time = time.time() self.drawing_update() if self.module('misseditor') is not None: self.module('misseditor').update_map_click_position(self.click_position) if obj.event.rightIsDown: if self.draw_callback is not None: self.drawing_end() return if time.time() - self.click_time > 0.1: self.click_position = obj.latlon self.click_time = time.time()
unload module
def unload(self): '''unload module''' super(MapModule, self).unload() self.map.close() if self.instance == 1: self.mpstate.map = None self.mpstate.map_functions = {}
end line drawing
def drawing_end(self): '''end line drawing''' from MAVProxy.modules.mavproxy_map import mp_slipmap if self.draw_callback is None: return self.draw_callback(self.draw_line) self.draw_callback = None self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True)) self.map.add_object(mp_slipmap.SlipClearLayer('Drawing'))