INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744
def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' canvas = self.canvas dc =wx.ClientDC(canvas) # Set logical function to XOR for rubberbanding dc.SetLogicalFunction(wx.XOR) # Set dc brush and pen # Here I set brush and pen to white and grey respectively # You can set it to your own choices # The brush setting is not really needed since we # dont do any filling of the dc. It is set just for # the sake of completion. wbrush =wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT) wpen =wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID) dc.SetBrush(wbrush) dc.SetPen(wpen) dc.ResetBoundingBox() dc.BeginDrawing() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 if y1<y0: y0, y1 = y1, y0 if x1<y0: x0, x1 = x1, x0 w = x1 - x0 h = y1 - y0 rect = int(x0), int(y0), int(w), int(h) try: lastrect = self.lastrect except AttributeError: pass else: dc.DrawRectangle(*lastrect) #erase last self.lastrect = rect dc.DrawRectangle(*rect) dc.EndDrawing()
Creates the 'menu' - implemented as a button which opens a pop-up menu since wxPython does not allow a menu as a control
def _create_menu(self): """ Creates the 'menu' - implemented as a button which opens a pop-up menu since wxPython does not allow a menu as a control """ DEBUG_MSG("_create_menu()", 1, self) self._menu = MenuButtonWx(self) self.AddControl(self._menu) self.AddSeparator()
Creates the button controls, and links them to event handlers
def _create_controls(self, can_kill): """ Creates the button controls, and links them to event handlers """ DEBUG_MSG("_create_controls()", 1, self) # Need the following line as Windows toolbars default to 15x16 self.SetToolBitmapSize(wx.Size(16,16)) self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('stock_left.xpm'), 'Left', 'Scroll left') self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('stock_right.xpm'), 'Right', 'Scroll right') self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase X axis magnification') self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease X axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_Y_PAN_UP,_load_bitmap('stock_up.xpm'), 'Up', 'Scroll up') self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('stock_down.xpm'), 'Down', 'Scroll down') self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase Y axis magnification') self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease Y axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_SAVE, _load_bitmap('stock_save_as.xpm'), 'Save', 'Save plot contents as images') self.AddSeparator() bind(self, wx.EVT_TOOL, self._onLeftScroll, id=_NTB_X_PAN_LEFT) bind(self, wx.EVT_TOOL, self._onRightScroll, id=_NTB_X_PAN_RIGHT) bind(self, wx.EVT_TOOL, self._onXZoomIn, id=_NTB_X_ZOOMIN) bind(self, wx.EVT_TOOL, self._onXZoomOut, id=_NTB_X_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onUpScroll, id=_NTB_Y_PAN_UP) bind(self, wx.EVT_TOOL, self._onDownScroll, id=_NTB_Y_PAN_DOWN) bind(self, wx.EVT_TOOL, self._onYZoomIn, id=_NTB_Y_ZOOMIN) bind(self, wx.EVT_TOOL, self._onYZoomOut, id=_NTB_Y_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onSave, id=_NTB_SAVE) bind(self, wx.EVT_TOOL_ENTER, self._onEnterTool, id=self.GetId()) if can_kill: bind(self, wx.EVT_TOOL, self._onClose, id=_NTB_CLOSE) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel)
ind is a list of index numbers for the axes which are to be made active
def set_active(self, ind): """ ind is a list of index numbers for the axes which are to be made active """ DEBUG_MSG("set_active()", 1, self) self._ind = ind if ind != None: self._active = [ self._axes[i] for i in self._ind ] else: self._active = [] # Now update button text wit active axes self._menu.updateButtonText(ind)
Update the toolbar menu - e.g., called when a new subplot or axes are added
def update(self): """ Update the toolbar menu - e.g., called when a new subplot or axes are added """ DEBUG_MSG("update()", 1, self) self._axes = self.canvas.figure.get_axes() self._menu.updateAxes(len(self._axes))
SRTM data is split into different directories, get a list of all of them and create a dictionary for easy lookup.
def createFileList(self): """SRTM data is split into different directories, get a list of all of them and create a dictionary for easy lookup.""" global childFileListDownload global filelistDownloadActive mypid = os.getpid() if mypid not in childFileListDownload or not childFileListDownload[mypid].is_alive(): childFileListDownload[mypid] = multiproc.Process(target=self.createFileListHTTP) filelistDownloadActive = 1 childFileListDownload[mypid].start() filelistDownloadActive = 0
fetch a URL with redirect handling
def getURIWithRedirect(self, url): '''fetch a URL with redirect handling''' tries = 0 while tries < 5: conn = httplib.HTTPConnection(self.server) conn.request("GET", url) r1 = conn.getresponse() if r1.status in [301, 302, 303, 307]: location = r1.getheader('Location') if self.debug: print("redirect from %s to %s" % (url, location)) url = location conn.close() tries += 1 continue data = r1.read() conn.close() if sys.version_info.major < 3: return data else: encoding = r1.headers.get_content_charset(default) return data.decode(encoding) return None
Create a list of the available SRTM files on the server using HTTP file transfer protocol (rather than ftp). 30may2010 GJ ORIGINAL VERSION
def createFileListHTTP(self): """Create a list of the available SRTM files on the server using HTTP file transfer protocol (rather than ftp). 30may2010 GJ ORIGINAL VERSION """ mp_util.child_close_fds() if self.debug: print("Connecting to %s" % self.server, self.directory) try: data = self.getURIWithRedirect(self.directory) except Exception: return parser = parseHTMLDirectoryListing() parser.feed(data) continents = parser.getDirListing() if self.debug: print('continents: ', continents) for continent in continents: if not continent[0].isalpha() or continent.startswith('README'): continue if self.debug: print("Downloading file list for: ", continent) url = "%s%s" % (self.directory,continent) if self.debug: print("fetching %s" % url) try: data = self.getURIWithRedirect(url) except Exception as ex: print("Failed to download %s : %s" % (url, ex)) continue parser = parseHTMLDirectoryListing() parser.feed(data) files = parser.getDirListing() for filename in files: self.filelist[self.parseFilename(filename)] = ( continent, filename) '''print(self.filelist)''' # Add meta info self.filelist["server"] = self.server self.filelist["directory"] = self.directory tmpname = self.filelist_file + ".tmp" with open(tmpname , 'wb') as output: pickle.dump(self.filelist, output) output.close() try: os.unlink(self.filelist_file) except Exception: pass try: os.rename(tmpname, self.filelist_file) except Exception: pass if self.debug: print("created file list with %u entries" % len(self.filelist))
Get lat/lon values from filename.
def parseFilename(self, filename): """Get lat/lon values from filename.""" match = self.filename_regex.match(filename) if match is None: # TODO?: Raise exception? '''print("Filename", filename, "unrecognized!")''' return None lat = int(match.group(2)) lon = int(match.group(4)) if match.group(1) == "S": lat = -lat if match.group(3) == "W": lon = -lon return lat, lon
Get a SRTM tile object. This function can return either an SRTM1 or SRTM3 object depending on what is available, however currently it only returns SRTM3 objects.
def getTile(self, lat, lon): """Get a SRTM tile object. This function can return either an SRTM1 or SRTM3 object depending on what is available, however currently it only returns SRTM3 objects.""" global childFileListDownload global filelistDownloadActive mypid = os.getpid() if mypid in childFileListDownload and childFileListDownload[mypid].is_alive(): if self.debug: print("still getting file list") return 0 elif not os.path.isfile(self.filelist_file) and filelistDownloadActive == 0: self.createFileList() return 0 elif not self.filelist: if self.debug: print("Filelist download complete, loading data ", self.filelist_file) data = open(self.filelist_file, 'rb') self.filelist = pickle.load(data) data.close() try: continent, filename = self.filelist[(int(lat), int(lon))] except KeyError: if len(self.filelist) > self.min_filelist_len: # we appear to have a full filelist - this must be ocean return SRTMOceanTile(int(lat), int(lon)) return 0 global childTileDownload mypid = os.getpid() if not os.path.exists(os.path.join(self.cachedir, filename)): if not mypid in childTileDownload or not childTileDownload[mypid].is_alive(): try: childTileDownload[mypid] = multiproc.Process(target=self.downloadTile, args=(str(continent), str(filename))) childTileDownload[mypid].start() except Exception as ex: if mypid in childTileDownload: childTileDownload.pop(mypid) return 0 '''print("Getting Tile")''' return 0 elif mypid in childTileDownload and childTileDownload[mypid].is_alive(): '''print("Still Getting Tile")''' return 0 # TODO: Currently we create a new tile object each time. # Caching is required for improved performance. try: return SRTMTile(os.path.join(self.cachedir, filename), int(lat), int(lon)) except InvalidTileError: return 0
control behaviour of the module
def cmd_example(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.status()) elif args[0] == "set": self.example_settings.command(args[1:]) else: print(self.usage())
returns information about module
def status(self): '''returns information about module''' self.status_callcount += 1 self.last_bored = time.time() # status entertains us return("status called %(status_callcount)d times. My target positions=%(packets_mytarget)u Other target positions=%(packets_mytarget)u" % {"status_callcount": self.status_callcount, "packets_mytarget": self.packets_mytarget, "packets_othertarget": self.packets_othertarget, })
called rapidly by mavproxy
def idle_task(self): '''called rapidly by mavproxy''' now = time.time() if now-self.last_bored > self.boredom_interval: self.last_bored = now message = self.boredom_message() self.say("%s: %s" % (self.name,message)) # See if whatever we're connected to would like to play: self.master.mav.statustext_send(mavutil.mavlink.MAV_SEVERITY_NOTICE, message)
handle mavlink packets
def mavlink_packet(self, m): '''handle mavlink packets''' if m.get_type() == 'GLOBAL_POSITION_INT': if self.settings.target_system == 0 or self.settings.target_system == m.get_srcSystem(): self.packets_mytarget += 1 else: self.packets_othertarget += 1
handle RC value override
def cmd_rc(self, args): '''handle RC value override''' if len(args) != 2: print("Usage: rc <channel|all> <pwmvalue>") return value = int(args[1]) if value > 65535 or value < -1: raise ValueError("PWM value must be a positive integer between 0 and 65535") if value == -1: value = 65535 channels = self.override if args[0] == 'all': for i in range(16): channels[i] = value else: channel = int(args[0]) if channel < 1 or channel > 16: print("Channel must be between 1 and 8 or 'all'") return channels[channel - 1] = value self.set_override(channels)
complete a MAVLink variable or expression
def complete_variable(text): '''complete a MAVLink variable or expression''' if text == '': return list(rline_mpstate.status.msgs.keys()) if text.endswith(":2"): suffix = ":2" text = text[:-2] else: suffix = '' try: if mavutil.evaluate_expression(text, rline_mpstate.status.msgs) is not None: return [text+suffix] except Exception as ex: pass try: m1 = re.match("^(.*?)([A-Z0-9][A-Z0-9_]*)[.]([A-Za-z0-9_]*)$", text) except Exception as ex: return [] if m1 is not None: prefix = m1.group(1) mtype = m1.group(2) fname = m1.group(3) if mtype in rline_mpstate.status.msgs: ret = [] for f in rline_mpstate.status.msgs[mtype].get_fieldnames(): if f.startswith(fname): ret.append(prefix + mtype + '.' + f + suffix) return ret return [] try: m2 = re.match("^(.*?)([A-Z0-9][A-Z0-9_]*)$", text) except Exception as ex: return [] prefix = m2.group(1) mtype = m2.group(2) ret = [] for k in list(rline_mpstate.status.msgs.keys()): if k.startswith(mtype): ret.append(prefix + k + suffix) return ret
complete using one rule
def complete_rule(rule, cmd): '''complete using one rule''' global rline_mpstate rule_components = rule.split(' ') # complete the empty string (e.g "graph <TAB><TAB>") if len(cmd) == 0: return rule_expand(rule_components[0], "") # check it matches so far for i in range(len(cmd)-1): if not rule_match(rule_components[i], cmd[i]): return [] # expand the next rule component expanded = rule_expand(rule_components[len(cmd)-1], cmd[-1]) return expanded
Return the altitude at a particular long/lat
def getAltitudeAtPoint(self, latty, longy): '''Return the altitude at a particular long/lat''' #check the bounds if self.startlongitude > 0 and (longy < self.startlongitude or longy > self.endlongitude): return -1 if self.startlongitude < 0 and (longy > self.startlongitude or longy < self.endlongitude): return -1 if self.startlatitude > 0 and (latty < self.startlatitude or longy > self.endlatitude): return -1 if self.startlatitude < 0 and (latty > self.startlatitude or longy < self.endlatitude): return -1 x = numpy.abs((latty - self.startlatitude)/self.deltalatitude) y = numpy.abs((longy - self.startlongitude)/self.deltalongitude) #do some interpolation # print("x,y", x, y) x_int = int(x) x_frac = x - int(x) y_int = int(y) y_frac = y - int(y) #print("frac", x_int, x_frac, y_int, y_frac) value00 = self.data[x_int, y_int] value10 = self.data[x_int+1, y_int] value01 = self.data[x_int, y_int+1] value11 = self.data[x_int+1, y_int+1] #print("values ", value00, value10, value01, value11) #check for null values if value00 == -99999: value00 = 0 if value10 == -99999: value10 = 0 if value01 == -99999: value01 = 0 if value11 == -99999: value11 = 0 value1 = self._avg(value00, value10, x_frac) value2 = self._avg(value01, value11, x_frac) value = self._avg(value1, value2, y_frac) return value
Creates the figure and axes for the plotting panel.
def createPlotPanel(self): '''Creates the figure and axes for the plotting panel.''' self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self,-1,self.figure) self.canvas.SetSize(wx.Size(300,300)) self.axes.axis('off') self.figure.subplots_adjust(left=0,right=1,top=1,bottom=0) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas,1,wx.EXPAND,wx.ALL) self.SetSizerAndFit(self.sizer) self.Fit()
Rescales the horizontal axes to make the lengthscales equal.
def rescaleX(self): '''Rescales the horizontal axes to make the lengthscales equal.''' self.ratio = self.figure.get_size_inches()[0]/float(self.figure.get_size_inches()[1]) self.axes.set_xlim(-self.ratio,self.ratio) self.axes.set_ylim(-1,1)
Calculates the current font size and left position for the current window.
def calcFontScaling(self): '''Calculates the current font size and left position for the current window.''' self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi self.fontSize = self.vertSize*(self.ypx/2.0) self.leftPos = self.axes.get_xlim()[0] self.rightPos = self.axes.get_xlim()[1]
Checks if the window was resized.
def checkReszie(self): '''Checks if the window was resized.''' if not self.resized: oldypx = self.ypx oldxpx = self.xpx self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi if (oldypx != self.ypx) or (oldxpx != self.xpx): self.resized = True else: self.resized = False
Adjust the value of the heading pointer.
def adjustHeadingPointer(self): '''Adjust the value of the heading pointer.''' self.headingText.set_text(str(self.heading)) self.headingText.set_size(self.fontSize)
Creates the pointer for the current heading.
def createHeadingPointer(self): '''Creates the pointer for the current heading.''' self.headingTri = patches.RegularPolygon((0.0,0.80),3,0.05,color='k',zorder=4) self.axes.add_patch(self.headingTri) self.headingText = self.axes.text(0.0,0.675,'0',color='k',size=self.fontSize,horizontalalignment='center',verticalalignment='center',zorder=4)
Creates the north pointer relative to current heading.
def createNorthPointer(self): '''Creates the north pointer relative to current heading.''' self.headingNorthTri = patches.RegularPolygon((0.0,0.80),3,0.05,color='k',zorder=4) self.axes.add_patch(self.headingNorthTri) self.headingNorthText = self.axes.text(0.0,0.675,'N',color='k',size=self.fontSize,horizontalalignment='center',verticalalignment='center',zorder=4)
Adjust the position and orientation of the north pointer.
def adjustNorthPointer(self): '''Adjust the position and orientation of the north pointer.''' self.headingNorthText.set_size(self.fontSize) headingRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,0.0,self.heading)+self.axes.transData self.headingNorthText.set_transform(headingRotate) if (self.heading > 90) and (self.heading < 270): headRot = self.heading-180 else: headRot = self.heading self.headingNorthText.set_rotation(headRot) self.headingNorthTri.set_transform(headingRotate) # Adjust if overlapping with heading pointer if (self.heading <= 10.0) or (self.heading >= 350.0): self.headingNorthText.set_text('') else: self.headingNorthText.set_text('N')
Hides/shows the given widgets.
def toggleWidgets(self,widgets): '''Hides/shows the given widgets.''' for wig in widgets: if wig.get_visible(): wig.set_visible(False) else: wig.set_visible(True)
Creates the text for roll, pitch and yaw.
def createRPYText(self): '''Creates the text for roll, pitch and yaw.''' self.rollText = self.axes.text(self.leftPos+(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0),'Roll: %.2f' % self.roll,color='w',size=self.fontSize) self.pitchText = self.axes.text(self.leftPos+(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0),'Pitch: %.2f' % self.pitch,color='w',size=self.fontSize) self.yawText = self.axes.text(self.leftPos+(self.vertSize/10.0),-0.97,'Yaw: %.2f' % self.yaw,color='w',size=self.fontSize) self.rollText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.pitchText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.yawText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
Update the locations of roll, pitch, yaw text.
def updateRPYLocations(self): '''Update the locations of roll, pitch, yaw text.''' # Locations self.rollText.set_position((self.leftPos+(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0))) self.pitchText.set_position((self.leftPos+(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0))) self.yawText.set_position((self.leftPos+(self.vertSize/10.0),-0.97)) # Font Size self.rollText.set_size(self.fontSize) self.pitchText.set_size(self.fontSize) self.yawText.set_size(self.fontSize)
Updates the displayed Roll, Pitch, Yaw Text
def updateRPYText(self): 'Updates the displayed Roll, Pitch, Yaw Text' self.rollText.set_text('Roll: %.2f' % self.roll) self.pitchText.set_text('Pitch: %.2f' % self.pitch) self.yawText.set_text('Yaw: %.2f' % self.yaw)
Creates the center pointer in the middle of the screen.
def createCenterPointMarker(self): '''Creates the center pointer in the middle of the screen.''' self.axes.add_patch(patches.Rectangle((-0.75,-self.thick),0.5,2.0*self.thick,facecolor='orange',zorder=3)) self.axes.add_patch(patches.Rectangle((0.25,-self.thick),0.5,2.0*self.thick,facecolor='orange',zorder=3)) self.axes.add_patch(patches.Circle((0,0),radius=self.thick,facecolor='orange',edgecolor='none',zorder=3))
Creates the two polygons to show the sky and ground.
def createHorizonPolygons(self): '''Creates the two polygons to show the sky and ground.''' # Sky Polygon vertsTop = [[-1,0],[-1,1],[1,1],[1,0],[-1,0]] self.topPolygon = Polygon(vertsTop,facecolor='dodgerblue',edgecolor='none') self.axes.add_patch(self.topPolygon) # Ground Polygon vertsBot = [[-1,0],[-1,-1],[1,-1],[1,0],[-1,0]] self.botPolygon = Polygon(vertsBot,facecolor='brown',edgecolor='none') self.axes.add_patch(self.botPolygon)
Updates the verticies of the patches for the ground and sky.
def calcHorizonPoints(self): '''Updates the verticies of the patches for the ground and sky.''' ydiff = math.tan(math.radians(-self.roll))*float(self.ratio) pitchdiff = self.dist10deg*(self.pitch/10.0) # Sky Polygon vertsTop = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,1),(self.ratio,1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)] self.topPolygon.set_xy(vertsTop) # Ground Polygon vertsBot = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,-1),(self.ratio,-1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)] self.botPolygon.set_xy(vertsBot)
Creates the rectangle patches for the pitch indicators.
def createPitchMarkers(self): '''Creates the rectangle patches for the pitch indicators.''' self.pitchPatches = [] # Major Lines (multiple of 10 deg) for i in [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9]: width = self.calcPitchMarkerWidth(i) currPatch = patches.Rectangle((-width/2.0,self.dist10deg*i-(self.thick/2.0)),width,self.thick,facecolor='w',edgecolor='none') self.axes.add_patch(currPatch) self.pitchPatches.append(currPatch) # Add Label for +-30 deg self.vertSize = 0.09 self.pitchLabelsLeft = [] self.pitchLabelsRight = [] i=0 for j in [-90,-60,-30,30,60,90]: self.pitchLabelsLeft.append(self.axes.text(-0.55,(j/10.0)*self.dist10deg,str(j),color='w',size=self.fontSize,horizontalalignment='center',verticalalignment='center')) self.pitchLabelsLeft[i].set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.pitchLabelsRight.append(self.axes.text(0.55,(j/10.0)*self.dist10deg,str(j),color='w',size=self.fontSize,horizontalalignment='center',verticalalignment='center')) self.pitchLabelsRight[i].set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) i += 1
Adjusts the location and orientation of pitch markers.
def adjustPitchmarkers(self): '''Adjusts the location and orientation of pitch markers.''' pitchdiff = self.dist10deg*(self.pitch/10.0) rollRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,-pitchdiff,self.roll)+self.axes.transData j=0 for i in [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9]: width = self.calcPitchMarkerWidth(i) self.pitchPatches[j].set_xy((-width/2.0,self.dist10deg*i-(self.thick/2.0)-pitchdiff)) self.pitchPatches[j].set_transform(rollRotate) j+=1 # Adjust Text Size and rotation i=0 for j in [-9,-6,-3,3,6,9]: self.pitchLabelsLeft[i].set_y(j*self.dist10deg-pitchdiff) self.pitchLabelsRight[i].set_y(j*self.dist10deg-pitchdiff) self.pitchLabelsLeft[i].set_size(self.fontSize) self.pitchLabelsRight[i].set_size(self.fontSize) self.pitchLabelsLeft[i].set_rotation(self.roll) self.pitchLabelsRight[i].set_rotation(self.roll) self.pitchLabelsLeft[i].set_transform(rollRotate) self.pitchLabelsRight[i].set_transform(rollRotate) i += 1
Creates the text for airspeed, altitude and climb rate.
def createAARText(self): '''Creates the text for airspeed, altitude and climb rate.''' self.airspeedText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0),'AS: %.1f m/s' % self.airspeed,color='w',size=self.fontSize,ha='right') self.altitudeText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0),'ALT: %.1f m ' % self.relAlt,color='w',size=self.fontSize,ha='right') self.climbRateText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97,'CR: %.1f m/s' % self.climbRate,color='w',size=self.fontSize,ha='right') self.airspeedText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.altitudeText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.climbRateText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
Update the locations of airspeed, altitude and Climb rate.
def updateAARLocations(self): '''Update the locations of airspeed, altitude and Climb rate.''' # Locations self.airspeedText.set_position((self.rightPos-(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0))) self.altitudeText.set_position((self.rightPos-(self.vertSize/10.0),-0.97+self.vertSize-(0.5*self.vertSize/10.0))) self.climbRateText.set_position((self.rightPos-(self.vertSize/10.0),-0.97)) # Font Size self.airspeedText.set_size(self.fontSize) self.altitudeText.set_size(self.fontSize) self.climbRateText.set_size(self.fontSize)
Updates the displayed airspeed, altitude, climb rate Text
def updateAARText(self): 'Updates the displayed airspeed, altitude, climb rate Text' self.airspeedText.set_text('AR: %.1f m/s' % self.airspeed) self.altitudeText.set_text('ALT: %.1f m ' % self.relAlt) self.climbRateText.set_text('CR: %.1f m/s' % self.climbRate)
Creates the bar to display current battery percentage.
def createBatteryBar(self): '''Creates the bar to display current battery percentage.''' self.batOutRec = patches.Rectangle((self.rightPos-(1.3+self.rOffset)*self.batWidth,1.0-(0.1+1.0+(2*0.075))*self.batHeight),self.batWidth*1.3,self.batHeight*1.15,facecolor='darkgrey',edgecolor='none') self.batInRec = patches.Rectangle((self.rightPos-(self.rOffset+1+0.15)*self.batWidth,1.0-(0.1+1+0.075)*self.batHeight),self.batWidth,self.batHeight,facecolor='lawngreen',edgecolor='none') self.batPerText = self.axes.text(self.rightPos - (self.rOffset+0.65)*self.batWidth,1-(0.1+1+(0.075+0.15))*self.batHeight,'%.f' % self.batRemain,color='w',size=self.fontSize,ha='center',va='top') self.batPerText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.voltsText = self.axes.text(self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-(0.1+0.05+0.075)*self.batHeight,'%.1f V' % self.voltage,color='w',size=self.fontSize,ha='right',va='top') self.ampsText = self.axes.text(self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-self.vertSize-(0.1+0.05+0.1+0.075)*self.batHeight,'%.1f A' % self.current,color='w',size=self.fontSize,ha='right',va='top') self.voltsText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.ampsText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')]) self.axes.add_patch(self.batOutRec) self.axes.add_patch(self.batInRec)
Updates the position and values of the battery bar.
def updateBatteryBar(self): '''Updates the position and values of the battery bar.''' # Bar self.batOutRec.set_xy((self.rightPos-(1.3+self.rOffset)*self.batWidth,1.0-(0.1+1.0+(2*0.075))*self.batHeight)) self.batInRec.set_xy((self.rightPos-(self.rOffset+1+0.15)*self.batWidth,1.0-(0.1+1+0.075)*self.batHeight)) self.batPerText.set_position((self.rightPos - (self.rOffset+0.65)*self.batWidth,1-(0.1+1+(0.075+0.15))*self.batHeight)) self.batPerText.set_fontsize(self.fontSize) self.voltsText.set_text('%.1f V' % self.voltage) self.ampsText.set_text('%.1f A' % self.current) self.voltsText.set_position((self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-(0.1+0.05)*self.batHeight)) self.ampsText.set_position((self.rightPos-(self.rOffset+1.3+0.2)*self.batWidth,1-self.vertSize-(0.1+0.05+0.1)*self.batHeight)) self.voltsText.set_fontsize(self.fontSize) self.ampsText.set_fontsize(self.fontSize) if self.batRemain >= 0: self.batPerText.set_text(int(self.batRemain)) self.batInRec.set_height(self.batRemain*self.batHeight/100.0) if self.batRemain/100.0 > 0.5: self.batInRec.set_facecolor('lawngreen') elif self.batRemain/100.0 <= 0.5 and self.batRemain/100.0 > 0.2: self.batInRec.set_facecolor('yellow') elif self.batRemain/100.0 <= 0.2 and self.batRemain >= 0.0: self.batInRec.set_facecolor('r') elif self.batRemain == -1: self.batInRec.set_height(self.batHeight) self.batInRec.set_facecolor('k')
Creates the mode and arm state text.
def createStateText(self): '''Creates the mode and arm state text.''' self.modeText = self.axes.text(self.leftPos+(self.vertSize/10.0),0.97,'UNKNOWN',color='grey',size=1.5*self.fontSize,ha='left',va='top') self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='black')])
Updates the mode and colours red or green depending on arm state.
def updateStateText(self): '''Updates the mode and colours red or green depending on arm state.''' self.modeText.set_position((self.leftPos+(self.vertSize/10.0),0.97)) self.modeText.set_text(self.mode) self.modeText.set_size(1.5*self.fontSize) if self.armed: self.modeText.set_color('red') self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='yellow')]) elif (self.armed == False): self.modeText.set_color('lightgreen') self.modeText.set_bbox(None) self.modeText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='black')]) else: # Fall back if unknown self.modeText.set_color('grey') self.modeText.set_bbox(None) self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='black')])
Creates the text for the current and final waypoint, and the distance to the new waypoint.
def createWPText(self): '''Creates the text for the current and final waypoint, and the distance to the new waypoint.''' self.wpText = self.axes.text(self.leftPos+(1.5*self.vertSize/10.0),0.97-(1.5*self.vertSize)+(0.5*self.vertSize/10.0),'0/0\n(0 m, 0 s)',color='w',size=self.fontSize,ha='left',va='top') self.wpText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='black')])
Updates the current waypoint and distance to it.
def updateWPText(self): '''Updates the current waypoint and distance to it.''' self.wpText.set_position((self.leftPos+(1.5*self.vertSize/10.0),0.97-(1.5*self.vertSize)+(0.5*self.vertSize/10.0))) self.wpText.set_size(self.fontSize) if type(self.nextWPTime) is str: self.wpText.set_text('%.f/%.f\n(%.f m, ~ s)' % (self.currentWP,self.finalWP,self.wpDist)) else: self.wpText.set_text('%.f/%.f\n(%.f m, %.f s)' % (self.currentWP,self.finalWP,self.wpDist,self.nextWPTime))
Creates the waypoint pointer relative to current heading.
def createWPPointer(self): '''Creates the waypoint pointer relative to current heading.''' self.headingWPTri = patches.RegularPolygon((0.0,0.55),3,0.05,facecolor='lime',zorder=4,ec='k') self.axes.add_patch(self.headingWPTri) self.headingWPText = self.axes.text(0.0,0.45,'1',color='lime',size=self.fontSize,horizontalalignment='center',verticalalignment='center',zorder=4) self.headingWPText.set_path_effects([PathEffects.withStroke(linewidth=1,foreground='k')])
Adjust the position and orientation of the waypoint pointer.
def adjustWPPointer(self): '''Adjust the position and orientation of the waypoint pointer.''' self.headingWPText.set_size(self.fontSize) headingRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,0.0,-self.wpBearing+self.heading)+self.axes.transData self.headingWPText.set_transform(headingRotate) angle = self.wpBearing - self.heading if angle < 0: angle += 360 if (angle > 90) and (angle < 270): headRot = angle-180 else: headRot = angle self.headingWPText.set_rotation(-headRot) self.headingWPTri.set_transform(headingRotate) self.headingWPText.set_text('%.f' % (angle))
Creates the altitude history plot.
def createAltHistoryPlot(self): '''Creates the altitude history plot.''' self.altHistRect = patches.Rectangle((self.leftPos+(self.vertSize/10.0),-0.25),0.5,0.5,facecolor='grey',edgecolor='none',alpha=0.4,zorder=4) self.axes.add_patch(self.altHistRect) self.altPlot, = self.axes.plot([self.leftPos+(self.vertSize/10.0),self.leftPos+(self.vertSize/10.0)+0.5],[0.0,0.0],color='k',marker=None,zorder=4) self.altMarker, = self.axes.plot(self.leftPos+(self.vertSize/10.0)+0.5,0.0,marker='o',color='k',zorder=4) self.altText2 = self.axes.text(self.leftPos+(4*self.vertSize/10.0)+0.5,0.0,'%.f m' % self.relAlt,color='k',size=self.fontSize,ha='left',va='center',zorder=4)
Updates the altitude history plot.
def updateAltHistory(self): '''Updates the altitude history plot.''' self.altHist.append(self.relAlt) self.timeHist.append(self.relAltTime) # Delete entries older than x seconds histLim = 10 currentTime = time.time() point = 0 for i in range(0,len(self.timeHist)): if (self.timeHist[i] > (currentTime - 10.0)): break # Remove old entries self.altHist = self.altHist[i:] self.timeHist = self.timeHist[i:] # Transform Data x = [] y = [] tmin = min(self.timeHist) tmax = max(self.timeHist) x1 = self.leftPos+(self.vertSize/10.0) y1 = -0.25 altMin = 0 altMax = max(self.altHist) # Keep alt max for whole mission if altMax > self.altMax: self.altMax = altMax else: altMax = self.altMax if tmax != tmin: mx = 0.5/(tmax-tmin) else: mx = 0.0 if altMax != altMin: my = 0.5/(altMax-altMin) else: my = 0.0 for t in self.timeHist: x.append(mx*(t-tmin)+x1) for alt in self.altHist: val = my*(alt-altMin)+y1 # Crop extreme noise if val < -0.25: val = -0.25 elif val > 0.25: val = 0.25 y.append(val) # Display Plot self.altHistRect.set_x(self.leftPos+(self.vertSize/10.0)) self.altPlot.set_data(x,y) self.altMarker.set_data(self.leftPos+(self.vertSize/10.0)+0.5,val) self.altText2.set_position((self.leftPos+(4*self.vertSize/10.0)+0.5,val)) self.altText2.set_size(self.fontSize) self.altText2.set_text('%.f m' % self.relAlt)
To adjust text and positions on rescaling the window when resized.
def on_idle(self, event): '''To adjust text and positions on rescaling the window when resized.''' # Check for resize self.checkReszie() if self.resized: # Fix Window Scales self.rescaleX() self.calcFontScaling() # Recalculate Horizon Polygons self.calcHorizonPoints() # Update Roll, Pitch, Yaw Text Locations self.updateRPYLocations() # Update Airpseed, Altitude, Climb Rate Locations self.updateAARLocations() # Update Pitch Markers self.adjustPitchmarkers() # Update Heading and North Pointer self.adjustHeadingPointer() self.adjustNorthPointer() # Update Battery Bar self.updateBatteryBar() # Update Mode and State self.updateStateText() # Update Waypoint Text self.updateWPText() # Adjust Waypoint Pointer self.adjustWPPointer() # Update History Plot self.updateAltHistory() # Update Matplotlib Plot self.canvas.draw() self.canvas.Refresh() self.resized = False time.sleep(0.05)
Main Loop.
def on_timer(self, event): '''Main Loop.''' state = self.state self.loopStartTime = time.time() if state.close_event.wait(0.001): self.timer.Stop() self.Destroy() return # Check for resizing self.checkReszie() if self.resized: self.on_idle(0) # Get attitude information while state.child_pipe_recv.poll(): objList = state.child_pipe_recv.recv() for obj in objList: self.calcFontScaling() if isinstance(obj,Attitude): self.oldRoll = self.roll self.pitch = obj.pitch*180/math.pi self.roll = obj.roll*180/math.pi self.yaw = obj.yaw*180/math.pi # Update Roll, Pitch, Yaw Text Text self.updateRPYText() # Recalculate Horizon Polygons self.calcHorizonPoints() # Update Pitch Markers self.adjustPitchmarkers() elif isinstance(obj,VFR_HUD): self.heading = obj.heading self.airspeed = obj.airspeed self.climbRate = obj.climbRate # Update Airpseed, Altitude, Climb Rate Locations self.updateAARText() # Update Heading North Pointer self.adjustHeadingPointer() self.adjustNorthPointer() elif isinstance(obj,Global_Position_INT): self.relAlt = obj.relAlt self.relAltTime = obj.curTime # Update Airpseed, Altitude, Climb Rate Locations self.updateAARText() # Update Altitude History self.updateAltHistory() elif isinstance(obj,BatteryInfo): self.voltage = obj.voltage self.current = obj.current self.batRemain = obj.batRemain # Update Battery Bar self.updateBatteryBar() elif isinstance(obj,FlightState): self.mode = obj.mode self.armed = obj.armState # Update Mode and Arm State Text self.updateStateText() elif isinstance(obj,WaypointInfo): self.currentWP = obj.current self.finalWP = obj.final self.wpDist = obj.currentDist self.nextWPTime = obj.nextWPTime if obj.wpBearing < 0.0: self.wpBearing = obj.wpBearing + 360 else: self.wpBearing = obj.wpBearing # Update waypoint text self.updateWPText() # Adjust Waypoint Pointer self.adjustWPPointer() elif isinstance(obj, FPS): # Update fps target self.fps = obj.fps # Quit Drawing if too early if (time.time() > self.nextTime): # Update Matplotlib Plot self.canvas.draw() self.canvas.Refresh() self.Refresh() self.Update() # Calculate next frame time if (self.fps > 0): fpsTime = 1/self.fps self.nextTime = fpsTime + self.loopStartTime else: self.nextTime = time.time()
To adjust the distance between pitch markers.
def on_KeyPress(self,event): '''To adjust the distance between pitch markers.''' if event.GetKeyCode() == wx.WXK_UP: self.dist10deg += 0.1 print('Dist per 10 deg: %.1f' % self.dist10deg) elif event.GetKeyCode() == wx.WXK_DOWN: self.dist10deg -= 0.1 if self.dist10deg <= 0: self.dist10deg = 0.1 print('Dist per 10 deg: %.1f' % self.dist10deg) # Toggle Widgets elif event.GetKeyCode() == 49: # 1 widgets = [self.modeText,self.wpText] self.toggleWidgets(widgets) elif event.GetKeyCode() == 50: # 2 widgets = [self.batOutRec,self.batInRec,self.voltsText,self.ampsText,self.batPerText] self.toggleWidgets(widgets) elif event.GetKeyCode() == 51: # 3 widgets = [self.rollText,self.pitchText,self.yawText] self.toggleWidgets(widgets) elif event.GetKeyCode() == 52: # 4 widgets = [self.airspeedText,self.altitudeText,self.climbRateText] self.toggleWidgets(widgets) elif event.GetKeyCode() == 53: # 5 widgets = [self.altHistRect,self.altPlot,self.altMarker,self.altText2] self.toggleWidgets(widgets) elif event.GetKeyCode() == 54: # 6 widgets = [self.headingTri,self.headingText,self.headingNorthTri,self.headingNorthText,self.headingWPTri,self.headingWPText] self.toggleWidgets(widgets) # Update Matplotlib Plot self.canvas.draw() self.canvas.Refresh() self.Refresh() self.Update()
Select option for Tune Pot on Channel 6 (quadcopter only)
def cmd_tuneopt(self, args): '''Select option for Tune Pot on Channel 6 (quadcopter only)''' usage = "usage: tuneopt <set|show|reset|list>" if self.mpstate.vehicle_type != 'copter': print("This command is only available for copter") return if len(args) < 1: print(usage) return if args[0].lower() == 'reset': self.param_set('TUNE', '0') elif args[0].lower() == 'set': if len(args) < 4: print('Usage: tuneopt set OPTION LOW HIGH') return option = self.tune_option_validate(args[1]) if not option: print('Invalid Tune option: ' + args[1]) return low = args[2] high = args[3] self.param_set('TUNE', tune_options[option]) self.param_set('TUNE_LOW', float(low) * 1000) self.param_set('TUNE_HIGH', float(high) * 1000) elif args[0].lower() == 'show': self.tune_show() elif args[0].lower() == 'list': print("Options available:") for s in sorted(tune_options.keys()): print(' ' + s) else: print(usage)
fence loader by sysid
def fenceloader(self): '''fence loader by sysid''' if not self.target_system in self.fenceloader_by_sysid: self.fenceloader_by_sysid[self.target_system] = mavwp.MAVFenceLoader() return self.fenceloader_by_sysid[self.target_system]
handle and incoming mavlink packet
def mavlink_packet(self, m): '''handle and incoming mavlink packet''' if m.get_type() == "FENCE_STATUS": self.last_fence_breach = m.breach_time self.last_fence_status = m.breach_status elif m.get_type() in ['SYS_STATUS']: bits = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE present = ((m.onboard_control_sensors_present & bits) == bits) if self.present == False and present == True: self.say("fence present") elif self.present == True and present == False: self.say("fence removed") self.present = present enabled = ((m.onboard_control_sensors_enabled & bits) == bits) if self.enabled == False and enabled == True: self.say("fence enabled") elif self.enabled == True and enabled == False: self.say("fence disabled") self.enabled = enabled healthy = ((m.onboard_control_sensors_health & bits) == bits) if self.healthy == False and healthy == True: self.say("fence OK") elif self.healthy == True and healthy == False: self.say("fence breach") self.healthy = healthy #console output for fence: if not self.present: self.console.set_status('Fence', 'FEN', row=0, fg='black') elif self.enabled == False: self.console.set_status('Fence', 'FEN', row=0, fg='grey') elif self.enabled == True and self.healthy == True: self.console.set_status('Fence', 'FEN', row=0, fg='green') elif self.enabled == True and self.healthy == False: self.console.set_status('Fence', 'FEN', row=0, fg='red')
load fence points from a file
def load_fence(self, filename): '''load fence points from a file''' try: self.fenceloader.target_system = self.target_system self.fenceloader.target_component = self.target_component self.fenceloader.load(filename.strip('"')) except Exception as msg: print("Unable to load %s - %s" % (filename, msg)) return print("Loaded %u geo-fence points from %s" % (self.fenceloader.count(), filename)) self.send_fence()
list fence points, optionally saving to a file
def list_fence(self, filename): '''list fence points, optionally saving to a file''' self.fenceloader.clear() count = self.get_mav_param('FENCE_TOTAL', 0) if count == 0: print("No geo-fence points") return for i in range(int(count)): p = self.fetch_fence_point(i) if p is None: return self.fenceloader.add(p) if filename is not None: try: self.fenceloader.save(filename.strip('"')) except Exception as msg: print("Unable to save %s - %s" % (filename, msg)) return print("Saved %u geo-fence points to %s" % (self.fenceloader.count(), filename)) else: for i in range(self.fenceloader.count()): p = self.fenceloader.point(i) self.console.writeln("lat=%f lng=%f" % (p.lat, p.lng)) if self.status.logdir is not None: fname = 'fence.txt' if self.target_system > 1: fname = 'fence_%u.txt' % self.target_system fencetxt = os.path.join(self.status.logdir, fname) self.fenceloader.save(fencetxt.strip('"')) print("Saved fence to %s" % fencetxt) self.have_list = True
display fft for raw ACC data in logfile
def mavfft_display(logfile, condition=None): '''display fft for raw ACC data in logfile''' '''object to store data about a single FFT plot''' class PlotData(object): def __init__(self, ffth): self.seqno = -1 self.fftnum = ffth.N self.sensor_type = ffth.type self.instance = ffth.instance self.sample_rate_hz = ffth.smp_rate self.multiplier = ffth.mul self.data = {} self.data["X"] = [] self.data["Y"] = [] self.data["Z"] = [] self.holes = False self.freq = None def add_fftd(self, fftd): if fftd.N != self.fftnum: print("Skipping ISBD with wrong fftnum (%u vs %u)\n" % (fftd.fftnum, self.fftnum)) return if self.holes: print("Skipping ISBD(%u) for ISBH(%u) with holes in it" % (fftd.seqno, self.fftnum)) return if fftd.seqno != self.seqno+1: print("ISBH(%u) has holes in it" % fftd.N) self.holes = True return self.seqno += 1 self.data["X"].extend(fftd.x) self.data["Y"].extend(fftd.y) self.data["Z"].extend(fftd.z) def prefix(self): if self.sensor_type == 0: return "Accel" elif self.sensor_type == 1: return "Gyro" else: return "?Unknown Sensor Type?" def tag(self): return str(self) def __str__(self): return "%s[%u]" % (self.prefix(), self.instance) print("Processing log for ISBH and ISBD messages") things_to_plot = [] plotdata = None start_time = time.time() mlog = mavutil.mavlink_connection(logfile) while True: m = mlog.recv_match(type=['ISBH','ISBD'],condition=condition) if m is None: break msg_type = m.get_type() if msg_type == "ISBH": if plotdata is not None: # close off previous data collection things_to_plot.append(plotdata) # initialise plot-data collection object plotdata = PlotData(m) continue if msg_type == "ISBD": if plotdata is None: continue plotdata.add_fftd(m) if len(things_to_plot) == 0: print("No FFT data. Did you set INS_LOG_BAT_MASK?") return time_delta = time.time() - start_time print("Extracted %u fft data sets" % len(things_to_plot)) sum_fft = {} freqmap = {} count = 0 first_freq = None for thing_to_plot in things_to_plot: for axis in [ "X","Y","Z" ]: d = numpy.array(thing_to_plot.data[axis])/float(thing_to_plot.multiplier) if len(d) == 0: print("No data?!?!?!") continue avg = numpy.sum(d) / len(d) d -= avg d_fft = numpy.fft.rfft(d) if thing_to_plot.tag() not in sum_fft: sum_fft[thing_to_plot.tag()] = { "X": 0, "Y": 0, "Z": 0 } sum_fft[thing_to_plot.tag()][axis] = numpy.add(sum_fft[thing_to_plot.tag()][axis], d_fft) count += 1 freq = numpy.fft.rfftfreq(len(d), 1.0/thing_to_plot.sample_rate_hz) freqmap[thing_to_plot.tag()] = freq for sensor in sum_fft: pylab.figure(str(sensor)) for axis in [ "X","Y","Z" ]: pylab.plot(freqmap[sensor], numpy.abs(sum_fft[sensor][axis]/count), label=axis) pylab.legend(loc='upper right') pylab.xlabel('Hz') pylab.show()
set the currently displayed image
def set_image(self, img, bgr=False): '''set the currently displayed image''' if not self.is_alive(): return if not hasattr(img, 'shape'): img = np.asarray(img[:,:]) if bgr: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.in_queue.put(MPImageData(img))
check for events, returning one event
def poll(self): '''check for events, returning one event''' if self.out_queue.qsize() <= 0: return None evt = self.out_queue.get() while isinstance(evt, win_layout.WinLayout): win_layout.set_layout(evt, self.set_layout) if self.out_queue.qsize() == 0: return None evt = self.out_queue.get() return evt
check for events a list of events
def events(self): '''check for events a list of events''' ret = [] while True: e = self.poll() if e is None: break ret.append(e) return ret
prevent the main loop spinning too fast
def on_idle(self, event): '''prevent the main loop spinning too fast''' state = self.state now = time.time() if now - self.last_layout_send > 1: self.last_layout_send = now state.out_queue.put(win_layout.get_wx_window_layout(self)) time.sleep(0.1)
the redraw timer ensures we show new map tiles as they are downloaded
def on_redraw_timer(self, event): '''the redraw timer ensures we show new map tiles as they are downloaded''' state = self.state while state.in_queue.qsize(): try: obj = state.in_queue.get() except Exception: time.sleep(0.05) return if isinstance(obj, MPImageData): with warnings.catch_warnings(): warnings.simplefilter('ignore') img = wx.EmptyImage(obj.width, obj.height) img.SetData(obj.data) self.img = img self.need_redraw = True if state.auto_size: client_area = state.frame.GetClientSize() total_area = state.frame.GetSize() bx = max(total_area.x - client_area.x,0) by = max(total_area.y - client_area.y,0) state.frame.SetSize(wx.Size(obj.width+bx, obj.height+by)) if isinstance(obj, MPImageTitle): state.frame.SetTitle(obj.title) if isinstance(obj, MPImageRecenter): self.on_recenter(obj.location) if isinstance(obj, MPImageMenu): self.set_menu(obj.menu) if isinstance(obj, MPImagePopupMenu): self.set_popup_menu(obj.menu) if isinstance(obj, MPImageBrightness): state.brightness = obj.brightness self.need_redraw = True if isinstance(obj, MPImageFullSize): self.full_size() if isinstance(obj, MPImageFitToWindow): self.fit_to_window() if isinstance(obj, win_layout.WinLayout): win_layout.set_wx_window_layout(state.frame, obj) if self.need_redraw: self.redraw()
handle mouse wheel zoom changes
def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' state = self.state if not state.can_zoom: return mousepos = self.image_coordinates(event.GetPosition()) rotation = event.GetWheelRotation() / event.GetWheelDelta() oldzoom = self.zoom if rotation > 0: self.zoom /= 1.0/(1.1 * rotation) elif rotation < 0: self.zoom /= 1.1 * (-rotation) if self.zoom > 10: self.zoom = 10 elif self.zoom < 0.1: self.zoom = 0.1 if oldzoom < 1 and self.zoom > 1: self.zoom = 1 if oldzoom > 1 and self.zoom < 1: self.zoom = 1 client_area = state.frame.GetClientSize() fit_window_zoom_level = min(float(client_area.x) / self.img.GetWidth(), float(client_area.y) / self.img.GetHeight()) if self.zoom < fit_window_zoom_level: self.zoom = fit_window_zoom_level self.need_redraw = True new = self.image_coordinates(event.GetPosition()) # adjust dragpos so the zoom doesn't change what pixel is under the mouse self.dragpos = wx.Point(self.dragpos.x - (new.x-mousepos.x), self.dragpos.y - (new.y-mousepos.y)) self.limit_dragpos()
find an object to be modified
def find_object(self, key, layers): '''find an object to be modified''' state = self.state if layers is None or layers == '': layers = state.layers.keys() for layer in layers: if key in state.layers[layer]: return state.layers[layer][key] return None
add an object to a layer
def add_object(self, obj): '''add an object to a layer''' state = self.state if not obj.layer in state.layers: # its a new layer state.layers[obj.layer] = {} state.layers[obj.layer][obj.key] = obj state.need_redraw = True if (not self.legend_checkbox_menuitem_added and isinstance(obj, SlipFlightModeLegend)): self.add_legend_checkbox_menuitem() self.legend_checkbox_menuitem_added = True self.SetMenuBar(self.menu.wx_menu())
prevent the main loop spinning too fast
def on_idle(self, event): '''prevent the main loop spinning too fast''' state = self.state if state.close_window.acquire(False): self.state.app.ExitMainLoop() now = time.time() if now - self.last_layout_send > 1: self.last_layout_send = now state.event_queue.put(win_layout.get_wx_window_layout(self)) # receive any display objects from the parent obj = None while not state.object_queue.empty(): obj = state.object_queue.get() if isinstance(obj, win_layout.WinLayout): win_layout.set_wx_window_layout(self, obj) if isinstance(obj, SlipObject): self.add_object(obj) if isinstance(obj, SlipPosition): # move an object object = self.find_object(obj.key, obj.layer) if object is not None: object.update_position(obj) if getattr(object, 'follow', False): self.follow(object) if obj.label is not None: object.label = obj.label if obj.colour is not None: object.colour = obj.colour state.need_redraw = True if isinstance(obj, SlipDefaultPopup): state.default_popup = obj if isinstance(obj, SlipInformation): # see if its a existing one or a new one if obj.key in state.info: # print('update %s' % str(obj.key)) state.info[obj.key].update(obj) else: # print('add %s' % str(obj.key)) state.info[obj.key] = obj state.need_redraw = True if isinstance(obj, SlipCenter): # move center (lat,lon) = obj.latlon state.panel.re_center(state.width/2, state.height/2, lat, lon) state.need_redraw = True if isinstance(obj, SlipZoom): # change zoom state.panel.set_ground_width(obj.ground_width) state.need_redraw = True if isinstance(obj, SlipFollow): # enable/disable follow state.follow = obj.enable if isinstance(obj, SlipFollowObject): # enable/disable follow on an object for layer in state.layers: if obj.key in state.layers[layer]: if hasattr(state.layers[layer][obj.key], 'follow'): state.layers[layer][obj.key].follow = obj.enable if isinstance(obj, SlipBrightness): # set map brightness state.brightness = obj.brightness state.need_redraw = True if isinstance(obj, SlipClearLayer): # remove all objects from a layer if obj.layer in state.layers: state.layers.pop(obj.layer) state.need_redraw = True if isinstance(obj, SlipRemoveObject): # remove an object by key for layer in state.layers: if obj.key in state.layers[layer]: state.layers[layer].pop(obj.key) state.need_redraw = True if isinstance(obj, SlipHideObject): # hide an object by key for layer in state.layers: if obj.key in state.layers[layer]: state.layers[layer][obj.key].set_hidden(obj.hide) state.need_redraw = True if obj is None: time.sleep(0.05)
set ground width of view
def set_ground_width(self, ground_width): '''set ground width of view''' state = self.state state.ground_width = ground_width state.panel.re_center(state.width/2, state.height/2, state.lat, state.lon)
draw objects on the image
def draw_objects(self, objects, bounds, img): '''draw objects on the image''' keys = sorted(objects.keys()) for k in keys: obj = objects[k] if not self.state.legend and isinstance(obj, SlipFlightModeLegend): continue bounds2 = obj.bounds() if bounds2 is None or mp_util.bounds_overlap(bounds, bounds2): obj.draw(img, self.pixmapper, bounds)
redraw the map with current settings
def redraw_map(self): '''redraw the map with current settings''' state = self.state view_same = (self.last_view is not None and self.map_img is not None and self.last_view == self.current_view()) if view_same and not state.need_redraw: return # get the new map self.map_img = state.mt.area_to_image(state.lat, state.lon, state.width, state.height, state.ground_width) if state.brightness != 0: # valid state.brightness range is [-255, 255] brightness = np.uint8(np.abs(state.brightness)) if state.brightness > 0: self.map_img = np.where((255 - self.map_img) < brightness, 255, self.map_img + brightness) else: self.map_img = np.where((255 + self.map_img) < brightness, 0, self.map_img - brightness) # find display bounding box (lat2,lon2) = self.coordinates(state.width-1, state.height-1) bounds = (lat2, state.lon, state.lat-lat2, lon2-state.lon) # get the image img = self.map_img.copy() # possibly draw a grid if state.grid: SlipGrid('grid', layer=3, linewidth=1, colour=(255,255,0)).draw(img, self.pixmapper, bounds) # draw layer objects keys = state.layers.keys() keys = sorted(list(keys)) for k in keys: self.draw_objects(state.layers[k], bounds, img) # draw information objects for key in state.info: state.info[key].draw(state.panel, state.panel.information) # display the image self.imagePanel.set_image(img) self.update_position() self.mainSizer.Fit(self) self.Refresh() self.last_view = self.current_view() self.SetFocus() state.need_redraw = False
handle mouse wheel zoom changes
def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' rotation = event.GetWheelRotation() / event.GetWheelDelta() if rotation > 0: zoom = 1.0/(1.1 * rotation) elif rotation < 0: zoom = 1.1 * (-rotation) self.change_zoom(zoom) self.redraw_map()
show popup menu for an object
def show_popup(self, selected, pos): '''show popup menu for an object''' state = self.state if selected.popup_menu is not None: import copy popup_menu = selected.popup_menu if state.default_popup is not None and state.default_popup.combine: popup_menu = copy.deepcopy(popup_menu) popup_menu.add(MPMenuSeparator()) popup_menu.combine(state.default_popup.popup) wx_menu = popup_menu.wx_menu() state.frame.PopupMenu(wx_menu, pos)
handle mouse events
def on_mouse(self, event): '''handle mouse events''' state = self.state pos = event.GetPosition() if event.Leaving(): self.mouse_pos = None else: self.mouse_pos = pos self.update_position() if hasattr(event, 'ButtonIsDown'): any_button_down = event.ButtonIsDown(wx.MOUSE_BTN_ANY) left_button_down = event.ButtonIsDown(wx.MOUSE_BTN_LEFT) right_button_down = event.ButtonIsDown(wx.MOUSE_BTN_RIGHT) else: left_button_down = event.leftIsDown right_button_down = event.rightIsDown any_button_down = left_button_down or right_button_down if any_button_down or event.ButtonUp(): # send any event with a mouse button to the parent latlon = self.coordinates(pos.x, pos.y) selected = self.selected_objects(pos) state.event_queue.put(SlipMouseEvent(latlon, event, selected)) if event.RightDown(): state.popup_object = None state.popup_latlon = None if len(selected) > 0: obj = state.layers[selected[0].layer][selected[0].objkey] if obj.popup_menu is not None: state.popup_object = obj state.popup_latlon = latlon self.show_popup(obj, pos) state.popup_started = True if not state.popup_started and state.default_popup is not None: state.popup_latlon = latlon self.show_default_popup(pos) state.popup_started = True if not right_button_down: state.popup_started = False if event.LeftDown() or event.RightDown(): self.mouse_down = pos self.last_click_pos = self.click_pos self.click_pos = self.coordinates(pos.x, pos.y) if event.Dragging() and left_button_down: # drag map to new position newpos = pos if self.mouse_down and newpos: dx = (self.mouse_down.x - newpos.x) dy = -(self.mouse_down.y - newpos.y) pdist = math.sqrt(dx**2 + dy**2) if pdist > state.drag_step: bearing = math.degrees(math.atan2(dx, dy)) distance = (state.ground_width/float(state.width)) * pdist newlatlon = mp_util.gps_newpos(state.lat, state.lon, bearing, distance) (state.lat, state.lon) = newlatlon self.mouse_down = newpos self.redraw_map()
child process - this holds all the GUI elements
def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() import matplotlib, platform if platform.system() != "Darwin": # on MacOS we can't set WxAgg here as it conflicts with the MacOS version matplotlib.use('WXAgg') from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx app = wx.App(False) from MAVProxy.modules.lib import live_graph_ui app.frame = live_graph_ui.GraphFrame(state=self) app.frame.Show() app.MainLoop()
watch a mavlink packet pattern
def cmd_watch(args): '''watch a mavlink packet pattern''' if len(args) == 0: mpstate.status.watch = None return mpstate.status.watch = args print("Watching %s" % mpstate.status.watch)
load a module
def load_module(modname, quiet=False, **kwargs): '''load a module''' modpaths = ['MAVProxy.modules.mavproxy_%s' % modname, modname] for (m,pm) in mpstate.modules: if m.name == modname and not modname in mpstate.multi_instance: if not quiet: print("module %s already loaded" % modname) # don't report an error return True ex = None for modpath in modpaths: try: m = import_package(modpath) reload(m) module = m.init(mpstate, **kwargs) if isinstance(module, mp_module.MPModule): mpstate.modules.append((module, m)) if not quiet: if kwargs: print("Loaded module %s with kwargs = %s" % (modname, kwargs)) else: print("Loaded module %s" % (modname,)) return True else: ex = "%s.init did not return a MPModule instance" % modname break except ImportError as msg: ex = msg if mpstate.settings.moddebug > 1: import traceback print(traceback.format_exc()) help_traceback = "" if mpstate.settings.moddebug < 3: help_traceback = " Use 'set moddebug 3' in the MAVProxy console to enable traceback" print("Failed to load module: %s.%s" % (ex, help_traceback)) return False
module commands
def cmd_module(args): '''module commands''' usage = "usage: module <list|load|reload|unload>" if len(args) < 1: print(usage) return if args[0] == "list": for (m,pm) in mpstate.modules: print("%s: %s" % (m.name, m.description)) elif args[0] == "load": if len(args) < 2: print("usage: module load <name>") return (modname, kwargs) = generate_kwargs(args[1]) try: load_module(modname, **kwargs) except TypeError as ex: print(ex) print("%s module does not support keyword arguments"% modname) return elif args[0] == "reload": if len(args) < 2: print("usage: module reload <name>") return (modname, kwargs) = generate_kwargs(args[1]) pmodule = None for (m,pm) in mpstate.modules: if m.name == modname: pmodule = pm if pmodule is None: print("Module %s not loaded" % modname) return if unload_module(modname): import zipimport try: reload(pmodule) except ImportError: clear_zipimport_cache() reload(pmodule) try: if load_module(modname, quiet=True, **kwargs): print("Reloaded module %s" % modname) except TypeError: print("%s module does not support keyword arguments" % modname) elif args[0] == "unload": if len(args) < 2: print("usage: module unload <name>") return modname = os.path.basename(args[1]) unload_module(modname) else: print(usage)
see http://stackoverflow.com/questions/6868382/python-shlex-split-ignore-single-quotes
def shlex_quotes(value): '''see http://stackoverflow.com/questions/6868382/python-shlex-split-ignore-single-quotes''' lex = shlex.shlex(value) lex.quotes = '"' lex.whitespace_split = True lex.commenters = '' return list(lex)
process packets from MAVLink slaves, forwarding to the master
def process_mavlink(slave): '''process packets from MAVLink slaves, forwarding to the master''' try: buf = slave.recv() except socket.error: return try: global mavversion if slave.first_byte and mavversion is None: slave.auto_mavlink_version(buf) msgs = slave.mav.parse_buffer(buf) except mavutil.mavlink.MAVError as e: mpstate.console.error("Bad MAVLink slave message from %s: %s" % (slave.address, e.message)) return if msgs is None: return if mpstate.settings.mavfwd and not mpstate.status.setup_mode: for m in msgs: mpstate.master().write(m.get_msgbuf()) if mpstate.status.watch: for msg_type in mpstate.status.watch: if fnmatch.fnmatch(m.get_type().upper(), msg_type.upper()): mpstate.console.writeln('> '+ str(m)) break mpstate.status.counters['Slave'] += 1
log writing thread
def log_writer(): '''log writing thread''' while True: mpstate.logfile_raw.write(bytearray(mpstate.logqueue_raw.get())) timeout = time.time() + 10 while not mpstate.logqueue_raw.empty() and time.time() < timeout: mpstate.logfile_raw.write(mpstate.logqueue_raw.get()) while not mpstate.logqueue.empty() and time.time() < timeout: mpstate.logfile.write(mpstate.logqueue.get()) if mpstate.settings.flushlogs or time.time() >= timeout: mpstate.logfile.flush() mpstate.logfile_raw.flush()
Returns tuple (logdir, telemetry_log_filepath, raw_telemetry_log_filepath)
def log_paths(): '''Returns tuple (logdir, telemetry_log_filepath, raw_telemetry_log_filepath)''' if opts.aircraft is not None: dirname = "" if opts.mission is not None: print(opts.mission) dirname += "%s/logs/%s/Mission%s" % (opts.aircraft, time.strftime("%Y-%m-%d"), opts.mission) else: dirname += "%s/logs/%s" % (opts.aircraft, time.strftime("%Y-%m-%d")) # dirname is currently relative. Possibly add state_basedir: if mpstate.settings.state_basedir is not None: dirname = os.path.join(mpstate.settings.state_basedir,dirname) mkdir_p(dirname) highest = None for i in range(1, 10000): fdir = os.path.join(dirname, 'flight%u' % i) if not os.path.exists(fdir): break highest = fdir if mpstate.continue_mode and highest is not None: fdir = highest elif os.path.exists(fdir): print("Flight logs full") sys.exit(1) logname = 'flight.tlog' logdir = fdir else: logname = os.path.basename(opts.logfile) dir_path = os.path.dirname(opts.logfile) if not os.path.isabs(dir_path) and mpstate.settings.state_basedir is not None: dir_path = os.path.join(mpstate.settings.state_basedir,dir_path) logdir = dir_path mkdir_p(logdir) return (logdir, os.path.join(logdir, logname), os.path.join(logdir, logname + '.raw'))
open log files
def open_telemetry_logs(logpath_telem, logpath_telem_raw): '''open log files''' if opts.append_log or opts.continue_mode: mode = 'ab' else: mode = 'wb' try: mpstate.logfile = open(logpath_telem, mode=mode) mpstate.logfile_raw = open(logpath_telem_raw, mode=mode) print("Log Directory: %s" % mpstate.status.logdir) print("Telemetry log: %s" % logpath_telem) #make sure there's enough free disk space for the logfile (>200Mb) #statvfs doesn't work in Windows if platform.system() != 'Windows': stat = os.statvfs(logpath_telem) if stat.f_bfree*stat.f_bsize < 209715200: print("ERROR: Not enough free disk space for logfile") mpstate.status.exit = True return # use a separate thread for writing to the logfile to prevent # delays during disk writes (important as delays can be long if camera # app is running) t = threading.Thread(target=log_writer, name='log_writer') t.daemon = True t.start() except Exception as e: print("ERROR: opening log file for writing: %s" % e) mpstate.status.exit = True return
check status of master links
def check_link_status(): '''check status of master links''' tnow = time.time() if mpstate.status.last_message != 0 and tnow > mpstate.status.last_message + 5: say("no link") mpstate.status.heartbeat_error = True for master in mpstate.mav_master: if not master.linkerror and (tnow > master.last_message + 5 or master.portdead): say("link %s down" % (mp_module.MPModule.link_label(master))) master.linkerror = True
main processing loop
def main_loop(): '''main processing loop''' global screensaver_cookie if not mpstate.status.setup_mode and not opts.nowait: for master in mpstate.mav_master: if master.linknum != 0: break print("Waiting for heartbeat from %s" % master.address) send_heartbeat(master) master.wait_heartbeat(timeout=0.1) set_stream_rates() while True: if mpstate is None or mpstate.status.exit: return # enable or disable screensaver: if (mpstate.settings.inhibit_screensaver_when_armed and screensaver_interface is not None): if mpstate.status.armed and screensaver_cookie is None: # now we can inhibit the screensaver screensaver_cookie = screensaver_interface.Inhibit("MAVProxy", "Vehicle is armed") elif not mpstate.status.armed and screensaver_cookie is not None: # we can also restore it screensaver_interface.UnInhibit(screensaver_cookie) screensaver_cookie = None while not mpstate.input_queue.empty(): line = mpstate.input_queue.get() mpstate.input_count += 1 cmds = line.split(';') if len(cmds) == 1 and cmds[0] == "": mpstate.empty_input_count += 1 for c in cmds: process_stdin(c) for master in mpstate.mav_master: if master.fd is None: if master.port.inWaiting() > 0: process_master(master) periodic_tasks() rin = [] for master in mpstate.mav_master: if master.fd is not None and not master.portdead: rin.append(master.fd) for m in mpstate.mav_outputs: rin.append(m.fd) for sysid in mpstate.sysid_outputs: m = mpstate.sysid_outputs[sysid] rin.append(m.fd) if rin == []: time.sleep(0.0001) continue for fd in mpstate.select_extra: rin.append(fd) try: (rin, win, xin) = select.select(rin, [], [], mpstate.settings.select_timeout) except select.error: continue if mpstate is None: return for fd in rin: if mpstate is None: return for master in mpstate.mav_master: if fd == master.fd: process_master(master) if mpstate is None: return continue for m in mpstate.mav_outputs: if fd == m.fd: process_mavlink(m) if mpstate is None: return continue for sysid in mpstate.sysid_outputs: m = mpstate.sysid_outputs[sysid] if fd == m.fd: process_mavlink(m) if mpstate is None: return continue # this allow modules to register their own file descriptors # for the main select loop if fd in mpstate.select_extra: try: # call the registered read function (fn, args) = mpstate.select_extra[fd] fn(args) except Exception as msg: if mpstate.settings.moddebug == 1: print(msg) # on an exception, remove it from the select list mpstate.select_extra.pop(fd)
wait for user input
def input_loop(): '''wait for user input''' while mpstate.status.exit != True: try: if mpstate.status.exit != True: line = input(mpstate.rl.prompt) except EOFError: mpstate.status.exit = True sys.exit(1) mpstate.input_queue.put(line)
run a script file
def run_script(scriptfile): '''run a script file''' try: f = open(scriptfile, mode='r') except Exception: return mpstate.console.writeln("Running script %s" % scriptfile) sub = mp_substitute.MAVSubstitute() for line in f: line = line.strip() if line == "" or line.startswith('#'): continue try: line = sub.substitute(line, os.environ) except mp_substitute.MAVSubstituteError as ex: print("Bad variable: %s" % str(ex)) if mpstate.settings.script_fatal: sys.exit(1) continue if line.startswith('@'): line = line[1:] else: mpstate.console.writeln("-> %s" % line) process_stdin(line) f.close()
Set the Mavlink version based on commandline options
def set_mav_version(mav10, mav20, autoProtocol, mavversionArg): '''Set the Mavlink version based on commandline options''' # if(mav10 == True or mav20 == True or autoProtocol == True): # print("Warning: Using deprecated --mav10, --mav20 or --auto-protocol options. Use --mavversion instead") #sanity check the options if (mav10 == True or mav20 == True) and autoProtocol == True: print("Error: Can't have [--mav10, --mav20] and --auto-protocol both True") sys.exit(1) if mav10 == True and mav20 == True: print("Error: Can't have --mav10 and --mav20 both True") sys.exit(1) if mavversionArg is not None and (mav10 == True or mav20 == True or autoProtocol == True): print("Error: Can't use --mavversion with legacy (--mav10, --mav20 or --auto-protocol) options") sys.exit(1) #and set the specific mavlink version (False = autodetect) global mavversion if mavversionArg == "1.0" or mav10 == True: os.environ['MAVLINK09'] = '1' mavversion = "1" else: os.environ['MAVLINK20'] = '1' mavversion = "2"
map mav_param onto the current target system parameters
def mav_param(self): '''map mav_param onto the current target system parameters''' compid = self.settings.target_component if compid == 0: compid = 1 sysid = (self.settings.target_system, compid) if not sysid in self.mav_param_by_sysid: self.mav_param_by_sysid[sysid] = mavparm.MAVParmDict() return self.mav_param_by_sysid[sysid]
Compute UTM projection using Redfearn's formula lat, lon is latitude and longitude in decimal degrees If false easting and northing are specified they will override the standard If zone is specified reproject lat and long to specified zone instead of standard zone If meridian is specified, reproject lat and lon to that instead of zone. In this case zone will be set to -1 to indicate non-UTM projection Note that zone and meridian cannot both be specifed
def redfearn(lat, lon, false_easting=None, false_northing=None, zone=None, central_meridian=None, scale_factor=None): """Compute UTM projection using Redfearn's formula lat, lon is latitude and longitude in decimal degrees If false easting and northing are specified they will override the standard If zone is specified reproject lat and long to specified zone instead of standard zone If meridian is specified, reproject lat and lon to that instead of zone. In this case zone will be set to -1 to indicate non-UTM projection Note that zone and meridian cannot both be specifed """ from math import pi, sqrt, sin, cos, tan #GDA Specifications a = 6378137.0 #Semi major axis inverse_flattening = 298.257222101 #1/f if scale_factor is None: K0 = 0.9996 #Central scale factor else: K0 = scale_factor #print('scale', K0) zone_width = 6 #Degrees longitude_of_central_meridian_zone0 = -183 longitude_of_western_edge_zone0 = -186 if false_easting is None: false_easting = 500000 if false_northing is None: if lat < 0: false_northing = 10000000 #Southern hemisphere else: false_northing = 0 #Northern hemisphere) #Derived constants f = 1.0/inverse_flattening b = a*(1-f) #Semi minor axis e2 = 2*f - f*f# = f*(2-f) = (a^2-b^2/a^2 #Eccentricity e = sqrt(e2) e2_ = e2/(1-e2) # = (a^2-b^2)/b^2 #Second eccentricity e_ = sqrt(e2_) e4 = e2*e2 e6 = e2*e4 #Foot point latitude n = (a-b)/(a+b) #Same as e2 - why ? n2 = n*n n3 = n*n2 n4 = n2*n2 G = a*(1-n)*(1-n2)*(1+9*n2/4+225*n4/64)*pi/180 phi = lat*pi/180 #Convert latitude to radians sinphi = sin(phi) sin2phi = sin(2*phi) sin4phi = sin(4*phi) sin6phi = sin(6*phi) cosphi = cos(phi) cosphi2 = cosphi*cosphi cosphi3 = cosphi*cosphi2 cosphi4 = cosphi2*cosphi2 cosphi5 = cosphi*cosphi4 cosphi6 = cosphi2*cosphi4 cosphi7 = cosphi*cosphi6 cosphi8 = cosphi4*cosphi4 t = tan(phi) t2 = t*t t4 = t2*t2 t6 = t2*t4 #Radius of Curvature rho = a*(1-e2)/(1-e2*sinphi*sinphi)**1.5 nu = a/(1-e2*sinphi*sinphi)**0.5 psi = nu/rho psi2 = psi*psi psi3 = psi*psi2 psi4 = psi2*psi2 #Meridian distance A0 = 1 - e2/4 - 3*e4/64 - 5*e6/256 A2 = 3.0/8*(e2+e4/4+15*e6/128) A4 = 15.0/256*(e4+3*e6/4) A6 = 35*e6/3072 term1 = a*A0*phi term2 = -a*A2*sin2phi term3 = a*A4*sin4phi term4 = -a*A6*sin6phi m = term1 + term2 + term3 + term4 #OK if zone is not None and central_meridian is not None: msg = 'You specified both zone and central_meridian. Provide only one of them' raise ValueError(msg) # Zone if zone is None: zone = int((lon - longitude_of_western_edge_zone0)/zone_width) # Central meridian if central_meridian is None: central_meridian = zone*zone_width+longitude_of_central_meridian_zone0 else: zone = -1 omega = (lon-central_meridian)*pi/180 #Relative longitude (radians) omega2 = omega*omega omega3 = omega*omega2 omega4 = omega2*omega2 omega5 = omega*omega4 omega6 = omega3*omega3 omega7 = omega*omega6 omega8 = omega4*omega4 #Northing term1 = nu*sinphi*cosphi*omega2/2 term2 = nu*sinphi*cosphi3*(4*psi2+psi-t2)*omega4/24 term3 = nu*sinphi*cosphi5*\ (8*psi4*(11-24*t2)-28*psi3*(1-6*t2)+\ psi2*(1-32*t2)-psi*2*t2+t4-t2)*omega6/720 term4 = nu*sinphi*cosphi7*(1385-3111*t2+543*t4-t6)*omega8/40320 northing = false_northing + K0*(m + term1 + term2 + term3 + term4) #Easting term1 = nu*omega*cosphi term2 = nu*cosphi3*(psi-t2)*omega3/6 term3 = nu*cosphi5*(4*psi3*(1-6*t2)+psi2*(1+8*t2)-2*psi*t2+t4)*omega5/120 term4 = nu*cosphi7*(61-479*t2+179*t4-t6)*omega7/5040 easting = false_easting + K0*(term1 + term2 + term3 + term4) return zone, easting, northing
converts lat/long to UTM coords. Equations from USGS Bulletin 1532 East Longitudes are positive, West longitudes are negative. North latitudes are positive, South latitudes are negative Lat and Long are in decimal degrees Written by Chuck Gantz- [email protected]
def LLtoUTM( Lat, Long, ReferenceEllipsoid=23): """ converts lat/long to UTM coords. Equations from USGS Bulletin 1532 East Longitudes are positive, West longitudes are negative. North latitudes are positive, South latitudes are negative Lat and Long are in decimal degrees Written by Chuck Gantz- [email protected] """ a = _ellipsoid[ReferenceEllipsoid][_EquatorialRadius] eccSquared = _ellipsoid[ReferenceEllipsoid][_eccentricitySquared] k0 = 0.9996 #Make sure the longitude is between -180.00 .. 179.9 LongTemp = (Long+180)-int((Long+180)/360)*360-180 # -180.00 .. 179.9 LatRad = Lat*_deg2rad LongRad = LongTemp*_deg2rad ZoneNumber = int((LongTemp + 180)/6) + 1 if Lat >= 56.0 and Lat < 64.0 and LongTemp >= 3.0 and LongTemp < 12.0: ZoneNumber = 32 # Special zones for Svalbard if Lat >= 72.0 and Lat < 84.0: if LongTemp >= 0.0 and LongTemp < 9.0:ZoneNumber = 31 elif LongTemp >= 9.0 and LongTemp < 21.0: ZoneNumber = 33 elif LongTemp >= 21.0 and LongTemp < 33.0: ZoneNumber = 35 elif LongTemp >= 33.0 and LongTemp < 42.0: ZoneNumber = 37 LongOrigin = (ZoneNumber - 1)*6 - 180 + 3 #+3 puts origin in middle of zone LongOriginRad = LongOrigin * _deg2rad #compute the UTM Zone from the latitude and longitude UTMZone = "%d%c" % (ZoneNumber, _UTMLetterDesignator(Lat)) eccPrimeSquared = (eccSquared)/(1-eccSquared) N = a/sqrt(1-eccSquared*sin(LatRad)*sin(LatRad)) T = tan(LatRad)*tan(LatRad) C = eccPrimeSquared*cos(LatRad)*cos(LatRad) A = cos(LatRad)*(LongRad-LongOriginRad) M = a*((1 - eccSquared/4 - 3*eccSquared*eccSquared/64 - 5*eccSquared*eccSquared*eccSquared/256)*LatRad - (3*eccSquared/8 + 3*eccSquared*eccSquared/32 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*LatRad) + (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*LatRad) - (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*LatRad)) UTMEasting = (k0*N*(A+(1-T+C)*A*A*A/6 + (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120) + 500000.0) UTMNorthing = (k0*(M+N*tan(LatRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24 + (61 -58*T +T*T +600*C -330*eccPrimeSquared)*A*A*A*A*A*A/720))) if Lat < 0: UTMNorthing = UTMNorthing + 10000000.0; #10000000 meter offset for southern hemisphere #UTMZone was originally returned here. I don't know what the #letter at the end was for. #print("UTMZone", UTMZone) return (ZoneNumber, UTMEasting, UTMNorthing)
get a WinLayout for a wx window
def get_wx_window_layout(wx_window): '''get a WinLayout for a wx window''' dsize = wx.DisplaySize() pos = wx_window.GetPosition() size = wx_window.GetSize() name = wx_window.GetTitle() return WinLayout(name, pos, size, dsize)
set a WinLayout for a wx window
def set_wx_window_layout(wx_window, layout): '''set a WinLayout for a wx window''' try: wx_window.SetSize(layout.size) wx_window.SetPosition(layout.pos) except Exception as ex: print(ex)
set window layout
def set_layout(wlayout, callback): '''set window layout''' global display_size global window_list global loaded_layout global pending_load global vehiclename #if not wlayout.name in window_list: # print("layout %s" % wlayout) if not wlayout.name in window_list and loaded_layout is not None and wlayout.name in loaded_layout: callback(loaded_layout[wlayout.name]) window_list[wlayout.name] = ManagedWindow(wlayout, callback) display_size = wlayout.dsize if pending_load: pending_load = False load_layout(vehiclename)
get location of layout file
def layout_filename(fallback): '''get location of layout file''' global display_size global vehiclename (dw,dh) = display_size if 'HOME' in os.environ: dirname = os.path.join(os.environ['HOME'], ".mavproxy") if not os.path.exists(dirname): try: os.mkdir(dirname) except Exception: pass elif 'LOCALAPPDATA' in os.environ: dirname = os.path.join(os.environ['LOCALAPPDATA'], "MAVProxy") else: return None if vehiclename: fname = os.path.join(dirname, "layout-%s-%ux%u" % (vehiclename,dw,dh)) if not fallback or os.path.exists(fname): return fname return os.path.join(dirname, "layout-%ux%u" % (dw,dh))
save window layout
def save_layout(vehname): '''save window layout''' global display_size global window_list global vehiclename if display_size is None: print("No layouts to save") return vehiclename = vehname fname = layout_filename(False) if fname is None: print("No file to save layout to") return layout = {} try: # include previous layout, so we retain layouts for widows not # currently displayed layout = pickle.load(open(fname,"rb")) except Exception: pass count = 0 for name in window_list: layout[name] = window_list[name].layout count += 1 pickle.dump(layout, open(fname,"wb")) print("Saved layout for %u windows" % count)
load window layout
def load_layout(vehname): '''load window layout''' global display_size global window_list global loaded_layout global pending_load global vehiclename if display_size is None: pending_load = True return vehiclename = vehname fname = layout_filename(True) if fname is None: print("No file to load layout from") return try: layout = pickle.load(open(fname,"rb")) except Exception: layout = {} print("Unable to load %s" % fname) loaded_layout = layout return count = 0 for name in window_list: if name in layout: try: window_list[name].callback(layout[name]) count += 1 except Exception as ex: print(ex) loaded_layout = layout print("Loaded layout for %u windows" % count)
called on apply
def on_apply(self, event): '''called on apply''' for label in self.setting_map.keys(): setting = self.setting_map[label] ctrl = self.controls[label] value = ctrl.GetValue() if str(value) != str(setting.value): oldvalue = setting.value if not setting.set(value): print("Invalid value %s for %s" % (value, setting.name)) continue if str(oldvalue) != str(setting.value): self.parent_pipe.send(setting)
called on save button
def on_save(self, event): '''called on save button''' dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*', wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: self.settings.save(dlg.GetPath())
called on load button
def on_load(self, event): '''called on load button''' dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*', wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: self.settings.load(dlg.GetPath()) # update the controls with new values for label in self.setting_map.keys(): setting = self.setting_map[label] ctrl = self.controls[label] value = ctrl.GetValue() if isinstance(value, str) or isinstance(value, unicode): ctrl.SetValue(str(setting.value)) else: ctrl.SetValue(setting.value)
add a text input line
def add_text(self, setting, width=300, height=100, multiline=False): '''add a text input line''' tab = self.panel(setting.tab) if multiline: ctrl = wx.TextCtrl(tab, -1, "", size=(width,height), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER) else: ctrl = wx.TextCtrl(tab, -1, "", size=(width,-1) ) self._add_input(setting, ctrl)
add a choice input line
def add_choice(self, setting, choices): '''add a choice input line''' tab = self.panel(setting.tab) default = setting.value if default is None: default = choices[0] ctrl = wx.ComboBox(tab, -1, choices=choices, value = str(default), style = wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT ) self._add_input(setting, ctrl)