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 ... |
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.A... |
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.AddSimp... |
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._ac... |
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 no... |
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]:... |
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, se... |
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))
... |
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 = ... |
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... |
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" %
... |
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 connecte... |
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 +... |
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... |
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... |
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)... |
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... |
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.fi... |
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.le... |
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 (... |
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,horizontalal... |
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=sel... |
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(h... |
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.vertS... |
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-(... |
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='orang... |
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)
# Groun... |
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.... |
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 = patche... |
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,... |
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 = ... |
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),... |
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.ba... |
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.... |
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,foregr... |
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.mode... |
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',v... |
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... |
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',s... |
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_t... |
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... |
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... |
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()
# Re... |
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.r... |
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
... |
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:
... |
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_... |
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:
... |
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.f... |
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
... |
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(MPImageDat... |
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:
... |
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)
... |
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
... |
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]
... |
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_checkb... |
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
s... |
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()
... |
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
... |
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.... |
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:
pop... |
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'):
an... |
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')
... |
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... |
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 le... |
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 ... |
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())
w... |
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"), opt... |
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)
... |
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 ... |
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)
se... |
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.... |
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 c... |
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_s... |
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, r... | 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... |
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- chuck.gantz@globalstar.com | 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 Chuc... |
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... |
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(di... |
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 l... |
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 i... |
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
... |
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.... |
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(ta... |
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),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.