INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
add a spin control
def add_intspin(self, setting): '''add a spin control''' tab = self.panel(setting.tab) default = setting.value (minv, maxv) = setting.range ctrl = wx.SpinCtrl(tab, -1, initial = default, min = minv, max = maxv) self._add_input(setting, ctrl, value=default)
add a floating point spin control
def add_floatspin(self, setting): '''add a floating point spin control''' from wx.lib.agw.floatspin import FloatSpin tab = self.panel(setting.tab) default = setting.value (minv, maxv) = setting.range ctrl = FloatSpin(tab, -1, value = default, min_val = minv, max_val = maxv, increment = setting.increment) if setting.format is not None: ctrl.SetFormat(setting.format) if setting.digits is not None: ctrl.SetDigits(setting.digits) self._add_input(setting, ctrl, value=default)
handle an incoming mavlink packet
def process_mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() # if you add processing for an mtype here, remember to add it # to mavlink_packet, above if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']: if (self.num_wps_expected == 0): #I haven't asked for WPs, or these messages are duplicates #of msgs I've already received. self.console.error("No waypoint load started (from Editor).") #I only clear the mission in the Editor if this was a read event elif (self.num_wps_expected == -1): self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_CLEAR_MISS_TABLE)) self.num_wps_expected = m.count self.wps_received = {} if (m.count > 0): self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_ADD_MISS_TABLE_ROWS,num_rows=m.count-1)) #write has been sent by the mission editor: elif (self.num_wps_expected > 1): if (m.count != self.num_wps_expected): self.console.error("Unepxected waypoint count from APM after write (Editor)") #since this is a write operation from the Editor there #should be no need to update number of table rows elif mtype in ['WAYPOINT', 'MISSION_ITEM']: #still expecting wps? if (len(self.wps_received) < self.num_wps_expected): #if we haven't already received this wp, write it to the GUI: if (m.seq not in self.wps_received.keys()): self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_MISS_ITEM, num=m.seq,command=m.command,param1=m.param1, param2=m.param2,param3=m.param3,param4=m.param4, lat=m.x,lon=m.y,alt=m.z,frame=m.frame)) self.wps_received[m.seq] = True
child process - this holds GUI elements
def child_task(self, q, l, gq, gl, cw_sem): '''child process - this holds GUI elements''' mp_util.child_close_fds() from MAVProxy.modules.lib import wx_processguard from ..lib.wx_loader import wx from MAVProxy.modules.mavproxy_misseditor import missionEditorFrame self.app = wx.App(False) self.app.frame = missionEditorFrame.MissionEditorFrame(parent=None,id=wx.ID_ANY) self.app.frame.set_event_queue(q) self.app.frame.set_event_queue_lock(l) self.app.frame.set_gui_event_queue(gq) self.app.frame.set_gui_event_queue_lock(gl) self.app.frame.set_close_window_semaphore(cw_sem) self.app.SetExitOnFrameDelete(True) self.app.frame.Show() # start a thread to monitor the "close window" semaphore: class CloseWindowSemaphoreWatcher(threading.Thread): def __init__(self, task, sem): threading.Thread.__init__(self) self.task = task self.sem = sem def run(self): self.sem.acquire(True) self.task.app.ExitMainLoop() watcher_thread = CloseWindowSemaphoreWatcher(self, cw_sem) watcher_thread.start() self.app.MainLoop() # tell the watcher it is OK to quit: cw_sem.release() watcher_thread.join()
close the Mission Editor window
def close(self): '''close the Mission Editor window''' self.time_to_quit = True self.close_window.release() if self.child.is_alive(): self.child.join(1) self.child.terminate() self.mavlink_message_queue_handler.join() self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_TIME_TO_QUIT)); self.event_queue_lock.release()
Create a new figure manager instance
def new_figure_manager(num, *args, **kwargs): """ Create a new figure manager instance """ if __debug__: verbose.report('backend_agg.new_figure_manager', 'debug-annoying') FigureClass = kwargs.pop('FigureClass', Figure) thisFig = FigureClass(*args, **kwargs) return new_figure_manager_given_figure(num, thisFig)
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. """ canvas = FigureCanvasAgg(figure) manager = FigureManagerBase(canvas, num) return manager
Draw the path
def draw_path(self, gc, path, transform, rgbFace=None): """ Draw the path """ nmax = rcParams['agg.path.chunksize'] # here at least for testing npts = path.vertices.shape[0] if (nmax > 100 and npts > nmax and path.should_simplify and rgbFace is None and gc.get_hatch() is None): nch = np.ceil(npts/float(nmax)) chsize = int(np.ceil(npts/nch)) i0 = np.arange(0, npts, chsize) i1 = np.zeros_like(i0) i1[:-1] = i0[1:] - 1 i1[-1] = npts for ii0, ii1 in zip(i0, i1): v = path.vertices[ii0:ii1,:] c = path.codes if c is not None: c = c[ii0:ii1] c[0] = Path.MOVETO # move to end of last chunk p = Path(v, c) self._renderer.draw_path(gc, p, transform, rgbFace) else: self._renderer.draw_path(gc, path, transform, rgbFace)
Draw the math text using matplotlib.mathtext
def draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw the math text using matplotlib.mathtext """ if __debug__: verbose.report('RendererAgg.draw_mathtext', 'debug-annoying') ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) xd = descent * np.sin(np.deg2rad(angle)) yd = descent * np.cos(np.deg2rad(angle)) x = np.round(x + ox + xd) y = np.round(y - oy + yd) self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
Render the text
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): """ Render the text """ if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying') if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) flags = get_hinting_flag() font = self._get_agg_font(prop) if font is None: return None if len(s) == 1 and ord(s) > 127: font.load_char(ord(s), flags=flags) else: # We pass '0' for angle here, since it will be rotated (in raster # space) in the following call to draw_text_image). font.set_text(s, 0, flags=flags) font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased']) d = font.get_descent() / 64.0 # The descent needs to be adjusted for the angle xd = -d * np.sin(np.deg2rad(angle)) yd = d * np.cos(np.deg2rad(angle)) #print x, y, int(x), int(y), s self._renderer.draw_text_image( font.get_image(), np.round(x - xd), np.round(y + yd) + 1, angle, gc)
get the width and height in display coords of the string s with FontPropertry prop # passing rgb is a little hack to make cacheing in the # texmanager more efficient. It is not meant to be used # outside the backend
def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop # passing rgb is a little hack to make cacheing in the # texmanager more efficient. It is not meant to be used # outside the backend """ if rcParams['text.usetex']: # todo: handle props size = prop.get_size_in_points() texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent(s, fontsize, renderer=self) return w, h, d if ismath: ox, oy, width, height, descent, fonts, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent flags = get_hinting_flag() font = self._get_agg_font(prop) font.set_text(s, 0.0, flags=flags) # the width and height of unrotated string w, h = font.get_width_height() d = font.get_descent() w /= 64.0 # convert from subpixels h /= 64.0 d /= 64.0 return w, h, d
Get the font for text instance t, cacheing for efficiency
def _get_agg_font(self, prop): """ Get the font for text instance t, cacheing for efficiency """ if __debug__: verbose.report('RendererAgg._get_agg_font', 'debug-annoying') key = hash(prop) font = RendererAgg._fontd.get(key) if font is None: fname = findfont(prop) font = RendererAgg._fontd.get(fname) if font is None: font = FT2Font( str(fname), hinting_factor=rcParams['text.hinting_factor']) RendererAgg._fontd[fname] = font RendererAgg._fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font
Restore the saved region. If bbox (instance of BboxBase, or its extents) is given, only the region specified by the bbox will be restored. *xy* (a tuple of two floasts) optionally specifies the new position (the LLC of the original region, not the LLC of the bbox) where the region will be restored. >>> region = renderer.copy_from_bbox() >>> x1, y1, x2, y2 = region.get_extents() >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), ... xy=(x1-dx, y1))
def restore_region(self, region, bbox=None, xy=None): """ Restore the saved region. If bbox (instance of BboxBase, or its extents) is given, only the region specified by the bbox will be restored. *xy* (a tuple of two floasts) optionally specifies the new position (the LLC of the original region, not the LLC of the bbox) where the region will be restored. >>> region = renderer.copy_from_bbox() >>> x1, y1, x2, y2 = region.get_extents() >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), ... xy=(x1-dx, y1)) """ if bbox is not None or xy is not None: if bbox is None: x1, y1, x2, y2 = region.get_extents() elif isinstance(bbox, BboxBase): x1, y1, x2, y2 = bbox.extents else: x1, y1, x2, y2 = bbox if xy is None: ox, oy = x1, y1 else: ox, oy = xy self._renderer.restore_region2(region, x1, y1, x2, y2, ox, oy) else: self._renderer.restore_region(region)
Start filtering. It simply create a new canvas (the old one is saved).
def start_filter(self): """ Start filtering. It simply create a new canvas (the old one is saved). """ self._filter_renderers.append(self._renderer) self._renderer = _RendererAgg(int(self.width), int(self.height), self.dpi) self._update_methods()
Save the plot in the current canvas as a image and apply the *post_processing* function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it.
def stop_filter(self, post_processing): """ Save the plot in the current canvas as a image and apply the *post_processing* function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it. """ # WARNING. # For agg_filter to work, the rendere's method need # to overridden in the class. See draw_markers, and draw_path_collections from matplotlib._image import fromarray width, height = int(self.width), int(self.height) buffer, bounds = self._renderer.tostring_rgba_minimized() l, b, w, h = bounds self._renderer = self._filter_renderers.pop() self._update_methods() if w > 0 and h > 0: img = np.fromstring(buffer, np.uint8) img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255., self.dpi) image = fromarray(img, 1) image.flipud_out() gc = self.new_gc() self._renderer.draw_image(gc, l+ox, height - b - h +oy, image)
Draw the figure using the renderer
def draw(self): """ Draw the figure using the renderer """ if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying') self.renderer = self.get_renderer(cleared=True) # acquire a lock on the shared font cache RendererAgg.lock.acquire() try: self.figure.draw(self.renderer) finally: RendererAgg.lock.release()
set a status value
def set_check(self, name, state): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(CheckItem(name, state))
Generate the checklists. Note that: 0,1 = off/on for auto-ticked items 2,3 = off/on for manually ticked items
def createLists(self): '''Generate the checklists. Note that: 0,1 = off/on for auto-ticked items 2,3 = off/on for manually ticked items''' self.beforeAssemblyList = { 'Confirm batteries charged':2, 'No physical damage to airframe':2, 'All electronics present and connected':2, 'Bottle loaded':2, 'Ground station operational':2 } self.beforeEngineList = { 'Avionics Power ON':2, 'Pixhawk Booted':0, 'Odroid Booted':2, 'Cameras calibrated and capturing':2, 'GPS lock':0, 'Airspeed check':2, 'Barometer check':2, 'Compass check':2, 'Flight mode MANUAL':0, 'Avionics Power':0, 'Servo Power':0, 'IMU Check':0, 'Aircraft Params Loaded':2, 'Waypoints Loaded':0, 'Servo and clevis check':2, 'Geofence loaded':2, 'Ignition circuit and battery check':2, 'Check stabilisation in FBWA mode':2 } self.beforeTakeoffList = { 'Engine throttle responsive':2, 'Runway clear':2, 'Radio links > 6db margin':0, 'Antenna tracker check':2, 'GCS stable':2, } self.beforeCruiseList = { 'Airspeed > 10 m/s':0, 'Altitude > 30 m':0, '< 100 degrees to 1st Waypoint':2, 'Airspeed and climb rate nominal':2 } self.bottleDropList = { 'Joe found':2, 'Joe waypoint laid in':2, '< 100m to Joe waypoint':2, 'Bottle drop mechanism activated':2 } self.beforeLandingList = { 'Runway clear':2, 'APM set to FBWA mode':2, '< 100m from airfield home':2 } self.beforeShutdownList = { 'Taxi to parking':2, 'Engine cutoff':2, 'Data downloaded':2, 'Ignition power off':2, 'Avionics power off':2 }
before assembly checklist
def createWidgets(self): #create the panels for the tabs PanelAssembly = wx.Panel(self.nb) boxAssembly = wx.BoxSizer(wx.VERTICAL) PanelAssembly.SetAutoLayout(True) PanelAssembly.SetSizer(boxAssembly) PanelAssembly.Layout() PanelEngine = wx.Panel(self.nb) boxEngine = wx.BoxSizer(wx.VERTICAL) PanelEngine.SetAutoLayout(True) PanelEngine.SetSizer(boxEngine) PanelEngine.Layout() PanelTakeoff = wx.Panel(self.nb) boxTakeoff = wx.BoxSizer(wx.VERTICAL) PanelTakeoff.SetAutoLayout(True) PanelTakeoff.SetSizer(boxTakeoff) PanelTakeoff.Layout() PanelCruise = wx.Panel(self.nb) boxCruise = wx.BoxSizer(wx.VERTICAL) PanelCruise.SetAutoLayout(True) PanelCruise.SetSizer(boxCruise) PanelCruise.Layout() PanelDrop = wx.Panel(self.nb) boxDrop = wx.BoxSizer(wx.VERTICAL) PanelDrop.SetAutoLayout(True) PanelDrop.SetSizer(boxDrop) PanelDrop.Layout() PanelLanding = wx.Panel(self.nb) boxLanding = wx.BoxSizer(wx.VERTICAL) PanelLanding.SetAutoLayout(True) PanelLanding.SetSizer(boxLanding) PanelLanding.Layout() PanelShutdown = wx.Panel(self.nb) boxShutdown = wx.BoxSizer(wx.VERTICAL) PanelShutdown.SetAutoLayout(True) PanelShutdown.SetSizer(boxShutdown) PanelShutdown.Layout() #add the data to the individual tabs '''before assembly checklist''' for key in self.beforeAssemblyList: if self.beforeAssemblyList[key] == 0: disCheckBox = wx.CheckBox(PanelAssembly, wx.ID_ANY, key) disCheckBox.Enable(False) boxAssembly.Add(disCheckBox) if self.beforeAssemblyList[key] == 2: boxAssembly.Add(wx.CheckBox(PanelAssembly, wx.ID_ANY, key)) self.AssemblyButton = wx.Button(PanelAssembly, wx.ID_ANY, "Close final hatches") boxAssembly.Add(self.AssemblyButton) '''before Engine Start checklist''' for key in self.beforeEngineList: if self.beforeEngineList[key] == 0: disCheckBox = wx.CheckBox(PanelEngine, wx.ID_ANY, key) disCheckBox.Enable(False) boxEngine.Add(disCheckBox) if self.beforeEngineList[key] == 2: boxEngine.Add(wx.CheckBox(PanelEngine, wx.ID_ANY, key)) self.EngineButton = wx.Button(PanelEngine, wx.ID_ANY, "Ready for Engine start") boxEngine.Add(self.EngineButton) '''before takeoff checklist''' for key in self.beforeTakeoffList: if self.beforeTakeoffList[key] == 0: disCheckBox = wx.CheckBox(PanelTakeoff, wx.ID_ANY, key) disCheckBox.Enable(False) boxTakeoff.Add(disCheckBox) if self.beforeTakeoffList[key] == 2: boxTakeoff.Add(wx.CheckBox(PanelTakeoff, wx.ID_ANY, key)) self.TakeoffButton = wx.Button(PanelTakeoff, wx.ID_ANY, "Ready for Takeoff") boxTakeoff.Add(self.TakeoffButton) '''before cruise/AUTO checklist''' for key in self.beforeCruiseList: if self.beforeCruiseList[key] == 0: disCheckBox = wx.CheckBox(PanelCruise, wx.ID_ANY, key) disCheckBox.Enable(False) boxCruise.Add(disCheckBox) if self.beforeCruiseList[key] == 2: boxCruise.Add(wx.CheckBox(PanelCruise, wx.ID_ANY, key)) self.CruiseButton = wx.Button(PanelCruise, wx.ID_ANY, "Ready for Cruise/AUTO") boxCruise.Add(self.CruiseButton) '''before bottle drop checklist''' for key in self.bottleDropList: if self.bottleDropList[key] == 0: disCheckBox = wx.CheckBox(PanelDrop, wx.ID_ANY, key) disCheckBox.Enable(False) boxDrop.Add(disCheckBox) if self.bottleDropList[key] == 2: boxDrop.Add(wx.CheckBox(PanelDrop, wx.ID_ANY, key)) self.DropButton = wx.Button(PanelDrop, wx.ID_ANY, "Ready for Bottle Drop") boxDrop.Add(self.DropButton) '''before landing checklist''' for key in self.beforeLandingList: if self.beforeLandingList[key] == 0: disCheckBox = wx.CheckBox(PanelLanding, wx.ID_ANY, key) disCheckBox.Enable(False) boxLanding.Add(disCheckBox) if self.beforeLandingList[key] == 2: boxLanding.Add(wx.CheckBox(PanelLanding, wx.ID_ANY, key)) self.LandingButton = wx.Button(PanelLanding, wx.ID_ANY, "Ready for Landing") boxLanding.Add(self.LandingButton) '''before shutdown checklist''' for key in self.beforeShutdownList: if self.beforeShutdownList[key] == 0: disCheckBox = wx.CheckBox(PanelShutdown, wx.ID_ANY, key) disCheckBox.Enable(False) boxShutdown.Add(disCheckBox) if self.beforeShutdownList[key] == 2: boxShutdown.Add(wx.CheckBox(PanelShutdown, wx.ID_ANY, key)) self.ShutdownButton = wx.Button(PanelShutdown, wx.ID_ANY, "Ready for Shutdown") boxShutdown.Add(self.ShutdownButton) #and add in the tabs self.nb.AddPage(PanelAssembly, "1. During Assembly") self.nb.AddPage(PanelEngine, "2. Before Engine Start") self.nb.AddPage(PanelTakeoff, "3. Before Takeoff") self.nb.AddPage(PanelCruise, "4. Before Cruise/AUTO") self.nb.AddPage(PanelDrop, "5. Before Bottle Drop") self.nb.AddPage(PanelLanding, "6. Before Landing") self.nb.AddPage(PanelShutdown, "7. Before Shutdown")
return vehicle type string from a heartbeat
def vehicle_type_string(self, hb): '''return vehicle type string from a heartbeat''' if hb.type == mavutil.mavlink.MAV_TYPE_FIXED_WING: return 'Plane' if hb.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER: return 'Rover' if hb.type == mavutil.mavlink.MAV_TYPE_SURFACE_BOAT: return 'Boat' if hb.type == mavutil.mavlink.MAV_TYPE_SUBMARINE: return 'Sub' if hb.type in [mavutil.mavlink.MAV_TYPE_QUADROTOR, mavutil.mavlink.MAV_TYPE_COAXIAL, mavutil.mavlink.MAV_TYPE_HEXAROTOR, mavutil.mavlink.MAV_TYPE_OCTOROTOR, mavutil.mavlink.MAV_TYPE_TRICOPTER, mavutil.mavlink.MAV_TYPE_DODECAROTOR]: return "Copter" if hb.type == mavutil.mavlink.MAV_TYPE_HELICOPTER: return "Heli" if hb.type == mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER: return "Tracker" return "UNKNOWN(%u)" % hb.type
update menu for new vehicles
def update_vehicle_menu(self): '''update menu for new vehicles''' self.vehicle_menu.items = [] for s in sorted(self.vehicle_list): clist = self.module('param').get_component_id_list(s) if len(clist) == 1: name = 'SysID %u: %s' % (s, self.vehicle_name_by_sysid[s]) self.vehicle_menu.items.append(MPMenuItem(name, name, '# vehicle %u' % s)) else: for c in sorted(clist): try: name = 'SysID %u[%u]: %s' % (s, c, self.component_name[s][c]) except KeyError as e: name = 'SysID %u[%u]: ?' % (s,c) self.vehicle_menu.items.append(MPMenuItem(name, name, '# vehicle %u:%u' % (s,c))) self.mpstate.console.set_menu(self.menu, self.menu_callback)
add a new vehicle
def add_new_vehicle(self, hb): '''add a new vehicle''' if hb.type == mavutil.mavlink.MAV_TYPE_GCS: return sysid = hb.get_srcSystem() self.vehicle_list.append(sysid) self.vehicle_name_by_sysid[sysid] = self.vehicle_type_string(hb) self.update_vehicle_menu()
handle an incoming mavlink packet
def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' if not isinstance(self.console, wxconsole.MessageConsole): return if not self.console.is_alive(): self.mpstate.console = textconsole.SimpleConsole() return type = msg.get_type() if type == 'HEARTBEAT': sysid = msg.get_srcSystem() if not sysid in self.vehicle_list: self.add_new_vehicle(msg) if sysid not in self.component_name: self.component_name[sysid] = {} compid = msg.get_srcComponent() if compid not in self.component_name[sysid]: self.component_name[sysid][compid] = self.component_type_string(msg) self.update_vehicle_menu() if self.last_param_sysid_timestamp != self.module('param').new_sysid_timestamp: '''a new component ID has appeared for parameters''' self.last_param_sysid_timestamp = self.module('param').new_sysid_timestamp self.update_vehicle_menu() if type in ['RADIO', 'RADIO_STATUS']: # handle RADIO msgs from all vehicles if msg.rssi < msg.noise+10 or msg.remrssi < msg.remnoise+10: fg = 'red' else: fg = 'black' self.console.set_status('Radio', 'Radio %u/%u %u/%u' % (msg.rssi, msg.noise, msg.remrssi, msg.remnoise), fg=fg) if not self.is_primary_vehicle(msg): # don't process msgs from other than primary vehicle, other than # updating vehicle list return master = self.master # add some status fields if type in [ 'GPS_RAW', 'GPS_RAW_INT' ]: if type == "GPS_RAW": num_sats1 = master.field('GPS_STATUS', 'satellites_visible', 0) else: num_sats1 = msg.satellites_visible num_sats2 = master.field('GPS2_RAW', 'satellites_visible', -1) if num_sats2 == -1: sats_string = "%u" % num_sats1 else: sats_string = "%u/%u" % (num_sats1, num_sats2) if ((msg.fix_type >= 3 and master.mavlink10()) or (msg.fix_type == 2 and not master.mavlink10())): if (msg.fix_type >= 4): fix_type = "%u" % msg.fix_type else: fix_type = "" self.console.set_status('GPS', 'GPS: OK%s (%s)' % (fix_type, sats_string), fg='green') else: self.console.set_status('GPS', 'GPS: %u (%s)' % (msg.fix_type, sats_string), fg='red') if master.mavlink10(): gps_heading = int(self.mpstate.status.msgs['GPS_RAW_INT'].cog * 0.01) else: gps_heading = self.mpstate.status.msgs['GPS_RAW'].hdg self.console.set_status('Heading', 'Hdg %s/%u' % (master.field('VFR_HUD', 'heading', '-'), gps_heading)) elif type == 'VFR_HUD': if master.mavlink10(): alt = master.field('GPS_RAW_INT', 'alt', 0) / 1.0e3 else: alt = master.field('GPS_RAW', 'alt', 0) home = self.module('wp').get_home() if home is not None: home_lat = home.x home_lng = home.y else: home_lat = None home_lng = None lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1.0e-7 lng = master.field('GLOBAL_POSITION_INT', 'lon', 0) * 1.0e-7 rel_alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 1.0e-3 agl_alt = None if self.settings.basealt != 0: agl_alt = self.console.ElevationMap.GetElevation(lat, lng) if agl_alt is not None: agl_alt = self.settings.basealt - agl_alt else: try: agl_alt_home = self.console.ElevationMap.GetElevation(home_lat, home_lng) except Exception as ex: print(ex) agl_alt_home = None if agl_alt_home is not None: agl_alt = self.console.ElevationMap.GetElevation(lat, lng) if agl_alt is not None: agl_alt = agl_alt_home - agl_alt if agl_alt is not None: agl_alt += rel_alt vehicle_agl = master.field('TERRAIN_REPORT', 'current_height', None) if vehicle_agl is None: vehicle_agl = '---' else: vehicle_agl = self.height_string(vehicle_agl) self.console.set_status('AGL', 'AGL %s/%s' % (self.height_string(agl_alt), vehicle_agl)) self.console.set_status('Alt', 'Alt %s' % self.height_string(rel_alt)) self.console.set_status('AirSpeed', 'AirSpeed %s' % self.speed_string(msg.airspeed)) self.console.set_status('GPSSpeed', 'GPSSpeed %s' % self.speed_string(msg.groundspeed)) self.console.set_status('Thr', 'Thr %u' % msg.throttle) t = time.localtime(msg._timestamp) flying = False if self.mpstate.vehicle_type == 'copter': flying = self.master.motors_armed() else: flying = msg.groundspeed > 3 if flying and not self.in_air: self.in_air = True self.start_time = time.mktime(t) elif flying and self.in_air: self.total_time = time.mktime(t) - self.start_time self.console.set_status('FlightTime', 'FlightTime %u:%02u' % (int(self.total_time)/60, int(self.total_time)%60)) elif not flying and self.in_air: self.in_air = False self.total_time = time.mktime(t) - self.start_time self.console.set_status('FlightTime', 'FlightTime %u:%02u' % (int(self.total_time)/60, int(self.total_time)%60)) elif type == 'ATTITUDE': self.console.set_status('Roll', 'Roll %u' % math.degrees(msg.roll)) self.console.set_status('Pitch', 'Pitch %u' % math.degrees(msg.pitch)) elif 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, 'RC' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_RC_RECEIVER, 'TERR' : mavutil.mavlink.MAV_SYS_STATUS_TERRAIN, 'RNG' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION, 'LOG' : mavutil.mavlink.MAV_SYS_STATUS_LOGGING, } announce = [ 'RC' ] for s in sensors.keys(): bits = sensors[s] present = ((msg.onboard_control_sensors_present & bits) == bits) enabled = ((msg.onboard_control_sensors_enabled & bits) == bits) healthy = ((msg.onboard_control_sensors_health & bits) == bits) if not present: fg = 'black' elif not enabled: fg = 'grey' elif not healthy: fg = 'red' else: fg = 'green' # for terrain show yellow if still loading if s == 'TERR' and fg == 'green' and master.field('TERRAIN_REPORT', 'pending', 0) != 0: fg = 'yellow' self.console.set_status(s, s, fg=fg) for s in announce: bits = sensors[s] enabled = ((msg.onboard_control_sensors_enabled & bits) == bits) healthy = ((msg.onboard_control_sensors_health & bits) == bits) was_healthy = ((self.last_sys_status_health & bits) == bits) if enabled and not healthy and was_healthy: self.say("%s fail" % s) self.last_sys_status_health = msg.onboard_control_sensors_health # check for any error bits being set: now = time.time() if now - self.last_sys_status_errors_announce > self.mpstate.settings.sys_status_error_warn_interval: for field_num in range(1, 5): field = "errors_count%u" % field_num x = getattr(msg, field, None) if x is None: self.console.writeln("Failed to get field %s" % field) self.last_sys_status_errors_announce = now break if x != 0: self.last_sys_status_errors_announce = now self.say("Critical failure") break elif type == 'WIND': self.console.set_status('Wind', 'Wind %u/%.2f' % (msg.direction, msg.speed)) elif type == 'EKF_STATUS_REPORT': highest = 0.0 vars = ['velocity_variance', 'pos_horiz_variance', 'pos_vert_variance', 'compass_variance', 'terrain_alt_variance'] for var in vars: v = getattr(msg, var, 0) highest = max(v, highest) if highest >= 1.0: fg = 'red' elif highest >= 0.5: fg = 'orange' else: fg = 'green' self.console.set_status('EKF', 'EKF', fg=fg) elif type == 'HWSTATUS': if msg.Vcc >= 4600 and msg.Vcc <= 5300: fg = 'green' else: fg = 'red' self.console.set_status('Vcc', 'Vcc %.2f' % (msg.Vcc * 0.001), fg=fg) elif type == 'POWER_STATUS': if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_CHANGED: fg = 'red' else: fg = 'green' status = 'PWR:' if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_USB_CONNECTED: status += 'U' if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_BRICK_VALID: status += 'B' if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_SERVO_VALID: status += 'S' if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_PERIPH_OVERCURRENT: status += 'O1' if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_PERIPH_HIPOWER_OVERCURRENT: status += 'O2' self.console.set_status('PWR', status, fg=fg) self.console.set_status('Srv', 'Srv %.2f' % (msg.Vservo*0.001), fg='green') elif type == 'HEARTBEAT': fmode = master.flightmode if self.settings.vehicle_name: fmode = self.settings.vehicle_name + ':' + fmode self.console.set_status('Mode', '%s' % fmode, fg='blue') if len(self.vehicle_list) > 1: self.console.set_status('SysID', 'Sys:%u' % msg.get_srcSystem(), fg='blue') if self.master.motors_armed(): arm_colour = 'green' else: arm_colour = 'red' armstring = 'ARM' # add safety switch state if 'SYS_STATUS' in self.mpstate.status.msgs: if (self.mpstate.status.msgs['SYS_STATUS'].onboard_control_sensors_enabled & mavutil.mavlink.MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS) == 0: armstring += '(SAFE)' self.console.set_status('ARM', armstring, fg=arm_colour) if self.max_link_num != len(self.mpstate.mav_master): for i in range(self.max_link_num): self.console.set_status('Link%u'%(i+1), '', row=1) self.max_link_num = len(self.mpstate.mav_master) for m in self.mpstate.mav_master: if self.mpstate.settings.checkdelay: linkdelay = (self.mpstate.status.highest_msec - m.highest_msec)*1.0e-3 else: linkdelay = 0 linkline = "Link %s " % (self.link_label(m)) fg = 'dark green' if m.linkerror: linkline += "down" fg = 'red' else: packets_rcvd_percentage = 100 if (m.mav_count+m.mav_loss) != 0: #avoid divide-by-zero packets_rcvd_percentage = (100.0 * m.mav_count) / (m.mav_count + m.mav_loss) linkbits = ["%u pkts" % m.mav_count, "%u lost" % m.mav_loss, "%.2fs delay" % linkdelay, ] try: if m.mav.signing.sig_count: # other end is sending us signed packets if not m.mav.signing.secret_key: # we've received signed packets but # can't verify them fg = 'orange' linkbits.append("!KEY") elif not m.mav.signing.sign_outgoing: # we've received signed packets but aren't # signing outselves; this can lead to hairloss fg = 'orange' linkbits.append("!SIGNING") if m.mav.signing.badsig_count: fg = 'orange' linkbits.append("%u badsigs" % m.mav.signing.badsig_count) except AttributeError as e: # mav.signing.sig_count probably doesn't exist pass linkline += "OK {rcv_pct:.1f}% ({bits})".format( rcv_pct=packets_rcvd_percentage, bits=", ".join(linkbits)) if linkdelay > 1 and fg == 'dark green': fg = 'orange' self.console.set_status('Link%u'%m.linknum, linkline, row=1, fg=fg) elif type in ['WAYPOINT_CURRENT', 'MISSION_CURRENT']: wpmax = self.module('wp').wploader.count() if wpmax > 0: wpmax = "/%u" % wpmax else: wpmax = "" self.console.set_status('WP', 'WP %u%s' % (msg.seq, wpmax)) lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1.0e-7 lng = master.field('GLOBAL_POSITION_INT', 'lon', 0) * 1.0e-7 if lat != 0 and lng != 0: airspeed = master.field('VFR_HUD', 'airspeed', 30) if abs(airspeed - self.speed) > 5: self.speed = airspeed else: self.speed = 0.98*self.speed + 0.02*airspeed self.speed = max(1, self.speed) time_remaining = int(self.estimated_time_remaining(lat, lng, msg.seq, self.speed)) self.console.set_status('ETR', 'ETR %u:%02u' % (time_remaining/60, time_remaining%60)) elif type == 'NAV_CONTROLLER_OUTPUT': self.console.set_status('WPDist', 'Distance %s' % self.dist_string(msg.wp_dist)) self.console.set_status('WPBearing', 'Bearing %u' % msg.target_bearing) if msg.alt_error > 0: alt_error_sign = "L" else: alt_error_sign = "H" if msg.aspd_error > 0: aspd_error_sign = "L" else: aspd_error_sign = "H" if math.isnan(msg.alt_error): alt_error = "NaN" else: alt_error = "%d%s" % (msg.alt_error, alt_error_sign) self.console.set_status('AltError', 'AltError %s' % alt_error) self.console.set_status('AspdError', 'AspdError %.1f%s' % (msg.aspd_error*0.01, aspd_error_sign))
handle an incoming mavlink packet
def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' type = msg.get_type() if type == "STATUSTEXT": # say some statustext values if msg.text.startswith("Tuning: "): self.say(msg.text[8:])
speak some text using espeak
def say_espeak(self, text, priority='important'): '''speak some text using espeak''' from espeak import espeak if self.settings.speech_voice: espeak.set_voice(self.settings.speech_voice) espeak.synth(text)
speech commands
def cmd_speech(self, args): '''speech commands''' usage = "usage: speech <say>" if len(args) < 1: print(usage) return if args[0] == "say": if len(args) < 2: print("usage: speech say <text to say>") return self.say(" ".join(args[1::])) if args[0] == "list_voices": self.list_voices()
handling incoming log data
def handle_log_data(self, m): '''handling incoming log data''' if self.download_file is None: return # lose some data # import random # if random.uniform(0,1) < 0.05: # print('dropping ', str(m)) # return if m.ofs != self.download_ofs: self.download_file.seek(m.ofs) self.download_ofs = m.ofs if m.count != 0: s = bytearray(m.data[:m.count]) self.download_file.write(s) self.download_set.add(m.ofs // 90) self.download_ofs += m.count self.download_last_timestamp = time.time() if m.count == 0 or (m.count < 90 and len(self.download_set) == 1 + (m.ofs // 90)): dt = time.time() - self.download_start self.download_file.close() size = os.path.getsize(self.download_filename) speed = size / (1000.0 * dt) print("Finished downloading %s (%u bytes %u seconds, %.1f kbyte/sec %u retries)" % ( self.download_filename, size, dt, speed, self.retries)) self.download_file = None self.download_filename = None self.download_set = set() self.master.mav.log_request_end_send(self.target_system, self.target_component) if len(self.download_queue): self.log_download_next()
append this menu item to a menu
def _append(self, menu): '''append this menu item to a menu''' from MAVProxy.modules.lib.wx_loader import wx submenu = wx.Menu() for i in range(len(self.items)): submenu.AppendRadioItem(self.id()+i, self.items[i], self.description) if self.items[i] == self.initial: submenu.Check(self.id()+i, True) menu.AppendSubMenu(submenu, self.name)
return a wx.Menu() for this menu
def wx_menu(self): '''return a wx.Menu() for this menu''' from MAVProxy.modules.lib.wx_loader import wx menu = wx.Menu() for i in range(len(self.items)): m = self.items[i] m._append(menu) return menu
add an item to a submenu using a menu path array
def add_to_submenu(self, submenu_path, item): ''' add an item to a submenu using a menu path array ''' for m in self.items: if m.name == submenu_path[0]: m.add_to_submenu(submenu_path[1:], item) return raise(ValueError("No submenu (%s) found" % (submenu_path[0])))
return a wx.MenuBar() for the menu
def wx_menu(self): '''return a wx.MenuBar() for the menu''' from MAVProxy.modules.lib.wx_loader import wx menubar = wx.MenuBar() for i in range(len(self.items)): m = self.items[i] menubar.Append(m.wx_menu(), m.name) return menubar
show a file dialog
def call(self): '''show a file dialog''' from MAVProxy.modules.lib.wx_loader import wx # remap flags to wx descriptors flag_map = { 'open': wx.FD_OPEN, 'save': wx.FD_SAVE, 'overwrite_prompt': wx.FD_OVERWRITE_PROMPT, } flagsMapped = map(lambda x: flag_map[x], self.flags) #need to OR together the elements of the flagsMapped tuple if len(flagsMapped) == 1: dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flagsMapped[0]) else: dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flagsMapped[0]|flagsMapped[1]) if dlg.ShowModal() != wx.ID_OK: return None return "\"" + dlg.GetPath().encode('utf8') + "\""
show a value dialog
def call(self): '''show a value dialog''' from MAVProxy.modules.lib.wx_loader import wx try: dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default)) except TypeError: dlg = wx.TextEntryDialog(None, self.title, self.title, value=str(self.default)) if dlg.ShowModal() != wx.ID_OK: return None return dlg.GetValue()
cammsg
def cmd_cammsg(self, args): '''cammsg''' params = [0, 0, 0, 0, 1, 0, 0] # fill in any args passed by user for i in range(min(len(args),len(params))): params[i] = float(args[i]) print("Sent DIGICAM_CONTROL CMD_LONG") self.master.mav.command_long_send( self.settings.target_system, # target_system 0, # target_component mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL, # command 0, # confirmation params[0], # param1 params[1], # param2 params[2], # param3 params[3], # param4 params[4], # param5 params[5], # param6 params[6])
cammsg_old
def cmd_cammsg_old(self, args): '''cammsg_old''' print("Sent old DIGICAM_CONTROL") self.master.mav.digicam_control_send( self.settings.target_system, # target_system 0, # target_component 0, 0, 0, 0, 1, 0, 0, 0)
execute supplied command long
def cmd_long(self, args): '''execute supplied command long''' if len(args) < 1: print("Usage: long <command> [arg1] [arg2]...") return command = None if args[0].isdigit(): command = int(args[0]) else: try: command = eval("mavutil.mavlink." + args[0]) except AttributeError as e: try: command = eval("mavutil.mavlink.MAV_CMD_" + args[0]) except AttributeError as e: pass if command is None: print("Unknown command long ({0})".format(args[0])) return floating_args = [ float(x) for x in args[1:] ] while len(floating_args) < 7: floating_args.append(float(0)) self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, command, 0, *floating_args)
speed value
def cmd_do_change_speed(self, args): '''speed value''' if ( len(args) != 1): print("Usage: setspeed SPEED_VALUE") return if (len(args) == 1): speed = float(args[0]) print("SPEED %s" % (str(speed))) self.master.mav.command_long_send( self.settings.target_system, # target_system mavutil.mavlink.MAV_COMP_ID_SYSTEM_CONTROL, # target_component mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, # command 0, # confirmation 0, # param1 speed, # param2 (Speed value) 0, # param3 0, # param4 0, # param5 0, # param6 0)
execute supplied command_int
def cmd_command_int(self, args): '''execute supplied command_int''' if len(args) != 11: print("num args{0}".format(len(args))) print("Usage: command_int frame command current autocontinue param1 param2 param3 param4 x y z") print("e.g. command_int GLOBAL_RELATIVE_ALT DO_SET_HOME 0 0 0 0 0 0 -353632120 1491659330 0") print("e.g. command_int GLOBAL MAV_CMD_DO_SET_ROI 0 0 0 0 0 0 5000000 5000000 500") return if args[0].isdigit(): frame = int(args[0]) else: try: # attempt to allow MAV_FRAME_GLOBAL for frame frame = eval("mavutil.mavlink." + args[0]) except AttributeError as e: try: # attempt to allow GLOBAL for frame frame = eval("mavutil.mavlink.MAV_FRAME_" + args[0]) except AttributeError as e: pass if frame is None: print("Unknown frame ({0})".format(args[0])) return command = None if args[1].isdigit(): command = int(args[1]) else: # let "command_int ... MAV_CMD_DO_SET_HOME ..." work try: command = eval("mavutil.mavlink." + args[1]) except AttributeError as e: try: # let "command_int ... DO_SET_HOME" work command = eval("mavutil.mavlink.MAV_CMD_" + args[1]) except AttributeError as e: pass current = int(args[2]) autocontinue = int(args[3]) param1 = float(args[4]) param2 = float(args[5]) param3 = float(args[6]) param4 = float(args[7]) x = int(args[8]) y = int(args[9]) z = float(args[10]) self.master.mav.command_int_send(self.settings.target_system, self.settings.target_component, frame, command, 0, 0, param1, param2, param3, param4, x, y, z)
Scale an in value in the range (inlow, inhigh) to the range (outlow, outhigh).
def scale(val, inlow=-1, inhigh=1, outlow=1000, outhigh=2000): '''Scale an in value in the range (inlow, inhigh) to the range (outlow, outhigh).''' return ( ((float(val) - inlow) / (inhigh - inlow)) * (outhigh - outlow) + outlow )
show key sensors
def cmd_sensors(self, args): '''show key sensors''' gps_heading = self.status.msgs['GPS_RAW_INT'].cog * 0.01 self.console.writeln("heading: %u/%u alt: %u/%u r/p: %u/%u speed: %u/%u thr: %u" % ( self.status.msgs['VFR_HUD'].heading, gps_heading, self.status.altitude, self.gps_alt, math.degrees(self.status.msgs['ATTITUDE'].roll), math.degrees(self.status.msgs['ATTITUDE'].pitch), self.status.msgs['VFR_HUD'].airspeed, self.status.msgs['VFR_HUD'].groundspeed, self.status.msgs['VFR_HUD'].throttle))
check heading discrepancy
def check_heading(self, m): '''check heading discrepancy''' if 'GPS_RAW_INT' in self.status.msgs: gps = self.status.msgs['GPS_RAW_INT'] if gps.vel < 300: return diff = math.fabs(angle_diff(m.heading, gps.cog / 100.0)) else: return self.report('heading', diff < 20, 'heading error %u' % diff)
returns 0 if key not found
def cmd_reverse_lookup(command_name): '''returns 0 if key not found''' for key, value in miss_cmds.items(): if (value.upper() == command_name.upper()): return key return 0
try to work out a reasonable column name from parameter description
def make_column_label(command_name, description, default): '''try to work out a reasonable column name from parameter description''' for (pattern, label) in description_map: if fnmatch.fnmatch(description, pattern): return label return default
return dictionary of column labels if available
def get_column_labels(command_name): '''return dictionary of column labels if available''' cmd = cmd_reverse_lookup(command_name) if cmd == 0: return {} labels = {} enum = mavutil.mavlink.enums['MAV_CMD'][cmd] for col in enum.param.keys(): labels[col] = make_column_label(command_name, enum.param[col], "P%u" % col) return labels
find an antenna tracker connection if possible
def find_connection(self): '''find an antenna tracker connection if possible''' if self.connection is not None: return self.connection for m in self.mpstate.mav_master: if 'HEARTBEAT' in m.messages: if m.messages['HEARTBEAT'].type == mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER: return m return None
tracker command parser
def cmd_tracker(self, args): '''tracker command parser''' usage = "usage: tracker <start|set|arm|disarm|level|param|mode|position> [options]" if len(args) == 0: print(usage) return if args[0] == "start": self.cmd_tracker_start() elif args[0] == "set": self.tracker_settings.command(args[1:]) elif args[0] == 'arm': self.cmd_tracker_arm() elif args[0] == 'disarm': self.cmd_tracker_disarm() elif args[0] == 'level': self.cmd_tracker_level() elif args[0] == 'param': self.cmd_tracker_param(args[1:]) elif args[0] == 'mode': self.cmd_tracker_mode(args[1:]) elif args[0] == 'position': self.cmd_tracker_position(args[1:]) elif args[0] == 'calpress': self.cmd_tracker_calpress(args[1:]) else: print(usage)
tracker manual positioning commands
def cmd_tracker_position(self, args): '''tracker manual positioning commands''' connection = self.find_connection() if not connection: print("No antenna tracker found") return positions = [0, 0, 0, 0, 0] # x, y, z, r, buttons. only position[0] (yaw) and position[1] (pitch) are currently used for i in range(0, 4): if len(args) > i: positions[i] = int(args[i]) # default values are 0 connection.mav.manual_control_send(connection.target_system, positions[0], positions[1], positions[2], positions[3], positions[4])
calibrate barometer on tracker
def cmd_tracker_calpress(self, args): '''calibrate barometer on tracker''' connection = self.find_connection() if not connection: print("No antenna tracker found") return connection.calibrate_pressure()
set arbitrary mode
def cmd_tracker_mode(self, args): '''set arbitrary mode''' connection = self.find_connection() if not connection: print("No antenna tracker found") return mode_mapping = connection.mode_mapping() if mode_mapping is None: print('No mode mapping available') return if len(args) != 1: print('Available modes: ', mode_mapping.keys()) return mode = args[0].upper() if mode not in mode_mapping: print('Unknown mode %s: ' % mode) return connection.set_mode(mode_mapping[mode])
handle an incoming mavlink packet from the master vehicle. Relay it to the tracker if it is a GLOBAL_POSITION_INT
def mavlink_packet(self, m): '''handle an incoming mavlink packet from the master vehicle. Relay it to the tracker if it is a GLOBAL_POSITION_INT''' if m.get_type() in ['GLOBAL_POSITION_INT', 'SCALED_PRESSURE']: connection = self.find_connection() if not connection: return if m.get_srcSystem() != connection.target_system: connection.mav.send(m)
called in idle time
def idle_task(self): '''called in idle time''' if not self.connection: return # check for a mavlink message from the tracker m = self.connection.recv_msg() if m is None: return if self.tracker_settings.debug: print(m) self.pstate.handle_mavlink_packet(self.connection, m) self.pstate.fetch_check(self.connection) if self.module('map') is None: return if m.get_type() == 'GLOBAL_POSITION_INT': (self.lat, self.lon, self.heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01) if self.lat != 0 or self.lon != 0: self.module('map').create_vehicle_icon('AntennaTracker', 'red', follow=False, vehicle_type='antenna') self.mpstate.map.set_position('AntennaTracker', (self.lat, self.lon), rotation=self.heading)
Parameter commands
def cmd_tracker_param(self, args): '''Parameter commands''' if not self.connection: print("tracker not connected") return self.pstate.handle_command(self.connection, self.mpstate, args)
fix up jumps when we add/remove rows
def fix_jumps(self, row_selected, delta): '''fix up jumps when we add/remove rows''' numrows = self.grid_mission.GetNumberRows() for row in range(numrows): command = self.grid_mission.GetCellValue(row, ME_COMMAND_COL) if command in ["DO_JUMP", "DO_CONDITION_JUMP"]: p1 = int(float(self.grid_mission.GetCellValue(row, ME_P1_COL))) if p1 > row_selected and p1+delta>0: self.grid_mission.SetCellValue(row, ME_P1_COL, str(float(p1+delta)))
setup legend for graphs
def cmd_legend(self, args): '''setup legend for graphs''' if len(args) == 0: for leg in self.legend.keys(): print("%s -> %s" % (leg, self.legend[leg])) elif len(args) == 1: leg = args[0] if leg in self.legend: print("Removing legend %s" % leg) self.legend.pop(leg) elif len(args) >= 2: leg = args[0] leg2 = args[1] print("Adding legend %s -> %s" % (leg, leg2)) self.legend[leg] = leg2
called on idle
def idle_task(self): '''called on idle''' if self.menu is not None and self.module('map') is not None and not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu)
control gimbal
def cmd_gimbal(self, args): '''control gimbal''' usage = 'Usage: gimbal <rate|point|roi|roivel|mode|status>' if len(args) == 0: print(usage) return if args[0] == 'rate': self.cmd_gimbal_rate(args[1:]) elif args[0] == 'point': self.cmd_gimbal_point(args[1:]) elif args[0] == 'roi': self.cmd_gimbal_roi(args[1:]) elif args[0] == 'mode': self.cmd_gimbal_mode(args[1:]) elif args[0] == 'status': self.cmd_gimbal_status(args[1:]) elif args[0] == 'roivel': self.cmd_gimbal_roi_vel(args[1:])
control gimbal mode
def cmd_gimbal_mode(self, args): '''control gimbal mode''' if len(args) != 1: print("usage: gimbal mode <GPS|MAVLink>") return if args[0].upper() == 'GPS': mode = mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT elif args[0].upper() == 'MAVLINK': mode = mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING elif args[0].upper() == 'RC': mode = mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING else: print("Unsupported mode %s" % args[0]) self.master.mav.mount_configure_send(self.target_system, self.target_component, mode, 1, 1, 1)
control roi position
def cmd_gimbal_roi(self, args): '''control roi position''' latlon = None try: latlon = self.module('map').click_position except Exception: print("No map available") return if latlon is None: print("No map click position available") return self.master.mav.mount_control_send(self.target_system, self.target_component, latlon[0]*1e7, latlon[1]*1e7, 0, # altitude zero for now 0)
control roi position and velocity
def cmd_gimbal_roi_vel(self, args): '''control roi position and velocity''' if len(args) != 0 and len(args) != 3 and len(args) != 6: print("usage: gimbal roivel [VEL_NORTH VEL_EAST VEL_DOWN] [ACC_NORTH ACC_EASY ACC_DOWN]") return latlon = None vel = [0,0,0] acc = [0,0,0] if (len(args) >= 3): vel[0:3] = args[0:3] if (len(args) == 6): acc[0:3] = args[3:6] try: latlon = self.module('map').click_position except Exception: print("No map available") return if latlon is None: print("No map click position available") latlon = (0,0,0) self.master.mav.set_roi_global_int_send(0, #time_boot_ms 1, #target_system 1, #target_component mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, 0, #type_mask 0, #roi_index 0, #timeout_ms int(latlon[0]*1e7), #lat int int(latlon[1]*1e7), #lng int float(0), #alt float(vel[0]), #vx float(vel[1]), #vy float(vel[2]), #vz float(acc[0]), #ax float(acc[1]), #ay float(acc[2]))
control gimbal rate
def cmd_gimbal_rate(self, args): '''control gimbal rate''' if len(args) != 3: print("usage: gimbal rate ROLL PITCH YAW") return (roll, pitch, yaw) = (float(args[0]), float(args[1]), float(args[2])) self.master.mav.gimbal_control_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, radians(roll), radians(pitch), radians(yaw))
control gimbal pointing
def cmd_gimbal_point(self, args): '''control gimbal pointing''' if len(args) != 3: print("usage: gimbal point ROLL PITCH YAW") return (roll, pitch, yaw) = (float(args[0]), float(args[1]), float(args[2])) self.master.mav.mount_control_send(self.target_system, self.target_component, pitch*100, roll*100, yaw*100, 0)
show gimbal status
def cmd_gimbal_status(self, args): '''show gimbal status''' master = self.master if 'GIMBAL_REPORT' in master.messages: print(master.messages['GIMBAL_REPORT']) else: print("No GIMBAL_REPORT messages")
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if not self.mpstate.map: # don't draw if no map return if m.get_type() != 'GIMBAL_REPORT': return needed = ['ATTITUDE', 'GLOBAL_POSITION_INT'] for n in needed: if not n in self.master.messages: return # clear the camera icon self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('GimbalView')) gpi = self.master.messages['GLOBAL_POSITION_INT'] att = self.master.messages['ATTITUDE'] vehicle_dcm = Matrix3() vehicle_dcm.from_euler(att.roll, att.pitch, att.yaw) rotmat_copter_gimbal = Matrix3() rotmat_copter_gimbal.from_euler312(m.joint_roll, m.joint_el, m.joint_az) gimbal_dcm = vehicle_dcm * rotmat_copter_gimbal lat = gpi.lat * 1.0e-7 lon = gpi.lon * 1.0e-7 alt = gpi.relative_alt * 1.0e-3 # ground plane ground_plane = Plane() # the position of the camera in the air, remembering its a right # hand coordinate system, so +ve z is down camera_point = Vector3(0, 0, -alt) # get view point of camera when not rotated view_point = Vector3(1, 0, 0) # rotate view_point to form current view vector rot_point = gimbal_dcm * view_point # a line from the camera to the ground line = Line(camera_point, rot_point) # find the intersection with the ground pt = line.plane_intersection(ground_plane, forward_only=True) if pt is None: # its pointing up into the sky return None (view_lat, view_lon) = mp_util.gps_offset(lat, lon, pt.y, pt.x) icon = self.mpstate.map.icon('camera-small-red.png') self.mpstate.map.add_object(mp_slipmap.SlipIcon('gimbalview', (view_lat,view_lon), icon, layer='GimbalView', rotation=0, follow=False))
handle different image formats, returning (width,height) tuple
def image_shape(img): '''handle different image formats, returning (width,height) tuple''' if hasattr(img, 'shape'): return (img.shape[1], img.shape[0]) return (img.width, img.height)
draw a line on the image
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) (width, height) = image_shape(img) (ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2) if ret is False: if len(self._pix_points) == 0: self._pix_points.append(None) self._pix_points.append(None) return cv2.line(img, pix1, pix2, colour, linewidth) cv2.circle(img, pix2, linewidth*2, colour) if len(self._pix_points) == 0: self._pix_points.append(pix1) self._pix_points.append(pix2) if self.arrow: xdiff = pix2[0]-pix1[0] ydiff = pix2[1]-pix1[1] if (xdiff*xdiff + ydiff*ydiff) > 400: # the segment is longer than 20 pix SlipArrow(self.key, self.layer, (int(pix1[0]+xdiff/2.0), int(pix1[1]+ydiff/2.0)), self.colour, self.linewidth, math.atan2(ydiff, xdiff)+math.pi/2.0).draw(img)
draw a line on the image
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) (width, height) = image_shape(img) (ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2) if ret is False: return cv2.line(img, pix1, pix2, colour, linewidth) cv2.circle(img, pix2, linewidth*2, colour)
draw legend on the image
def draw(self, img, pixmapper, bounds): '''draw legend on the image''' if self._img is None: self._img = self.draw_legend() w = self._img.shape[1] h = self._img.shape[0] px = 5 py = 5 img[py:py+h,px:px+w] = self._img
return a cv image for the thumbnail
def img(self): '''return a cv image for the thumbnail''' if self._img is not None: return self._img self._img = cv2.cvtColor(self.original_img, cv2.COLOR_BGR2RGB) if self.border_width and self.border_colour is not None: cv2.rectangle(self._img, (0, 0), (self.width-1, self.height-1), self.border_colour, self.border_width) return self._img
draw the thumbnail on the image
def draw(self, img, pixmapper, bounds): '''draw the thumbnail on the image''' if self.hidden: return thumb = self.img() (px,py) = pixmapper(self.latlon) # find top left (w, h) = image_shape(thumb) px -= w//2 py -= h//2 (px, py, sx, sy, w, h) = self.clip(px, py, w, h, img) thumb_roi = thumb[sy:sy+h, sx:sx+w] img[py:py+h, px:px+w] = thumb_roi # remember where we placed it for clicked() self.posx = px+w//2 self.posy = py+h//2
draw the trail
def draw(self, img, pixmapper, bounds): '''draw the trail''' for p in self.points: (px,py) = pixmapper(p) (width, height) = image_shape(img) if px >= 0 and py >= 0 and px < width and py < height: cv2.circle(img, (px,py), 1, self.colour)
return a cv image for the icon
def img(self): '''return a cv image for the icon''' SlipThumbnail.img(self) if self.rotation: # rotate the image mat = cv2.getRotationMatrix2D((self.height//2, self.width//2), -self.rotation, 1.0) self._rotated = cv2.warpAffine(self._img, mat, (self.height, self.width)) else: self._rotated = self._img return self._rotated
draw the icon on the image
def draw(self, img, pixmapper, bounds): '''draw the icon on the image''' if self.hidden: return if self.trail is not None: self.trail.draw(img, pixmapper, bounds) icon = self.img() (px,py) = pixmapper(self.latlon) # find top left (w, h) = image_shape(icon) px -= w//2 py -= h//2 (px, py, sx, sy, w, h) = self.clip(px, py, w, h, img) img[py:py + h, px:px + w] = cv2.add(img[py:py+h, px:px+w], icon[sy:sy+h, sx:sx+w]) if self.label is not None: cv2.putText(img, self.label, (px,py), cv2.FONT_HERSHEY_SIMPLEX, 1.0, self.colour) # remember where we placed it for clicked() self.posx = px+w//2 self.posy = py+h//2
return a wx image
def img(self): '''return a wx image''' import wx with warnings.catch_warnings(): warnings.simplefilter('ignore') img = wx.EmptyImage(self.width, self.height) img.SetData(self.imgstr) return img
terrain command parser
def cmd_terrain(self, args): '''terrain command parser''' usage = "usage: terrain <set|status|check>" if len(args) == 0: print(usage) return if args[0] == "status": print("blocks_sent: %u requests_received: %u" % ( self.blocks_sent, self.requests_received)) elif args[0] == "set": self.terrain_settings.command(args[1:]) elif args[0] == "check": self.cmd_terrain_check(args[1:]) else: print(usage)
check a piece of terrain data
def cmd_terrain_check(self, args): '''check a piece of terrain data''' if len(args) >= 2: latlon = (float(args[0]), float(args[1])) else: try: latlon = self.module('map').click_position except Exception: print("No map available") return if latlon is None: print("No map click position available") return self.check_lat = int(latlon[0]*1e7) self.check_lon = int(latlon[1]*1e7) self.master.mav.terrain_check_send(self.check_lat, self.check_lon)
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 == 'TERRAIN_REQUEST': self.current_request = msg self.sent_mask = 0 self.requests_received += 1 elif type == 'TERRAIN_REPORT': if (msg.lat == self.check_lat and msg.lon == self.check_lon and (self.check_lat != 0 or self.check_lon != 0)): print(msg) self.check_lat = 0 self.check_lon = 0
send some terrain data
def send_terrain_data_bit(self, bit): '''send some terrain data''' lat = self.current_request.lat * 1.0e-7 lon = self.current_request.lon * 1.0e-7 bit_spacing = self.current_request.grid_spacing * 4 (lat, lon) = mp_util.gps_offset(lat, lon, east=bit_spacing * (bit % 8), north=bit_spacing * (bit // 8)) data = [] for i in range(4*4): y = i % 4 x = i // 4 (lat2,lon2) = mp_util.gps_offset(lat, lon, east=self.current_request.grid_spacing * y, north=self.current_request.grid_spacing * x) alt = self.ElevationModel.GetElevation(lat2, lon2) if alt is None: if self.terrain_settings.debug: print("no alt ", lat2, lon2) return data.append(int(alt)) self.master.mav.terrain_data_send(self.current_request.lat, self.current_request.lon, self.current_request.grid_spacing, bit, data) self.blocks_sent += 1 self.last_send_time = time.time() self.sent_mask |= 1<<bit if self.terrain_settings.debug and bit == 55: lat = self.current_request.lat * 1.0e-7 lon = self.current_request.lon * 1.0e-7 print("--lat=%f --lon=%f %.1f" % ( lat, lon, self.ElevationModel.GetElevation(lat, lon))) (lat2,lon2) = mp_util.gps_offset(lat, lon, east=32*self.current_request.grid_spacing, north=28*self.current_request.grid_spacing) print("--lat=%f --lon=%f %.1f" % ( lat2, lon2, self.ElevationModel.GetElevation(lat2, lon2)))
send some terrain data
def send_terrain_data(self): '''send some terrain data''' for bit in range(56): if self.current_request.mask & (1<<bit) and self.sent_mask & (1<<bit) == 0: self.send_terrain_data_bit(bit) return # no bits to send self.current_request = None self.sent_mask = 0
called when idle
def idle_task(self): '''called when idle''' if self.current_request is None: return if time.time() - self.last_send_time < 0.2: # limit to 5 per second return self.send_terrain_data()
set arbitrary mode
def cmd_mode(self, args): '''set arbitrary mode''' mode_mapping = self.master.mode_mapping() if mode_mapping is None: print('No mode mapping available') return if len(args) != 1: print('Available modes: ', mode_mapping.keys()) return if args[0].isdigit(): modenum = int(args[0]) else: mode = args[0].upper() if mode not in mode_mapping: print('Unknown mode %s: ' % mode) return modenum = mode_mapping[mode] self.master.set_mode(modenum)
handle mode switch by mode name as command
def unknown_command(self, args): '''handle mode switch by mode name as command''' mode_mapping = self.master.mode_mapping() mode = args[0].upper() if mode in mode_mapping: self.master.set_mode(mode_mapping[mode]) return True return False
set GUIDED target
def cmd_guided(self, args): '''set GUIDED target''' if len(args) != 1 and len(args) != 3: print("Usage: guided ALTITUDE | guided LAT LON ALTITUDE") return if len(args) == 3: latitude = float(args[0]) longitude = float(args[1]) altitude = float(args[2]) latlon = (latitude, longitude) else: try: latlon = self.module('map').click_position except Exception: print("No map available") return if latlon is None: print("No map click position available") return altitude = float(args[0]) print("Guided %s %s" % (str(latlon), str(altitude))) self.master.mav.mission_item_send (self.settings.target_system, self.settings.target_component, 0, self.module('wp').get_default_frame(), mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2, 0, 0, 0, 0, 0, latlon[0], latlon[1], altitude)
child process - this holds all the GUI elements
def child_task(self): '''child process - this holds all the GUI elements''' self.parent_pipe_send.close() from MAVProxy.modules.lib.wx_loader import wx from MAVProxy.modules.lib.wxhorizon_ui import HorizonFrame # Create wx application app = wx.App(False) app.frame = HorizonFrame(state=self, title=self.title) app.frame.SetDoubleBuffered(True) app.frame.Show() app.MainLoop() self.close_event.set()
check for FDM packets from runsim
def check_sim_in(self): '''check for FDM packets from runsim''' try: pkt = self.sim_in.recv(17*8 + 4) except socket.error as e: if not e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]: raise return if len(pkt) != 17*8 + 4: # wrong size, discard it print("wrong size %u" % len(pkt)) return (latitude, longitude, altitude, heading, v_north, v_east, v_down, ax, ay, az, phidot, thetadot, psidot, roll, pitch, yaw, vcas, check) = struct.unpack('<17dI', pkt) (p, q, r) = self.convert_body_frame(radians(roll), radians(pitch), radians(phidot), radians(thetadot), radians(psidot)) try: self.hil_state_msg = self.master.mav.hil_state_encode(int(time.time()*1e6), radians(roll), radians(pitch), radians(yaw), p, q, r, int(latitude*1.0e7), int(longitude*1.0e7), int(altitude*1.0e3), int(v_north*100), int(v_east*100), 0, int(ax*1000/9.81), int(ay*1000/9.81), int(az*1000/9.81)) except Exception: return
check if we should send new servos to flightgear
def check_sim_out(self): '''check if we should send new servos to flightgear''' now = time.time() if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None: return self.last_sim_send_time = now servos = [] for ch in range(1,9): servos.append(self.scale_channel(ch, getattr(self.rc_channels_scaled, 'chan%u_scaled' % ch))) servos.extend([0,0,0, 0,0,0]) buf = struct.pack('<14H', *servos) try: self.sim_out.send(buf) except socket.error as e: if not e.errno in [ errno.ECONNREFUSED ]: raise return
check if we should send new data to the APM
def check_apm_out(self): '''check if we should send new data to the APM''' now = time.time() if now - self.last_apm_send_time < 0.02: return self.last_apm_send_time = now if self.hil_state_msg is not None: self.master.mav.send(self.hil_state_msg)
convert a set of roll rates from earth frame to body frame
def convert_body_frame(self, phi, theta, phiDot, thetaDot, psiDot): '''convert a set of roll rates from earth frame to body frame''' p = phiDot - psiDot*math.sin(theta) q = math.cos(phi)*thetaDot + math.sin(phi)*psiDot*math.cos(theta) r = math.cos(phi)*psiDot*math.cos(theta) - math.sin(phi)*thetaDot return (p, q, r)
scale a channel to 1000/1500/2000
def scale_channel(self, ch, value): '''scale a channel to 1000/1500/2000''' v = value/10000.0 if v < -1: v = -1 elif v > 1: v = 1 if ch == 3 and self.mpstate.vehicle_type != 'rover': if v < 0: v = 0 return int(1000 + v*1000) return int(1500 + v*500)
control behaviour of the module
def cmd_messagerate(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.status()) elif args[0] == "reset": self.reset() else: print(self.usage())
reset rates
def reset(self): '''reset rates''' self.counts = {} self.buckets = [] self.last_calc = time.time()
returns rates
def status(self): '''returns rates''' counts = {} for bucket in self.buckets: for x in bucket: if not x in counts: counts[x] = 0 counts[x] += bucket[x] ret = "" mtypes = counts.keys() mtypes.sort() for mtype in mtypes: ret += "%s: %0.1f/s\n" % (mtype, counts[mtype]/float(len(self.buckets))) return ret
called rapidly by mavproxy
def idle_task(self): '''called rapidly by mavproxy''' now = time.time() time_delta = now - self.last_calc if time_delta > 1: self.last_calc = now self.buckets.append(self.counts) self.counts = {} if len(self.buckets) > self.max_buckets: self.buckets = self.buckets[-self.max_buckets:]
handle mavlink packets
def mavlink_packet(self, m): '''handle mavlink packets''' mtype = m.get_type() if mtype not in self.counts: self.counts[mtype] = 0 self.counts[mtype] += 1
set a setting
def set(self, value): '''set a setting''' if value == 'None' and self.default is None: value = None if value is not None: if self.type == bool: if str(value).lower() in ['1', 'true', 'yes']: value = True elif str(value).lower() in ['0', 'false', 'no']: value = False else: return False else: try: value = self.type(value) except: return False if self.range is not None: (minv,maxv) = self.range if value < minv or value > maxv: return False if self.choice is not None: found = False for v in self.choice: if v.lower() == value.lower(): found = True value = v break if not found: print("Must be one of %s" % str(self.choice)) return False self.value = value return True
add a new setting
def append(self, v): '''add a new setting''' if isinstance(v, MPSetting): setting = v else: (name,type,default) = v label = name tab = None if len(v) > 3: label = v[3] if len(v) > 4: tab = v[4] setting = MPSetting(name, type, default, label=label, tab=tab) # when a tab name is set, cascade it to future settings if setting.tab is None: setting.tab = self._default_tab else: self._default_tab = setting.tab self._vars[setting.name] = setting self._keys.append(setting.name) self._last_change = time.time()
set a setting
def set(self, name, value): '''set a setting''' if not name in self._vars: raise AttributeError setting = self._vars[name] oldvalue = setting.value if not setting.set(value): print("Unable to convert %s to type %s" % (value, setting.type)) return False if oldvalue != setting.value: self._last_change = time.time() if self._callback: self._callback(setting) return True
get a setting
def get(self, name): '''get a setting''' if not name in self._vars: raise AttributeError setting = self._vars[name] return setting.value
control options from cmdline
def command(self, args): '''control options from cmdline''' if len(args) == 0: self.show_all() return if getattr(self, args[0], [None]) == [None]: print("Unknown setting '%s'" % args[0]) return if len(args) == 1: self.show(args[0]) else: self.set(args[0], args[1])
save settings to a file. Return True/False on success/failure
def save(self, filename): '''save settings to a file. Return True/False on success/failure''' try: f = open(filename, mode='w') except Exception: return False for k in self.list(): f.write("%s=%s\n" % (k, self.get(k))) f.close() return True
load settings from a file. Return True/False on success/failure
def load(self, filename): '''load settings from a file. Return True/False on success/failure''' try: f = open(filename, mode='r') except Exception: return False while True: line = f.readline() if not line: break line = line.rstrip() eq = line.find('=') if eq == -1: continue name = line[:eq] value = line[eq+1:] self.set(name, value) f.close() return True