id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,100 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_ui.py
|
MAVProxy.modules.lib.wxhorizon_ui.HorizonFrame
|
class HorizonFrame(wx.Frame):
""" The main frame of the horizon indicator."""
def __init__(self, state, title):
self.state = state
# Create Frame and Panel(s)
wx.Frame.__init__(self, None, title=title)
state.frame = self
# Initialisation
self.initData()
self.initUI()
self.startTime = time.time()
self.nextTime = 0.0
self.fps = 10.0
def initData(self):
# Initialise Attitude
self.pitch = 0.0 # Degrees
self.roll = 0.0 # Degrees
self.yaw = 0.0 # Degrees
# History Values
self.oldRoll = 0.0 # Degrees
# Initialise Rate Information
self.airspeed = 0.0 # m/s
self.relAlt = 0.0 # m relative to home position
self.relAltTime = 0.0 # s The time that the relative altitude was recorded
self.climbRate = 0.0 # m/s
self.altHist = [] # Altitude History
self.timeHist = [] # Time History
self.altMax = 0.0 # Maximum altitude since startup
# Initialise HUD Info
self.heading = 0.0 # 0-360
# Initialise Battery Info
self.voltage = 0.0
self.current = 0.0
self.batRemain = 0.0
# Initialise Mode and State
self.mode = 'UNKNOWN'
self.armed = ''
self.safetySwitch = ''
# Intialise Waypoint Information
self.currentWP = 0
self.finalWP = 0
self.wpDist = 0
self.nextWPTime = 0
self.wpBearing = 0
def initUI(self):
# Create Event Timer and Bindings
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.timer.Start(100)
self.Bind(wx.EVT_IDLE, self.on_idle)
self.Bind(wx.EVT_CHAR_HOOK,self.on_KeyPress)
# Create Panel
self.panel = wx.Panel(self)
self.vertSize = 0.09
self.resized = False
# Create Matplotlib Panel
self.createPlotPanel()
# Fix Axes - vertical is of length 2, horizontal keeps the same lengthscale
self.rescaleX()
self.calcFontScaling()
# Create Horizon Polygons
self.createHorizonPolygons()
# Center Pointer Marker
self.thick = 0.015
self.createCenterPointMarker()
# Pitch Markers
self.dist10deg = 0.2 # Graph distance per 10 deg
self.createPitchMarkers()
# Add Roll, Pitch, Yaw Text
self.createRPYText()
# Add Airspeed, Altitude, Climb Rate Text
self.createAARText()
# Create Heading Pointer
self.createHeadingPointer()
# Create North Pointer
self.createNorthPointer()
# Create Battery Bar
self.batWidth = 0.1
self.batHeight = 0.2
self.rOffset = 0.35
self.createBatteryBar()
# Create Mode & State Text
self.createStateText()
# Create Waypoint Text
self.createWPText()
# Create Waypoint Pointer
self.createWPPointer()
# Create Altitude History Plot
self.createAltHistoryPlot()
# Show Frame
self.Show(True)
self.pending = []
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()
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)
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]
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
def createHeadingPointer(self):
'''Creates the pointer for the current heading.'''
self.headingTri = patches.RegularPolygon((0.0,0.80),3,radius=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)
def adjustHeadingPointer(self):
'''Adjust the value of the heading pointer.'''
self.headingText.set_text(str(self.heading))
self.headingText.set_size(self.fontSize)
def createNorthPointer(self):
'''Creates the north pointer relative to current heading.'''
self.headingNorthTri = patches.RegularPolygon((0.0,0.80),3,radius=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)
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')
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)
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')])
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)
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)
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))
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)
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)
if (self.roll > 90) or (self.roll < -90):
pitchdiff = pitchdiff*-1
# Draw Polygons
vertsTop = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,1),(self.ratio,1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]
vertsBot = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,-1),(self.ratio,-1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]
if (self.roll > 90) or (self.roll < -90):
vertsTop = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,-1),(self.ratio,-1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]
vertsBot = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,1),(self.ratio,1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]
self.topPolygon.set_xy(vertsTop)
self.botPolygon.set_xy(vertsBot)
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
def calcPitchMarkerWidth(self,i):
'''Calculates the width of a pitch marker.'''
if (i % 3) == 0:
if i == 0:
width = 1.5
else:
width = 0.9
else:
width = 0.6
return width
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
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')])
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)
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)
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)
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')
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')])
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')])
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')])
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))
def createWPPointer(self):
'''Creates the waypoint pointer relative to current heading.'''
self.headingWPTri = patches.RegularPolygon((0.0,0.55),3,radius=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')])
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))
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)
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)
# =============== Event Bindings =============== #
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)
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()
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()
|
class HorizonFrame(wx.Frame):
''' The main frame of the horizon indicator.'''
def __init__(self, state, title):
pass
def initData(self):
pass
def initUI(self):
pass
def createPlotPanel(self):
'''Creates the figure and axes for the plotting panel.'''
pass
def rescaleX(self):
'''Rescales the horizontal axes to make the lengthscales equal.'''
pass
def calcFontScaling(self):
'''Calculates the current font size and left position for the current window.'''
pass
def checkReszie(self):
'''Checks if the window was resized.'''
pass
def createHeadingPointer(self):
'''Creates the pointer for the current heading.'''
pass
def adjustHeadingPointer(self):
'''Adjust the value of the heading pointer.'''
pass
def createNorthPointer(self):
'''Creates the north pointer relative to current heading.'''
pass
def adjustNorthPointer(self):
'''Adjust the position and orientation of
the north pointer.'''
pass
def toggleWidgets(self,widgets):
'''Hides/shows the given widgets.'''
pass
def createRPYText(self):
'''Creates the text for roll, pitch and yaw.'''
pass
def updateRPYLocations(self):
'''Update the locations of roll, pitch, yaw text.'''
pass
def updateRPYText(self):
'''Updates the displayed Roll, Pitch, Yaw Text'''
pass
def createCenterPointMarker(self):
'''Creates the center pointer in the middle of the screen.'''
pass
def createHorizonPolygons(self):
'''Creates the two polygons to show the sky and ground.'''
pass
def calcHorizonPoints(self):
'''Updates the verticies of the patches for the ground and sky.'''
pass
def createPitchMarkers(self):
'''Creates the rectangle patches for the pitch indicators.'''
pass
def calcPitchMarkerWidth(self,i):
'''Calculates the width of a pitch marker.'''
pass
def adjustPitchmarkers(self):
'''Adjusts the location and orientation of pitch markers.'''
pass
def createAARText(self):
'''Creates the text for airspeed, altitude and climb rate.'''
pass
def updateAARLocations(self):
'''Update the locations of airspeed, altitude and Climb rate.'''
pass
def updateAARText(self):
'''Updates the displayed airspeed, altitude, climb rate Text'''
pass
def createBatteryBar(self):
'''Creates the bar to display current battery percentage.'''
pass
def updateBatteryBar(self):
'''Updates the position and values of the battery bar.'''
pass
def createStateText(self):
'''Creates the mode and arm state text.'''
pass
def updateStateText(self):
'''Updates the mode and colours red or green depending on arm state.'''
pass
def createWPText(self):
'''Creates the text for the current and final waypoint,
and the distance to the new waypoint.'''
pass
def updateWPText(self):
'''Updates the current waypoint and distance to it.'''
pass
def createWPPointer(self):
'''Creates the waypoint pointer relative to current heading.'''
pass
def adjustWPPointer(self):
'''Adjust the position and orientation of
the waypoint pointer.'''
pass
def createAltHistoryPlot(self):
'''Creates the altitude history plot.'''
pass
def updateAltHistory(self):
'''Updates the altitude history plot.'''
pass
def on_idle(self, event):
'''To adjust text and positions on rescaling the window when resized.'''
pass
def on_timer(self, event):
'''Main Loop.'''
pass
def on_KeyPress(self,event):
'''To adjust the distance between pitch markers.'''
pass
| 38 | 35 | 18 | 2 | 13 | 4 | 3 | 0.28 | 1 | 12 | 7 | 0 | 37 | 76 | 37 | 37 | 702 | 104 | 482 | 160 | 444 | 135 | 450 | 160 | 412 | 15 | 1 | 4 | 94 |
7,101 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon.py
|
MAVProxy.modules.lib.wxhorizon.HorizonIndicator
|
class HorizonIndicator():
'''
A horizon indicator for MAVProxy.
'''
def __init__(self,title='MAVProxy: Horizon Indicator'):
self.title = title
# Create Pipe to send attitude information from module to UI
self.child_pipe_recv,self.parent_pipe_send = multiproc.Pipe()
self.close_event = multiproc.Event()
self.close_event.clear()
self.child = multiproc.Process(target=self.child_task)
self.child.start()
self.child_pipe_recv.close()
def child_task(self):
'''child process - this holds all the GUI elements'''
self.parent_pipe_send.close()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxhorizon_ui import HorizonFrame
# Create wx application
app = wx.App(False)
app.frame = HorizonFrame(state=self, title=self.title)
app.frame.SetDoubleBuffered(True)
app.frame.Show()
app.MainLoop()
self.close_event.set() # indicate that the GUI has closed
def close(self):
'''Close the window.'''
self.close_event.set()
if self.is_alive():
self.child.join(2)
def is_alive(self):
'''check if child is still going'''
return self.child.is_alive()
|
class HorizonIndicator():
'''
A horizon indicator for MAVProxy.
'''
def __init__(self,title='MAVProxy: Horizon Indicator'):
pass
def child_task(self):
'''child process - this holds all the GUI elements'''
pass
def close(self):
'''Close the window.'''
pass
def is_alive(self):
'''check if child is still going'''
pass
| 5 | 4 | 8 | 0 | 6 | 2 | 1 | 0.35 | 0 | 1 | 1 | 0 | 4 | 5 | 4 | 4 | 38 | 4 | 26 | 13 | 18 | 9 | 26 | 13 | 18 | 2 | 0 | 1 | 5 |
7,102 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxgrapheditor.py
|
MAVProxy.modules.lib.wxgrapheditor.GraphDialog
|
class GraphDialog(wx.Dialog):
def __init__(self, title, graphdef, callback):
wx.Dialog.__init__(self, None, -1, title, size=(900, 400))
self.callback = callback
self.graphdef = graphdef
self.panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
# name entry
hbox_name = wx.BoxSizer(wx.HORIZONTAL)
st_name = wx.StaticText(self.panel, -1, 'Name: ')
self.tc_name = wx.TextCtrl(self.panel, -1, size=(400, -1))
try:
self.tc_name.Value = self.graphdef.name
except Exception:
self.tc_name.Value = 'UNKNOWN'
hbox_name.Add(st_name, 0, wx.LEFT, 10)
hbox_name.Add(self.tc_name, 0, wx.LEFT, 35)
vbox.Add(hbox_name, 0, wx.TOP, 10)
# expression entry
st = wx.StaticText(self.panel, -1, 'Expressions: ')
vbox.Add(st, 0, wx.LEFT, 10)
hbox_expressions = wx.BoxSizer(wx.HORIZONTAL)
self.tc_expressions = wx.TextCtrl(self.panel, -1, style=wx.TE_MULTILINE|wx.HSCROLL, size=(800, 80))
elist = []
for e in self.graphdef.expressions:
e = ' '.join(e.split())
elist.append(e)
self.tc_expressions.Value = '\n'.join(elist)
vbox.Add(self.tc_expressions, 0, wx.LEFT, 15)
# description entry
st = wx.StaticText(self.panel, -1, 'Description: ')
vbox.Add(st, 0, wx.LEFT, 10)
self.tc_description = wx.TextCtrl(self.panel, -1, style=wx.TE_MULTILINE)
vbox.Add(self.tc_description, 1, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, 15)
self.tc_description.Value = self.graphdef.description
# buttons
button_save = wx.Button(self.panel, 1, 'Save')
button_cancel = wx.Button(self.panel, 2, 'Cancel')
button_test = wx.Button(self.panel, 3, 'Test')
hbox_buttons = wx.BoxSizer(wx.HORIZONTAL)
hbox_buttons.Add(button_save, 0, wx.LEFT, 10)
hbox_buttons.Add(button_cancel, 0, wx.LEFT, 10)
hbox_buttons.Add(button_test, 0, wx.LEFT, 10)
vbox.Add(hbox_buttons, 0, wx.TOP, 10)
self.Bind(wx.EVT_BUTTON, self.OnSave, id=1)
self.Bind(wx.EVT_BUTTON, self.OnCancel, id=2)
self.Bind(wx.EVT_BUTTON, self.OnTest, id=3)
self.panel.SetSizer(vbox)
self.Centre()
def update_values(self):
self.graphdef.name = self.tc_name.Value.strip()
self.graphdef.expressions = self.tc_expressions.Value.split('\n')
self.graphdef.description = self.tc_description.Value
def OnCancel(self, event):
self.Close()
def OnTest(self, event):
self.update_values()
self.callback('test', self.graphdef)
def OnSave(self, event):
self.update_values()
self.callback('save', self.graphdef)
|
class GraphDialog(wx.Dialog):
def __init__(self, title, graphdef, callback):
pass
def update_values(self):
pass
def OnCancel(self, event):
pass
def OnTest(self, event):
pass
def OnSave(self, event):
pass
| 6 | 0 | 14 | 2 | 11 | 1 | 1 | 0.07 | 1 | 1 | 0 | 0 | 5 | 6 | 5 | 5 | 73 | 12 | 57 | 23 | 51 | 4 | 57 | 23 | 51 | 3 | 1 | 1 | 7 |
7,103 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxconsole_util.py
|
MAVProxy.modules.lib.wxconsole_util.Value
|
class Value():
'''a value for the status bar'''
def __init__(self, name, text, row=0, fg='black', bg='white'):
self.name = name
self.text = text
self.row = row
self.fg = fg
self.bg = bg
|
class Value():
'''a value for the status bar'''
def __init__(self, name, text, row=0, fg='black', bg='white'):
pass
| 2 | 1 | 6 | 0 | 6 | 0 | 1 | 0.14 | 0 | 0 | 0 | 0 | 1 | 5 | 1 | 1 | 8 | 0 | 7 | 7 | 5 | 1 | 7 | 7 | 5 | 1 | 0 | 0 | 1 |
7,104 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxconsole_util.py
|
MAVProxy.modules.lib.wxconsole_util.Text
|
class Text():
'''text to write to console'''
def __init__(self, text, fg='black', bg='white'):
self.text = text
self.fg = fg
self.bg = bg
|
class Text():
'''text to write to console'''
def __init__(self, text, fg='black', bg='white'):
pass
| 2 | 1 | 4 | 0 | 4 | 0 | 1 | 0.2 | 0 | 0 | 0 | 0 | 1 | 3 | 1 | 1 | 6 | 0 | 5 | 5 | 3 | 1 | 5 | 5 | 3 | 1 | 0 | 0 | 1 |
7,105 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxconsole_ui.py
|
MAVProxy.modules.lib.wxconsole_ui.ConsoleFrame
|
class ConsoleFrame(wx.Frame):
""" The main frame of the console"""
def __init__(self, state, title):
self.state = state
wx.Frame.__init__(self, None, title=title, size=(800,300))
# different icons for MAVExplorer and MAVProxy
try:
if title == "MAVExplorer":
self.SetIcon(icon.SimpleIcon("EXPLORER").get_ico())
else:
self.SetIcon(icon.SimpleIcon("CONSOLE").get_ico())
except Exception:
pass
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour('white')
state.frame = self
# values for the status bar
self.values = {}
self.menu = None
self.menu_callback = None
self.last_layout_send = time.time()
self.control = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_AUTO_URL)
self.vbox = wx.BoxSizer(wx.VERTICAL)
# start with one status row
self.status = [wx.BoxSizer(wx.HORIZONTAL)]
self.vbox.Add(self.status[0], 0, flag=wx.ALIGN_LEFT | wx.TOP)
self.vbox.Add(self.control, 1, flag=wx.LEFT | wx.BOTTOM | wx.GROW)
self.panel.SetSizer(self.vbox)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.timer.Start(100)
self.Bind(wx.EVT_IDLE, self.on_idle)
self.Bind(wx.EVT_TEXT_URL, self.on_text_url)
self.Show(True)
self.pending = []
def on_menu(self, event):
'''handle menu selections'''
state = self.state
ret = self.menu.find_selected(event)
if ret is None:
return
ret.call_handler()
state.child_pipe_send.send(ret)
def on_text_url(self, event):
'''handle double clicks on URL text'''
try:
import webbrowser
except ImportError:
return
mouse_event = event.GetMouseEvent()
if mouse_event.LeftDClick():
url_start = event.GetURLStart()
url_end = event.GetURLEnd()
url = self.control.GetRange(url_start, url_end)
try:
# attempt to use google-chrome
browser_controller = webbrowser.get('google-chrome')
browser_controller.open_new_tab(url)
except webbrowser.Error:
# use the system configured default browser
webbrowser.open_new_tab(url)
def on_idle(self, event):
time.sleep(0.05)
now = time.time()
if now - self.last_layout_send > 1:
self.last_layout_send = now
self.state.child_pipe_send.send(win_layout.get_wx_window_layout(self))
def on_timer(self, event):
state = self.state
if state.close_event.wait(0.001):
self.timer.Stop()
self.Destroy()
return
while True:
try:
poll_success = state.child_pipe_recv.poll()
if not poll_success:
return
except socket.error as e:
if e.errno == errno.EPIPE:
break
else:
raise e
try:
obj = state.child_pipe_recv.recv()
except Exception:
break
if isinstance(obj, Value):
# request to set a status field
if not obj.name in self.values:
# create a new status field
value = wx.StaticText(self.panel, -1, obj.text)
# possibly add more status rows
for i in range(len(self.status), obj.row+1):
self.status.append(wx.BoxSizer(wx.HORIZONTAL))
self.vbox.Insert(len(self.status)-1, self.status[i], 0, flag=wx.ALIGN_LEFT | wx.TOP)
self.vbox.Layout()
self.status[obj.row].Add(value, border=5)
self.status[obj.row].AddSpacer(20)
self.values[obj.name] = value
value = self.values[obj.name]
value.SetForegroundColour(obj.fg)
value.SetBackgroundColour(obj.bg)
# workaround wx bug on windows
value._foregroundColour = obj.fg
value.SetLabel(obj.text)
if platform.system() == 'Windows':
# more working around wx bugs in windows; without
# these the display does not update on colour change
value.Refresh()
value.Update()
self.panel.Layout()
elif isinstance(obj, Text):
'''request to add text to the console'''
self.pending.append(obj)
for p in self.pending:
# we're scrolled at the bottom
oldstyle = self.control.GetDefaultStyle()
style = wx.TextAttr()
style.SetTextColour(p.fg)
style.SetBackgroundColour(p.bg)
self.control.SetDefaultStyle(style)
self.control.AppendText(p.text)
self.control.SetDefaultStyle(oldstyle)
self.pending = []
elif isinstance(obj, mp_menu.MPMenuTop):
if obj is not None:
self.SetMenuBar(None)
self.menu = obj
self.SetMenuBar(self.menu.wx_menu())
self.Bind(wx.EVT_MENU, self.on_menu)
self.Refresh()
self.Update()
elif isinstance(obj, win_layout.WinLayout):
win_layout.set_wx_window_layout(self, obj)
self.timer.Stop()
self.Destroy()
return
|
class ConsoleFrame(wx.Frame):
''' The main frame of the console'''
def __init__(self, state, title):
pass
def on_menu(self, event):
'''handle menu selections'''
pass
def on_text_url(self, event):
'''handle double clicks on URL text'''
pass
def on_idle(self, event):
pass
def on_timer(self, event):
pass
| 6 | 3 | 30 | 3 | 24 | 3 | 5 | 0.13 | 1 | 9 | 5 | 0 | 5 | 11 | 5 | 5 | 156 | 18 | 122 | 35 | 115 | 16 | 117 | 34 | 110 | 16 | 1 | 4 | 27 |
7,106 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxconsole.py
|
MAVProxy.modules.lib.wxconsole.MessageConsole
|
class MessageConsole(textconsole.SimpleConsole):
'''
a message console for MAVProxy
'''
def __init__(self,
title='MAVProxy: console'):
textconsole.SimpleConsole.__init__(self)
self.title = title
self.menu_callback = None
self.parent_pipe_recv,self.child_pipe_send = multiproc.Pipe(duplex=False)
self.child_pipe_recv,self.parent_pipe_send = multiproc.Pipe(duplex=False)
self.close_event = multiproc.Event()
self.close_event.clear()
self.child = multiproc.Process(target=self.child_task)
self.child.start()
self.child_pipe_send.close()
self.child_pipe_recv.close()
t = threading.Thread(target=self.watch_thread)
t.daemon = True
t.start()
def child_task(self):
'''child process - this holds all the GUI elements'''
self.parent_pipe_send.close()
self.parent_pipe_recv.close()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxconsole_ui import ConsoleFrame
app = wx.App(False)
app.frame = ConsoleFrame(state=self, title=self.title)
app.frame.SetDoubleBuffered(True)
app.frame.Show()
app.MainLoop()
def watch_thread(self):
'''watch for menu events from child'''
from MAVProxy.modules.lib.mp_settings import MPSetting
try:
while True:
msg = self.parent_pipe_recv.recv()
if isinstance(msg, win_layout.WinLayout):
win_layout.set_layout(msg, self.set_layout)
elif self.menu_callback is not None:
self.menu_callback(msg)
time.sleep(0.1)
except EOFError:
pass
def set_layout(self, layout):
'''set window layout'''
self.parent_pipe_send.send(layout)
def write(self, text, fg='black', bg='white'):
'''write to the console'''
try:
self.parent_pipe_send.send(Text(text, fg, bg))
except Exception:
pass
def set_status(self, name, text='', row=0, fg='black', bg='white'):
'''set a status value'''
if self.is_alive():
self.parent_pipe_send.send(Value(name, text, row, fg, bg))
def set_menu(self, menu, callback):
if self.is_alive():
self.parent_pipe_send.send(menu)
self.menu_callback = callback
def close(self):
'''close the console'''
self.close_event.set()
if self.is_alive():
self.child.join(2)
def is_alive(self):
'''check if child is still going'''
return self.child.is_alive()
|
class MessageConsole(textconsole.SimpleConsole):
'''
a message console for MAVProxy
'''
def __init__(self,
title='MAVProxy: console'):
pass
def child_task(self):
'''child process - this holds all the GUI elements'''
pass
def watch_thread(self):
'''watch for menu events from child'''
pass
def set_layout(self, layout):
'''set window layout'''
pass
def write(self, text, fg='black', bg='white'):
'''write to the console'''
pass
def set_status(self, name, text='', row=0, fg='black', bg='white'):
'''set a status value'''
pass
def set_menu(self, menu, callback):
pass
def close(self):
'''close the console'''
pass
def is_alive(self):
'''check if child is still going'''
pass
| 10 | 8 | 7 | 0 | 7 | 1 | 2 | 0.17 | 1 | 8 | 5 | 0 | 9 | 8 | 9 | 17 | 79 | 9 | 60 | 24 | 45 | 10 | 58 | 23 | 44 | 5 | 1 | 3 | 17 |
7,107 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wx_addlink.py
|
MAVProxy.modules.lib.wx_addlink.linkAddDialog
|
class linkAddDialog(wx.Dialog):
def __init__(self, *args, **kwds):
super(linkAddDialog, self).__init__(*args, **kwds)
self.panelGUI = wx.Panel(self, wx.ID_ANY)
self.sizerGUI = wx.FlexGridSizer(5, 2, 0, 0)
self.addLink = None
self.conStr = None
label_1 = wx.StaticText(self.panelGUI, wx.ID_ANY, "Connection Type:")
self.sizerGUI.Add(label_1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 3)
self.choiceConnection = wx.Choice(self.panelGUI, wx.ID_ANY, choices=["udpin", "udpout", "tcpin", "tcp", "Serial"])
self.choiceConnection.SetSelection(0)
self.sizerGUI.Add(self.choiceConnection, 0, wx.ALL, 3)
self.labelConType = wx.StaticText(self.panelGUI, wx.ID_ANY, "IP:Port")
self.sizerGUI.Add(self.labelConType, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)
self.textConIPPort = wx.TextCtrl(self.panelGUI, wx.ID_ANY, "127.0.0.1:14550")
self.textConIPPort.SetMinSize((150, 34))
self.sizerGUI.Add(self.textConIPPort, 0, wx.ALL | wx.EXPAND, 3)
self.labelSerialPort = wx.StaticText(self.panelGUI, wx.ID_ANY, "Port:")
self.sizerGUI.Add(self.labelSerialPort, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 3)
self.choiceSerialPort = wx.Choice(self.panelGUI, wx.ID_ANY, choices=[])
self.sizerGUI.Add(self.choiceSerialPort, 0, wx.ALL | wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 3)
self.labelBaud = wx.StaticText(self.panelGUI, wx.ID_ANY, "Baud Rate:")
self.sizerGUI.Add(self.labelBaud, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 3)
self.choiceBaud = wx.Choice(self.panelGUI, wx.ID_ANY, choices=["9600", "19200", "38400", "57600", "115200", "921600", "1500000"])
self.choiceBaud.SetSelection(3)
self.sizerGUI.Add(self.choiceBaud, 0, wx.ALL | wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 3)
self.buttonAdd = wx.Button(self.panelGUI, wx.ID_ADD, "Add Link")
self.sizerGUI.Add(self.buttonAdd, 0, wx.ALL, 3)
self.buttonExit = wx.Button(self.panelGUI, wx.ID_CANCEL, "")
self.sizerGUI.Add(self.buttonExit, 0, wx.ALIGN_CENTER_VERTICAL, 0)
self.panelGUI.SetSizer(self.sizerGUI)
self.Layout()
self.Bind(wx.EVT_CHOICE, self.onChangeType, self.choiceConnection)
self.Bind(wx.EVT_BUTTON, self.onAdd, self.buttonAdd)
self.Bind(wx.EVT_BUTTON, self.onClose, self.buttonExit)
self.Bind(wx.EVT_CLOSE, self.onClose)
# Set initial state
self.choiceSerialPort.Disable()
self.choiceBaud.Disable()
self.labelSerialPort.Disable()
self.labelBaud.Disable()
self.textConIPPort.Enable()
self.labelConType.Enable()
ports = mavutil.auto_detect_serial(preferred_list=MAVProxy.modules.mavproxy_link.preferred_ports)
for p in ports:
self.choiceSerialPort.Append(p.device)
self.choiceSerialPort.SetSelection(0)
def onChangeType(self, event):
''' Change between network and serial connection options '''
choice = self.choiceConnection.GetString( self.choiceConnection.GetSelection())
if choice in ["udpin", "udpout", "tcpin", "tcp"]:
self.choiceSerialPort.Disable()
self.choiceBaud.Disable()
self.labelSerialPort.Disable()
self.labelBaud.Disable()
self.textConIPPort.Enable()
self.labelConType.Enable()
else:
self.choiceSerialPort.Enable()
self.choiceBaud.Enable()
self.labelSerialPort.Enable()
self.labelBaud.Enable()
self.textConIPPort.Disable()
self.labelConType.Disable()
self.choiceSerialPort.Clear()
ports = mavutil.auto_detect_serial(preferred_list=MAVProxy.modules.mavproxy_link.preferred_ports)
for p in ports:
self.choiceSerialPort.Append(p.device)
self.choiceSerialPort.SetSelection(0)
def onAdd(self, event):
'''Return connection string'''
choice = self.choiceConnection.GetString( self.choiceConnection.GetSelection())
self.conStr = None
if choice in ["udpin", "udpout", "tcpin", "tcp"]:
self.conStr = "" + choice + ":" + self.textConIPPort.GetValue()
else:
self.conStr = "" + self.choiceSerialPort.GetString(self.choiceSerialPort.GetSelection()) + ":" + self.choiceBaud.GetString(self.choiceBaud.GetSelection())
#print("1. " + self.conStr)
self.EndModal(wx.ID_ADD)
def onClose(self, event):
''' Exit the dialog (cancel) '''
if event is None and self.IsModal():
self.EndModal(wx.ID_ADD)
elif self.IsModal():
self.EndModal(event.EventObject.Id)
else:
self.Close()
|
class linkAddDialog(wx.Dialog):
def __init__(self, *args, **kwds):
pass
def onChangeType(self, event):
''' Change between network and serial connection options '''
pass
def onAdd(self, event):
'''Return connection string'''
pass
def onClose(self, event):
''' Exit the dialog (cancel) '''
pass
| 5 | 3 | 27 | 5 | 20 | 1 | 3 | 0.06 | 1 | 1 | 0 | 0 | 4 | 13 | 4 | 4 | 111 | 24 | 82 | 25 | 77 | 5 | 78 | 25 | 73 | 3 | 1 | 2 | 10 |
7,108 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wx_addlink.py
|
MAVProxy.modules.lib.wx_addlink.MPMenulinkAddDialog
|
class MPMenulinkAddDialog(object):
'''used to create a file dialog callback'''
def __init__(self):
pass
def call(self):
'''show a file dialog'''
from MAVProxy.modules.lib.wx_loader import wx
dlg = linkAddDialog(None, title='Add New Link')
if dlg.ShowModal() != wx.ID_ADD:
return None
else:
# get the connection string before closing dialog
Constr = dlg.conStr
dlg.Destroy()
return Constr
|
class MPMenulinkAddDialog(object):
'''used to create a file dialog callback'''
def __init__(self):
pass
def call(self):
'''show a file dialog'''
pass
| 3 | 2 | 7 | 1 | 6 | 1 | 2 | 0.25 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 2 | 17 | 2 | 12 | 6 | 8 | 3 | 11 | 6 | 7 | 2 | 1 | 1 | 3 |
7,109 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.VFR_HUD
|
class VFR_HUD():
'''HUD Information.'''
def __init__(self,hudMsg):
self.airspeed = hudMsg.airspeed
self.groundspeed = hudMsg.groundspeed
self.heading = hudMsg.heading
self.throttle = hudMsg.throttle
self.climbRate = hudMsg.climb
|
class VFR_HUD():
'''HUD Information.'''
def __init__(self,hudMsg):
pass
| 2 | 1 | 6 | 0 | 6 | 0 | 1 | 0.14 | 0 | 0 | 0 | 0 | 1 | 5 | 1 | 1 | 8 | 0 | 7 | 7 | 5 | 1 | 7 | 7 | 5 | 1 | 0 | 0 | 1 |
7,110 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SIYI/raw_thermal.py
|
MAVProxy.modules.mavproxy_SIYI.raw_thermal.RawThermal
|
class RawThermal:
"""handle raw thermal image"""
def __init__(self, siyi, res):
self.siyi = siyi
self.uri = ("192.168.144.25", 7345)
self.im = None
self.tracking = False
self.cap = None
self.res = res
self.FOV = 24.2
self.last_frame_t = time.time()
self.logdir = 'thermal'
self.should_exit = False
self.last_data = None
self.tmin = -1
self.tmax = -1
self.mouse_temp = -1
self.image_count = 0
self.marker_history = []
self.last_tstamp = None
if siyi is not None:
self.logdir = self.siyi.logdir
self.im = MPImage(
title="Raw Thermal",
mouse_events=True,
mouse_movement_events=True,
width=self.res[0],
height=self.res[1],
key_events=True,
can_drag=False,
can_zoom=False,
auto_size=False,
auto_fit=True
)
popup = self.im.get_popup_menu()
popup.add_to_submenu(["Mode"], MPMenuItem("ClickTrack", returnkey="Mode:ClickTrack"))
popup.add_to_submenu(["Mode"], MPMenuItem("Flag", returnkey="Mode:Flag"))
popup.add_to_submenu(["Marker"], MPMenuItem("Flame", returnkey="Marker:flame"))
popup.add_to_submenu(["Marker"], MPMenuItem("Flag", returnkey="Marker:flag"))
popup.add_to_submenu(["Marker"], MPMenuItem("Barrell", returnkey="Marker:barrell"))
dname = os.path.join(self.logdir, 'thermal')
try:
os.mkdir(dname)
except Exception as ex:
pass
self.thread = Thread(target=self.fetch_loop, name='fetch_loop')
self.thread.daemon = False
self.thread.start()
def fetch_loop(self):
'''main thread'''
while True:
if self.im is None:
break
time.sleep(0.1)
ret = self.fetch_latest_compressed()
if ret is None:
continue
(fname, tstamp, data) = ret
if self.last_tstamp is not None and tstamp == self.last_tstamp:
continue
self.last_tstamp = tstamp
self.display_image(fname, data)
self.save_image(fname, tstamp, data)
def in_history(self, latlon):
'''check if latlon in the history'''
autoflag_dist = self.siyi.siyi_settings.autoflag_dist
for (lat1,lon1) in self.marker_history:
dist = mp_util.gps_distance(lat1,lon1,latlon[0],latlon[1])
if dist < autoflag_dist:
return True
# add to history
self.marker_history.append(latlon)
if len(self.marker_history) > self.siyi.siyi_settings.autoflag_history:
self.marker_history.pop(0)
return False
def handle_auto_flag(self):
if not self.siyi.siyi_settings.autoflag_enable:
return
if self.tmax < self.siyi.siyi_settings.autoflag_temp:
return
map = self.siyi.module('map')
if not map:
return
width = self.res[0]
height = self.res[1]
latlonalt = self.xy_to_latlon(width//2, height//2)
if latlonalt is None:
return
slices = self.siyi.siyi_settings.autoflag_slices
slice_width = width // slices
slice_height = height // slices
data = self.last_data.reshape(height, width)
for sx in range(slices):
for sy in range(slices):
sub = data[sx*slice_width:(sx+1)*slice_width, sy*slice_height:(sy+1)*slice_height]
maxv = sub.max() - C_TO_KELVIN
if maxv < self.siyi.siyi_settings.autoflag_temp:
continue
X = (sx*slice_width) + slice_width//2
Y = (sy*slice_height) + slice_height//2
latlonalt = self.xy_to_latlon(X, Y)
if latlonalt is None:
continue
latlon = (latlonalt[0], latlonalt[1])
if self.in_history(latlon):
continue
map.cmd_map_marker(["flame"], latlon=latlon)
def display_image(self, fname, data):
'''display an image'''
a = np.frombuffer(data, dtype='>u2')
if len(a) != 640 * 512:
print("Bad size %u" % len(a))
return
# get in Kelvin
a = (a / 64.0)
maxv = a.max()
minv = a.min()
self.tmin = minv - C_TO_KELVIN
self.tmax = maxv - C_TO_KELVIN
if maxv <= minv:
maxv = minv + 1
self.last_data = a
self.handle_auto_flag()
# convert to 0 to 255
a = (a - minv) * 255 / (maxv - minv)
# convert to uint8 greyscale as 640x512 image
a = a.astype(np.uint8)
a = a.reshape(512, 640)
a = cv2.cvtColor(a, cv2.COLOR_GRAY2RGB)
if self.im is None:
return
self.im.set_image(a)
self.image_count += 1
self.update_title()
def decompress_zlib_buffer(self, compressed_buffer):
try:
# Decompress the buffer using zlib
uncompressed_buffer = zlib.decompress(compressed_buffer)
return uncompressed_buffer
except zlib.error as e:
# Handle any errors during decompression
return None
def fetch_latest_compressed(self):
'''fetch a compressed thermal image'''
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
timeout = self.siyi.siyi_settings.fetch_timeout
if timeout >= 0:
tcp.settimeout(2)
try:
tcp.connect(self.uri)
except Exception:
return None
buf = bytearray()
while True:
try:
b = tcp.recv(1024)
except Exception:
break
if not b:
break
buf += b
header_len = 128 + 12
if len(buf) < header_len:
return None
fname = buf[:128].decode("utf-8").strip('\x00')
compressed_size,tstamp = struct.unpack("<Id", buf[128:128+12])
compressed_data = buf[header_len:]
if compressed_size != len(compressed_data):
return None
uncompressed_data = self.decompress_zlib_buffer(compressed_data)
if len(uncompressed_data) != EXPECTED_DATA_SIZE:
return None
return fname, tstamp, uncompressed_data
def fetch_latest(self):
'''fetch a thermal image'''
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
timeout = self.siyi.siyi_settings.fetch_timeout
if timeout >= 0:
tcp.settimeout(2)
try:
tcp.connect(self.uri)
except Exception:
return None
buf = bytearray()
while True:
try:
b = tcp.recv(1024)
except Exception:
break
if not b:
break
buf += b
if len(buf) != 128 + 8 + EXPECTED_DATA_SIZE:
return None
fname = buf[:128].decode("utf-8").strip('\x00')
tstamp, = struct.unpack("<d", buf[128:128+8])
data = buf[128+8:]
return fname, tstamp, data
def save_image(self, fname, tstamp, data):
'''same thermal image in thermal/ directory'''
fname = os.path.basename(fname)[:-4]
tstr = datetime.datetime.fromtimestamp(tstamp).strftime("%Y_%m_%d_%H_%M_%S")
subsec = tstamp - math.floor(tstamp)
millis = int(subsec * 1000)
fname = "%s_%s_%03u.bin" % (fname, tstr, millis)
fname = os.path.join(self.logdir, 'thermal', fname)
f = open(fname, 'wb')
f.write(data)
f.close()
os.utime(fname, (tstamp, tstamp))
def create_colormap_threshold(self, threshold):
'''create a yellow->red colormap for a given threshold'''
def pixel(c):
p = np.zeros((1,1,3), np.uint8)
p[:] = c
return p
lightyellow = pixel((255,255,0))
red = pixel((255,0,0))
white = pixel((threshold,threshold,threshold))
black = pixel((0,0,0))
threshold = mp_util.constrain(threshold, 1, 255)
lut1 = cv2.resize(np.concatenate((black,white), axis=0), (1,threshold), interpolation=cv2.INTER_CUBIC)
lut2 = cv2.resize(np.concatenate((lightyellow,red), axis=0), (1,256-threshold), interpolation=cv2.INTER_CUBIC)
lut = np.concatenate((lut1, lut2), axis=0)
return lut
def create_colormap_dict(self):
'''create a yellow->red colormap for all thresholds'''
ret = dict()
for i in range(256):
ret[i] = self.create_colormap_threshold(i)
return ret
def set_threshold(self, threshold_value):
'''set pixel value for thermal colormap'''
if self.im is not None:
self.im.set_colormap_index(threshold_value)
def set_title(self, title):
"""set image title"""
if self.im is None:
return
self.im.set_title(title)
def get_pixel_temp(self, event):
"""get temperature of a pixel"""
x = event.x
y = event.y
if self.last_data is None:
return -1
try:
p = self.last_data[y*640+x]
return p - C_TO_KELVIN
except Exception:
return -1
def end_tracking(self):
'''end object tracking'''
self.tracking = False
if self.im is not None:
self.im.end_tracking()
def update_title(self):
"""update thermal view title"""
self.set_title("RawThermal(%u): (%.1fC to %.1fC) %.1fC (mode %s)" % (self.image_count, self.tmin, self.tmax,
self.mouse_temp, self.siyi.click_mode))
def xy_to_latlon(self, x, y):
'''convert x,y pixel coordinates to a latlon tuple'''
(xres, yres) = self.res
x = (2 * x / float(xres)) - 1.0
y = (2 * y / float(yres)) - 1.0
aspect_ratio = float(xres) / yres
FOV = self.FOV
slant_range = self.siyi.get_slantrange(x, y, FOV, aspect_ratio)
if slant_range is None:
return None
return self.siyi.get_latlonalt(slant_range, x, y, FOV, aspect_ratio)
def check_events(self):
"""check for image events"""
if self.im is None:
return
if not self.im.is_alive():
self.im = None
return
for event in self.im.events():
if isinstance(event, MPMenuItem):
if event.returnkey.startswith("Mode:"):
self.siyi.click_mode = event.returnkey[5:]
print("ViewMode: %s" % self.siyi.click_mode)
elif event.returnkey.startswith("Marker:"):
self.siyi.handle_marker(event.returnkey[7:])
elif event.returnkey == "fitWindow":
self.im.fit_to_window()
elif event.returnkey == "fullSize":
self.im.full_size()
continue
if isinstance(event, MPImageTrackPos):
if not self.tracking:
continue
latlonalt = self.xy_to_latlon(event.x, event.y)
if latlonalt is None:
return
self.siyi.set_target(latlonalt[0], latlonalt[1], latlonalt[2])
continue
if isinstance(event, MPImageFrameCounter):
self.frame_counter = event.frame
continue
if event.ClassName == "wxMouseEvent":
self.mouse_temp = self.get_pixel_temp(event)
self.update_title()
if (
event.ClassName == "wxMouseEvent"
and event.leftIsDown
and self.siyi is not None
):
latlonalt = self.xy_to_latlon(event.x, event.y)
if latlonalt is None:
continue
if event.shiftDown:
(xres,yres) = self.res
twidth = int(yres*0.01*self.siyi.siyi_settings.track_size_pct)
self.siyi.end_tracking()
self.im.start_tracker(event.x, event.y, twidth, twidth)
self.tracking = True
elif event.controlDown:
self.siyi.end_tracking()
else:
self.siyi.camera_click(self.siyi.click_mode, latlonalt)
|
class RawThermal:
'''handle raw thermal image'''
def __init__(self, siyi, res):
pass
def fetch_loop(self):
'''main thread'''
pass
def in_history(self, latlon):
'''check if latlon in the history'''
pass
def handle_auto_flag(self):
pass
def display_image(self, fname, data):
'''display an image'''
pass
def decompress_zlib_buffer(self, compressed_buffer):
pass
def fetch_latest_compressed(self):
'''fetch a compressed thermal image'''
pass
def fetch_latest_compressed(self):
'''fetch a thermal image'''
pass
def save_image(self, fname, tstamp, data):
'''same thermal image in thermal/ directory'''
pass
def create_colormap_threshold(self, threshold):
'''create a yellow->red colormap for a given threshold'''
pass
def pixel(c):
pass
def create_colormap_dict(self):
'''create a yellow->red colormap for all thresholds'''
pass
def set_threshold(self, threshold_value):
'''set pixel value for thermal colormap'''
pass
def set_title(self, title):
'''set image title'''
pass
def get_pixel_temp(self, event):
'''get temperature of a pixel'''
pass
def end_tracking(self):
'''end object tracking'''
pass
def update_title(self):
'''update thermal view title'''
pass
def xy_to_latlon(self, x, y):
'''convert x,y pixel coordinates to a latlon tuple'''
pass
def check_events(self):
'''check for image events'''
pass
| 20 | 16 | 19 | 2 | 16 | 1 | 4 | 0.07 | 0 | 14 | 4 | 0 | 18 | 19 | 18 | 18 | 375 | 53 | 300 | 108 | 280 | 22 | 279 | 106 | 259 | 18 | 0 | 3 | 79 |
7,111 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SecureCommand.py
|
MAVProxy.modules.mavproxy_SecureCommand.SecureCommandModule
|
class SecureCommandModule(mp_module.MPModule):
def __init__(self, mpstate):
super(SecureCommandModule, self).__init__(mpstate, "SecureCommand", "SecureCommand Support", public = True)
self.add_command('securecommand', self.cmd_securecommand, "SecureCommand control",
["<getsessionkey|getpublickeys|setpublickeys|removepublickeys|setconfig>", "set (SECURECOMMANDSETTING)"])
from MAVProxy.modules.lib.mp_settings import MPSetting
self.SecureCommand_settings = mp_settings.MPSettings([
MPSetting("private_keyfile", str, None),
])
self.add_completion_function('(SECURECOMMANDSETTING)',
self.SecureCommand_settings.completion)
self.session_key = None
self.public_keys = [None]*10
self.sequence = random.randint(0, 0xFFFFFFFF)
self.sent_sequence = None
def cmd_securecommand(self, args):
'''securecommand command parser'''
usage = "usage: securecommand <set|getsessionkey|getpublickeys|setpublickeys|removepublickeys|setconfig>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
self.SecureCommand_settings.command(args[1:])
elif args[0] == "getsessionkey":
self.cmd_getsessionkey()
elif args[0] == "getpublickeys":
self.cmd_getpublickeys(args[1:])
elif args[0] == "setpublickeys":
self.cmd_setpublickeys(args[1:])
elif args[0] == "removepublickeys":
self.cmd_removepublickeys(args[1:])
elif args[0] == "setconfig":
self.cmd_setconfig(args[1:])
else:
print(usage)
def advance_sequence(self):
'''add one to sequence'''
self.sequence = (self.sequence+1) & 0xFFFFFFFF
def get_private_key(self):
'''get private key, return 32 byte key or None'''
if self.SecureCommand_settings.private_keyfile is None:
return None
try:
d = open(self.SecureCommand_settings.private_keyfile,'r').read()
except Exception as ex:
return None
ktype = "PRIVATE_KEYV1:"
if not d.startswith(ktype):
return None
return base64.b64decode(d[len(ktype):])
def read_public_key(self, keyfile):
'''read a public key, return 32 byte key or None'''
try:
d = open(keyfile,'r').read()
except Exception as ex:
return None
ktype = "PUBLIC_KEYV1:"
if not d.startswith(ktype):
return None
return base64.b64decode(d[len(ktype):])
def have_private_key(self):
'''return true if we have a valid private key'''
return self.get_private_key() is not None
def make_signature(self, seq, command, data):
'''make a signature'''
private_key = self.get_private_key()
d = struct.pack("<II", seq, command)
d += data
if command != mavutil.mavlink.SECURE_COMMAND_GET_SESSION_KEY:
if self.session_key is None:
print("No session key")
raise Exception("No session key")
d += self.session_key
self.sent_sequence = seq
return monocypher.signature_sign(private_key, d)
def pad_data(self, data, dlen=220):
'''pad data with 0x00 to given length'''
clen = len(data)
plen = dlen-clen
return data + bytearray([0]*plen)
def cmd_getsessionkey(self):
'''request session key'''
if not self.have_private_key():
print("No private key set")
return
sig = self.make_signature(self.sequence, mavutil.mavlink.SECURE_COMMAND_GET_SESSION_KEY, bytes())
self.master.mav.secure_command_send(self.target_system, self.target_component,
self.sequence, mavutil.mavlink.SECURE_COMMAND_GET_SESSION_KEY,
0, len(sig), self.pad_data(sig))
self.advance_sequence()
def cmd_getpublickeys(self, args):
'''get public keys'''
if not self.have_private_key():
print("No private key set")
return
if not self.session_key:
print("No session key")
return
idx = 0
nkeys = 6
if len(args) > 0:
idx = int(args[0])
if len(args) > 1:
nkeys = int(args[1])
req = struct.pack("<BB", idx, nkeys)
sig = self.make_signature(self.sequence, mavutil.mavlink.SECURE_COMMAND_GET_PUBLIC_KEYS, req)
self.master.mav.secure_command_send(self.target_system, self.target_component,
self.sequence, mavutil.mavlink.SECURE_COMMAND_GET_PUBLIC_KEYS,
len(req), len(sig), self.pad_data(req+sig))
self.advance_sequence()
def cmd_removepublickeys(self, args):
'''remove public keys'''
if not self.have_private_key():
print("No private key set")
return
if not self.session_key:
print("No session key")
return
if len(args) != 2:
print("Usage: removepublickeys INDEX COUNT")
return
idx = int(args[0])
nkeys = int(args[1])
req = struct.pack("<BB", idx, nkeys)
sig = self.make_signature(self.sequence, mavutil.mavlink.SECURE_COMMAND_REMOVE_PUBLIC_KEYS, req)
self.master.mav.secure_command_send(self.target_system, self.target_component,
self.sequence, mavutil.mavlink.SECURE_COMMAND_REMOVE_PUBLIC_KEYS,
len(req), len(sig), self.pad_data(req+sig))
self.advance_sequence()
def cmd_setpublickeys(self, args):
'''set public keys'''
if not self.have_private_key():
print("No private key set")
return
if not self.session_key:
print("No session key")
return
if len(args) < 2:
print("Usage: setpublickeys keyindex KEYFILES...")
return
idx = int(args[0])
keys = []
for kfile in args[1:]:
for fname in sorted(glob.glob(kfile)):
k = self.read_public_key(fname)
if k is None:
print("Unable to load keyfile %s" % fname)
return
print("Loaded key %s" % fname)
keys.append(k)
if len(keys) > 6:
print("Too many keys %u - max is 6" % len(keys))
return
if len(keys) == 0:
print("No keys found")
return
req = struct.pack("<B", idx)
for k in keys:
req += k
sig = self.make_signature(self.sequence, mavutil.mavlink.SECURE_COMMAND_SET_PUBLIC_KEYS, req)
self.master.mav.secure_command_send(self.target_system, self.target_component,
self.sequence, mavutil.mavlink.SECURE_COMMAND_SET_PUBLIC_KEYS,
len(req), len(sig), self.pad_data(req+sig))
print("Sent %u public keys starting at index %u" % (len(keys), idx))
self.advance_sequence()
def cmd_setconfig(self, args):
'''set configuration parameters'''
if not self.have_private_key():
print("No private key set")
return
if not self.session_key:
print("No session key")
return
if len(args) < 1:
print("Usage: setconfig PARAM=VALUE...")
return
req = bytearray()
for i in range(len(args)):
p = args[i]
req += p.encode('utf-8')
if i < len(args)-1:
req += bytearray([0])
sig = self.make_signature(self.sequence, mavutil.mavlink.SECURE_COMMAND_SET_REMOTEID_CONFIG, req)
self.master.mav.secure_command_send(self.target_system, self.target_component,
self.sequence, mavutil.mavlink.SECURE_COMMAND_SET_REMOTEID_CONFIG,
len(req), len(sig), self.pad_data(req+sig))
print("Sent %u config commands" % len(args))
self.advance_sequence()
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == "SECURE_COMMAND_REPLY":
if m.sequence != self.sent_sequence:
print("Invalid reply sequence")
return
m.sent_sequence = None
if m.operation == mavutil.mavlink.SECURE_COMMAND_GET_SESSION_KEY:
if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
self.session_key = bytearray(m.data[:m.data_length])
print("Got session key length=%u" % len(self.session_key))
else:
print("Get session key failed: %u" % m.result)
if m.operation == mavutil.mavlink.SECURE_COMMAND_GET_PUBLIC_KEYS:
if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
idx = m.data[0]
if idx >= len(self.public_keys):
print("Invalid key index %u" % idx)
return
keys = bytearray(m.data[1:m.data_length])
numkeys = len(keys) // 32
if numkeys == 0:
print("No public keys returned")
return
for i in range(idx, numkeys):
self.public_keys[i] = keys[32*i:32*(i+1)]
keyfile = "public_key%u.dat" % i
open(keyfile, "w").write("PUBLIC_KEYV1:" + base64.b64encode(self.public_keys[i]).decode('utf-8') + "\n")
print("Wrote %s" % keyfile)
print("Got public keys %u to %u" % (idx, numkeys+idx-1))
else:
print("Get public keys failed: %u" % m.result)
if m.operation == mavutil.mavlink.SECURE_COMMAND_SET_PUBLIC_KEYS:
if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
print("Set public keys OK")
else:
print("Set public keys failed: %u" % m.result)
if m.operation == mavutil.mavlink.SECURE_COMMAND_REMOVE_PUBLIC_KEYS:
if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
print("Remove public keys OK")
else:
print("Remove public keys failed: %u" % m.result)
|
class SecureCommandModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_securecommand(self, args):
'''securecommand command parser'''
pass
def advance_sequence(self):
'''add one to sequence'''
pass
def get_private_key(self):
'''get private key, return 32 byte key or None'''
pass
def read_public_key(self, keyfile):
'''read a public key, return 32 byte key or None'''
pass
def have_private_key(self):
'''return true if we have a valid private key'''
pass
def make_signature(self, seq, command, data):
'''make a signature'''
pass
def pad_data(self, data, dlen=220):
'''pad data with 0x00 to given length'''
pass
def cmd_getsessionkey(self):
'''request session key'''
pass
def cmd_getpublickeys(self, args):
'''get public keys'''
pass
def cmd_removepublickeys(self, args):
'''remove public keys'''
pass
def cmd_setpublickeys(self, args):
'''set public keys'''
pass
def cmd_setconfig(self, args):
'''set configuration parameters'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
| 15 | 13 | 17 | 0 | 15 | 1 | 5 | 0.06 | 1 | 9 | 2 | 0 | 14 | 5 | 14 | 52 | 249 | 19 | 217 | 57 | 201 | 13 | 193 | 55 | 177 | 14 | 2 | 4 | 63 |
7,112 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_adsb.py
|
MAVProxy.modules.mavproxy_adsb.ADSBModule
|
class ADSBModule(mp_module.MPModule):
def __init__(self, mpstate):
super(ADSBModule, self).__init__(mpstate, "adsb", "ADS-B data support", public = True)
self.threat_vehicles = {}
self.active_threat_ids = [] # holds all threat ids the vehicle is evading
self.add_command('adsb', self.cmd_ADSB, "adsb control",
["<status>", "set (ADSBSETTING)"])
self.ADSB_settings = mp_settings.MPSettings([("timeout", int, 5), # seconds
("threat_radius", int, 200), # meters
("show_threat_radius", bool, False),
# threat_radius_clear = threat_radius*threat_radius_clear_multiplier
("threat_radius_clear_multiplier", int, 2),
("show_threat_radius_clear", bool, False)])
self.add_completion_function('(ADSBSETTING)',
self.ADSB_settings.completion)
self.threat_detection_timer = mavutil.periodic_event(2)
self.threat_timeout_timer = mavutil.periodic_event(2)
self.tnow = self.get_time()
def cmd_ADSB(self, args):
'''adsb command parser'''
usage = "usage: adsb <set>"
if len(args) == 0:
print(usage)
return
if args[0] == "status":
print("total threat count: %u active threat count: %u" %
(len(self.threat_vehicles), len(self.active_threat_ids)))
for id in self.threat_vehicles.keys():
print("id: %s distance: %.2f m callsign: %s alt: %.2f" % (id,
self.threat_vehicles[id].distance,
self.threat_vehicles[id].state['callsign'],
self.threat_vehicles[id].state['altitude']))
elif args[0] == "set":
self.ADSB_settings.command(args[1:])
else:
print(usage)
def perform_threat_detection(self):
'''determine threats'''
# TODO: perform more advanced threat detection
threat_radius_clear = self.ADSB_settings.threat_radius * \
self.ADSB_settings.threat_radius_clear_multiplier
for id in self.threat_vehicles.keys():
if self.threat_vehicles[id].distance is not None:
if self.threat_vehicles[id].distance <= self.ADSB_settings.threat_radius and not self.threat_vehicles[id].is_evading_threat:
# if the threat is in the threat radius and not currently
# known to the module...
# set flag to action threat
self.threat_vehicles[id].is_evading_threat = True
if self.threat_vehicles[id].distance > threat_radius_clear and self.threat_vehicles[id].is_evading_threat:
# if the threat is known to the module and outside the
# threat clear radius...
# clear flag to action threat
self.threat_vehicles[id].is_evading_threat = False
self.active_threat_ids = [id for id in self.threat_vehicles.keys(
) if self.threat_vehicles[id].is_evading_threat]
def update_threat_distances(self, latlonalt):
'''update the distance between threats and vehicle'''
for id in self.threat_vehicles.keys():
threat_latlonalt = (self.threat_vehicles[id].state['lat'] * 1e-7,
self.threat_vehicles[id].state['lon'] * 1e-7,
self.threat_vehicles[id].state['altitude'])
self.threat_vehicles[id].h_distance = self.get_h_distance(latlonalt, threat_latlonalt)
self.threat_vehicles[id].v_distance = self.get_v_distance(latlonalt, threat_latlonalt)
# calculate and set the total distance between threat and vehicle
self.threat_vehicles[id].distance = sqrt(
self.threat_vehicles[id].h_distance**2 + (self.threat_vehicles[id].v_distance)**2)
def get_h_distance(self, latlonalt1, latlonalt2):
'''get the horizontal distance between threat and vehicle'''
(lat1, lon1, alt1) = latlonalt1
(lat2, lon2, alt2) = latlonalt2
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
dLat = lat2 - lat1
dLon = lon2 - lon1
# math as per mavextra.distance_two()
a = sin(0.5 * dLat)**2 + sin(0.5 * dLon)**2 * cos(lat1) * cos(lat2)
c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
return 6371 * 1000 * c
def get_v_distance(self, latlonalt1, latlonalt2):
'''get the horizontal distance between threat and vehicle'''
(lat1, lon1, alt1) = latlonalt1
(lat2, lon2, alt2) = latlonalt2
return alt2 - alt1
def check_threat_timeout(self):
'''check and handle threat time out'''
for id in self.threat_vehicles.keys():
if self.threat_vehicles[id].update_time == 0:
self.threat_vehicles[id].update_time = self.get_time()
dt = self.get_time() - self.threat_vehicles[id].update_time
if dt > self.ADSB_settings.timeout:
# if the threat has timed out...
del self.threat_vehicles[id] # remove the threat from the dict
for mp in self.module_matching('map*'):
# remove the threat from the map
mp.map.remove_object(id)
mp.map.remove_object(id+":circle")
# we've modified the dict we're iterating over, so
# we'll get any more timed-out threats next time we're
# called:
return
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == "ADSB_VEHICLE":
id = 'ADSB-' + str(m.ICAO_address)
if id not in self.threat_vehicles.keys(): # check to see if the vehicle is in the dict
# if not then add it
self.threat_vehicles[id] = ADSBVehicle(id=id, state=m.to_dict())
for mp in self.module_matching('map*'):
from MAVProxy.modules.lib import mp_menu
from MAVProxy.modules.mavproxy_map import mp_slipmap
self.threat_vehicles[id].menu_item = mp_menu.MPMenuItem(name=id, returnkey=None)
threat_radius = get_threat_radius(m)
selected_icon = get_threat_icon(m, self.threat_vehicles[id].icon)
if selected_icon is not None:
# draw the vehicle on the map
popup = mp_menu.MPMenuSubMenu('ADSB', items=[self.threat_vehicles[id].menu_item])
icon = mp.map.icon(selected_icon)
mp.map.add_object(mp_slipmap.SlipIcon(id, (m.lat * 1e-7, m.lon * 1e-7),
icon, layer=3, rotation=m.heading*0.01, follow=False,
trail=mp_slipmap.SlipTrail(colour=(0, 255, 255)),
popup_menu=popup))
if threat_radius > 0:
mp.map.add_object(mp_slipmap.SlipCircle(id+":circle", 3,
(m.lat * 1e-7, m.lon * 1e-7),
threat_radius, (0, 255, 255), linewidth=1))
else: # the vehicle is in the dict
# update the dict entry
self.threat_vehicles[id].update(m.to_dict(), self.get_time())
for mp in self.module_matching('map*'):
# update the map
ground_alt = self.module('terrain').ElevationModel.GetElevation(m.lat*1e-7, m.lon*1e-7)
alt_amsl = m.altitude * 0.001
if alt_amsl > 0:
alt = int(alt_amsl - ground_alt)
label = str(alt) + "m"
else:
label = None
mp.map.set_position(id, (m.lat * 1e-7, m.lon * 1e-7), rotation=m.heading*0.01, label=label, colour=(0,250,250))
mp.map.set_position(id+":circle", (m.lat * 1e-7, m.lon * 1e-7))
def idle_task(self):
'''called on idle'''
if self.threat_timeout_timer.trigger():
self.check_threat_timeout()
if self.threat_detection_timer.trigger():
self.perform_threat_detection()
|
class ADSBModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_ADSB(self, args):
'''adsb command parser'''
pass
def perform_threat_detection(self):
'''determine threats'''
pass
def update_threat_distances(self, latlonalt):
'''update the distance between threats and vehicle'''
pass
def get_h_distance(self, latlonalt1, latlonalt2):
'''get the horizontal distance between threat and vehicle'''
pass
def get_v_distance(self, latlonalt1, latlonalt2):
'''get the horizontal distance between threat and vehicle'''
pass
def check_threat_timeout(self):
'''check and handle threat time out'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def idle_task(self):
'''called on idle'''
pass
| 10 | 8 | 18 | 2 | 13 | 4 | 3 | 0.28 | 1 | 11 | 7 | 0 | 9 | 6 | 9 | 47 | 171 | 24 | 120 | 44 | 108 | 33 | 96 | 44 | 84 | 8 | 2 | 4 | 31 |
7,113 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/ntrip.py
|
MAVProxy.modules.lib.ntrip.NtripClient
|
class NtripClient(object):
def __init__(self,
user="",
port=2101,
caster="",
mountpoint="",
host=False,
lat=46,
lon=122,
height=1212,
ssl=False,
V2=False,
):
if sys.version_info.major >= 3:
user = bytearray(user, 'ascii')
self.user = base64.b64encode(user)
self.port = port
self.caster = caster
self.caster_ip = None
self.mountpoint = mountpoint
if not self.mountpoint.startswith("/"):
self.mountpoint = "/" + self.mountpoint
self.setPosition(lat, lon)
self.height = height
self.ssl = ssl
self.host = host
self.V2 = V2
self.socket = None
self.socket_pending = None
self.found_header = False
self.sent_header = False
# RTCM3 parser
self.rtcm3 = rtcm3.RTCM3()
self.last_id = None
self.dt_last_gga_sent = 0
self.last_connect_attempt = time.time()
if self.port == 443:
# force SSL on port 443
self.ssl = True
def setPosition(self, lat, lon):
self.lon = lon
self.lat = lat
def getMountPointString(self):
userstr = self.user
if sys.version_info.major >= 3:
userstr = str(userstr, 'ascii')
mountPointString = "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nAuthorization: Basic %s\r\n" % (
self.mountpoint, useragent, userstr)
if self.host or self.V2:
hostString = "Host: %s:%i\r\n" % (self.caster, self.port)
mountPointString += hostString
if self.V2:
mountPointString += "Ntrip-Version: Ntrip/2.0\r\n"
mountPointString += "\r\n"
return mountPointString
def getGGAByteString(self):
gga_msg = NMEAMessage(
"GP",
"GGA",
GET, # msgmode is expected by this lib
lat=self.lat,
NS="S" if self.lat < 0 else "N",
lon=self.lon,
EW="W" if self.lon < 0 else "E",
quality=1,
numSV=15,
HDOP=0,
alt=self.height,
altUnit="M",
sep=0,
sepUnit="M",
diffAge="",
diffStation=0,
)
raw_gga: bytes = gga_msg.serialize()
return raw_gga
def get_ID(self):
'''get ID of last packet'''
return self.last_id
def read(self):
if self.socket is None:
if self.socket_pending is None:
now = time.time()
# rate limit connection attempts
if now - self.last_connect_attempt < 1.0:
return None
self.last_connect_attempt = now
self.connect()
return None
if not self.found_header:
if not self.sent_header:
self.sent_header = True
time.sleep(0.1)
mps = self.getMountPointString()
if sys.version_info.major >= 3:
mps = bytearray(mps, 'ascii')
try:
self.socket.sendall(mps)
except ssl.SSLWantReadError:
self.sent_header = False
return None
except Exception:
self.socket = None
return None
try:
casterResponse = self.socket.recv(4096)
except ssl.SSLWantReadError:
return None
except IOError as e:
if e.errno == errno.EWOULDBLOCK:
return None
self.socket = None
casterResponse = ''
if sys.version_info.major >= 3:
# Ignore non ascii characters in HTTP response
casterResponse = str(casterResponse, 'ascii', 'ignore')
header_lines = casterResponse.split("\r\n")
is_ntrip_rev1 = False
for line in header_lines:
if line == "":
self.found_header = True
if line.find("SOURCETABLE") != -1:
raise NtripError("Mount point does not exist")
elif line.find("401 Unauthorized") != -1:
raise NtripError("Unauthorized request")
elif line.find("404 Not Found") != -1:
raise NtripError("Mount Point does not exist")
elif line.find(" 200 OK") != -1:
# Request was valid
if line == "ICY 200 OK":
is_ntrip_rev1 = True
self.send_gga()
# NTRIP Rev1 allows for responses that do not contain headers and an extra blank line.
if is_ntrip_rev1 and not self.found_header:
self.found_header = True
return None
# normal data read
while True:
try:
data = self.socket.recv(1)
except ssl.SSLWantReadError:
return None
except IOError as e:
if e.errno == errno.EWOULDBLOCK:
return None
self.socket.close()
self.socket = None
return None
except Exception:
self.socket.close()
self.socket = None
return None
if len(data) == 0:
self.socket.close()
self.socket = None
return None
if self.rtcm3.read(data):
self.last_id = self.rtcm3.get_packet_ID()
return self.rtcm3.get_packet()
def connect(self):
'''connect to NTRIP server'''
self.sent_header = False
self.found_header = False
# use a non-blocking connect to prevent blocking of mavproxy main thread
if self.socket_pending is not None:
read_ok, write_ok, err = select.select([], [self.socket_pending], [], 0)
if self.socket_pending in write_ok:
err = self.socket_pending.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if err == 0:
self.socket = self.socket_pending
self.socket_pending = None
self.rtcm3.reset()
return True
else:
self.socket_pending = None
return
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(0)
if self.ssl:
sock = ssl.wrap_socket(sock)
try:
if self.caster_ip is None:
try:
self.caster_ip = socket.gethostbyname(self.caster)
except Exception:
return False
if self.caster_ip is None:
return False
error_indicator = sock.connect_ex((self.caster_ip, self.port))
self.socket_pending = sock
return False
except Exception as ex:
return False
if error_indicator == 0:
sock.setblocking(0)
self.socket = sock
self.rtcm3.reset()
return True
return False
def readLoop(self):
while True:
data = self.read()
if data is None:
continue
print("got: ", len(data))
def send_gga(self):
gga = self.getGGAByteString()
try:
self.socket.sendall(gga)
self.dt_last_gga_sent = time.time()
except Exception:
self.socket = None
|
class NtripClient(object):
def __init__(self,
user="",
port=2101,
caster="",
mountpoint="",
host=False,
lat=46,
lon=122,
height=1212,
ssl=False,
V2=False,
):
pass
def setPosition(self, lat, lon):
pass
def getMountPointString(self):
pass
def getGGAByteString(self):
pass
def get_ID(self):
'''get ID of last packet'''
pass
def read(self):
pass
def connect(self):
'''connect to NTRIP server'''
pass
def readLoop(self):
pass
def send_gga(self):
pass
| 10 | 2 | 24 | 1 | 22 | 1 | 6 | 0.05 | 1 | 5 | 1 | 0 | 9 | 19 | 9 | 9 | 225 | 13 | 202 | 59 | 181 | 11 | 169 | 46 | 159 | 28 | 1 | 4 | 56 |
7,114 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/multiproc_util.py
|
MAVProxy.modules.lib.multiproc_util.WrapMMap
|
class WrapMMap(object):
'''Wrap a memory map object for pickling
This is a pickleable wrapper for a mmap.mmap object
returned from the builtin function mmap.mmap(fileno, length, ...)
The wrapper restores the mmap's seek pointer (offset).
'''
# mmap does not retain the filehandle and data_len as attributes
# when it is constructed, so it is necessary to pass them as args
# to the wrapper
def __init__(self, mm, filehandle, data_len):
# the mmap is not pickled
self._mm = mm
# state for pickling - populated in __getstate__
self._filehandle = WrapFileHandle(filehandle)
self._data_len = data_len
self._offset = None
def unwrap(self):
'''Returns the encapsulated object'''
return self._mm
def __getstate__(self):
# capture the mmap state
self._offset = self._mm.tell()
# copy the dict since we change it
odict = self.__dict__.copy()
# remove the _mm entry
del odict['_mm']
return odict
def __setstate__(self, dict):
# reopen mmap
filehandle = dict['_filehandle'].unwrap()
data_len = dict['_data_len']
mm = None
if platform.system() == "Windows":
mm = mmap.mmap(filehandle.fileno(), data_len, None, mmap.ACCESS_READ)
else:
mm = mmap.mmap(filehandle.fileno(), data_len, mmap.MAP_PRIVATE, mmap.PROT_READ)
# set the seek pointer
offset = dict['_offset']
mm.seek(offset)
# update attributes
self.__dict__.update(dict)
# restore the mmap
self._mm = mm
|
class WrapMMap(object):
'''Wrap a memory map object for pickling
This is a pickleable wrapper for a mmap.mmap object
returned from the builtin function mmap.mmap(fileno, length, ...)
The wrapper restores the mmap's seek pointer (offset).
'''
def __init__(self, mm, filehandle, data_len):
pass
def unwrap(self):
'''Returns the encapsulated object'''
pass
def __getstate__(self):
pass
def __setstate__(self, dict):
pass
| 5 | 2 | 11 | 2 | 6 | 3 | 1 | 0.72 | 1 | 2 | 1 | 0 | 4 | 4 | 4 | 4 | 58 | 15 | 25 | 14 | 20 | 18 | 24 | 14 | 19 | 2 | 1 | 1 | 5 |
7,115 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/multiproc_util.py
|
MAVProxy.modules.lib.multiproc_util.WrapFileHandle
|
class WrapFileHandle(object):
'''Wrap a filehandle object for pickling
This is a pickleable wrapper for a filehandle object
returned from the builtin function open(file, mode='r', ...)
The wrapper restores the filehandle seek pointer (offset) and preserves
the following arguments to open():
- name (file)
- mode
- encoding
- errors
- newline
'''
def __init__(self, filehandle):
# the filehandle is not pickled
self._filehandle = filehandle
# state for pickling - populated in __getstate__
self._name = None
self._mode = None
self._encoding = None
self._errors = None
self._newlines = None
self._offset = None
# TODO: these are additional args to open() but it is less
# clear where to acquire their state when persisting
# self._buffering = None
# self._closefd = None
# self._opener = None
def unwrap(self):
'''Returns the encapsulated object'''
return self._filehandle
def __getstate__(self):
# capture the filehandle state
self._name = self._filehandle.name
self._mode = self._filehandle.mode
self._encoding = self._filehandle.encoding
self._errors = self._filehandle.errors
self._newlines = self._filehandle.newlines
self._offset = self._filehandle.tell()
# copy the dict since we change it
odict = self.__dict__.copy()
# remove the _filehandle entry
del odict['_filehandle']
return odict
def __setstate__(self, dict):
# reopen file
name = dict['_name']
mode = dict['_mode']
encoding = dict['_encoding']
errors = dict['_errors']
newlines = dict['_newlines']
filehandle = open(name, mode=mode, encoding=encoding, errors=errors, newline=newlines)
# set the seek pointer
offset = dict['_offset']
filehandle.seek(offset)
# update attributes
self.__dict__.update(dict)
# restore the filehandle
self._filehandle = filehandle
|
class WrapFileHandle(object):
'''Wrap a filehandle object for pickling
This is a pickleable wrapper for a filehandle object
returned from the builtin function open(file, mode='r', ...)
The wrapper restores the filehandle seek pointer (offset) and preserves
the following arguments to open():
- name (file)
- mode
- encoding
- errors
- newline
'''
def __init__(self, filehandle):
pass
def unwrap(self):
'''Returns the encapsulated object'''
pass
def __getstate__(self):
pass
def __setstate__(self, dict):
pass
| 5 | 2 | 12 | 2 | 8 | 3 | 1 | 0.81 | 1 | 0 | 0 | 0 | 4 | 7 | 4 | 4 | 74 | 16 | 32 | 20 | 27 | 26 | 32 | 20 | 27 | 1 | 1 | 0 | 4 |
7,116 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/multiproc_util.py
|
MAVProxy.modules.lib.multiproc_util.MPDataLogChildTask
|
class MPDataLogChildTask(MPChildTask):
'''Manage a MAVProxy child task that expects a dataflash or telemetry log'''
def __init__(self, *args, **kwargs):
'''
Parameters
----------
mlog : DFReader / mavmmaplog
A dataflash or telemetry log
'''
super(MPDataLogChildTask, self).__init__(*args, **kwargs)
# all attributes are implicitly passed to the child process
self._mlog = kwargs['mlog']
# @override
def wrap(self):
'''Apply custom pickle wrappers to non-pickleable attributes'''
# wrap filehandle and mmap in mlog for pickling
if hasattr(self._mlog,'filehandle'):
filehandle = self._mlog.filehandle
elif hasattr(self._mlog,'f'):
filehandle = self._mlog.f
data_map = self._mlog.data_map
data_len = self._mlog.data_len
if hasattr(self._mlog,'filehandle'):
self._mlog.filehandle = WrapFileHandle(filehandle)
elif hasattr(self._mlog,'f'):
self._mlog.f = WrapFileHandle(filehandle)
self._mlog.data_map = WrapMMap(data_map, filehandle, data_len)
# @override
def unwrap(self):
'''Unwrap custom pickle wrappers of non-pickleable attributes'''
# restore the state of mlog
if hasattr(self._mlog,'filehandle'):
self._mlog.filehandle = self._mlog.filehandle.unwrap()
elif hasattr(self._mlog,'f'):
self._mlog.f = self._mlog.f.unwrap()
self._mlog.data_map = self._mlog.data_map.unwrap()
@property
def mlog(self):
'''The dataflash or telemetry log (DFReader / mavmmaplog)'''
return self._mlog
|
class MPDataLogChildTask(MPChildTask):
'''Manage a MAVProxy child task that expects a dataflash or telemetry log'''
def __init__(self, *args, **kwargs):
'''
Parameters
----------
mlog : DFReader / mavmmaplog
A dataflash or telemetry log
'''
pass
def wrap(self):
'''Apply custom pickle wrappers to non-pickleable attributes'''
pass
def unwrap(self):
'''Unwrap custom pickle wrappers of non-pickleable attributes'''
pass
@property
def mlog(self):
'''The dataflash or telemetry log (DFReader / mavmmaplog)'''
pass
| 6 | 5 | 10 | 1 | 6 | 3 | 3 | 0.6 | 1 | 3 | 2 | 3 | 4 | 1 | 4 | 16 | 48 | 8 | 25 | 10 | 19 | 15 | 21 | 9 | 16 | 5 | 2 | 1 | 10 |
7,117 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/multiproc_util.py
|
MAVProxy.modules.lib.multiproc_util.MPChildTask
|
class MPChildTask(object):
'''Manage a MAVProxy child task
MAVProxy child tasks typically require access to the dataflash
or telemetry logs. For processes started using the `spawn`
start method this requires the arguments to the child process
to be pickleable, which is not the case for file handles and
memory mapped files.
This class provides two functions `wrap` and `unwrap` that are
called before and after the parent spawns the child process,
and in the child process itself before the public child task
is called. Custom pickle functions and class wrappers / unwrappers
should be placed in these two functions.
'''
def __init__(self, *args, **kwargs):
self._child_pipe_recv, self._parent_pipe_send = multiproc.Pipe(duplex=False)
self._close_event = multiproc.Event()
self._close_event.clear()
self._child = None
# @abstractmethod
def wrap(self):
'''Apply custom pickle wrappers to non-pickleable attributes'''
pass
# @abstractmethod
def unwrap(self):
'''Unwrap custom pickle wrappers of non-pickleable attributes'''
pass
# @abstractmethod
def child_task(self):
'''Launch the child function or application'''
pass
def start(self):
'''Apply custom pickle wrappers then start the child process'''
# apply lock while the task is started as wrapping may mutate state
with mutex:
self.wrap()
try:
if os.name == 'nt':
# Windows can't pickle the mavlog object, thus can't spin off
self._child = threading.Thread(target=self._child_task)
else:
self._child = multiproc.Process(target=self._child_task)
self._child.start()
finally:
if not os.name == 'nt':
self.unwrap()
# deny the parent access to the child end of the pipe
self.child_pipe_recv.close()
def _child_task(self):
'''A non-public child task that calls unwrap before running the public child task'''
# deny the child access to the parent end of the pipe and unwrap
self.parent_pipe_send.close()
self.unwrap()
# call child task (in sub-class)
self.child_task()
# set the close event when the task is complete
self.close_event.set()
@property
def child_pipe_recv(self):
'''The child end of the pipe for receiving data from the parent'''
return self._child_pipe_recv
@property
def parent_pipe_send(self):
'''The parent end of the pipe for sending data to the child'''
return self._parent_pipe_send
@property
def close_event(self):
'''A multiprocessing close event'''
return self._close_event
@property
def child(self):
'''The child process'''
return self._child
def close(self):
'''Set the close event and join the process'''
self.close_event.set()
if self.is_alive():
self.child.join(2)
def is_alive(self):
'''Returns True if the child process is alive'''
return self.child.is_alive()
|
class MPChildTask(object):
'''Manage a MAVProxy child task
MAVProxy child tasks typically require access to the dataflash
or telemetry logs. For processes started using the `spawn`
start method this requires the arguments to the child process
to be pickleable, which is not the case for file handles and
memory mapped files.
This class provides two functions `wrap` and `unwrap` that are
called before and after the parent spawns the child process,
and in the child process itself before the public child task
is called. Custom pickle functions and class wrappers / unwrappers
should be placed in these two functions.
'''
def __init__(self, *args, **kwargs):
pass
def wrap(self):
'''Apply custom pickle wrappers to non-pickleable attributes'''
pass
def unwrap(self):
'''Unwrap custom pickle wrappers of non-pickleable attributes'''
pass
def child_task(self):
'''Launch the child function or application'''
pass
def start(self):
'''Apply custom pickle wrappers then start the child process'''
pass
def _child_task(self):
'''A non-public child task that calls unwrap before running the public child task'''
pass
@property
def child_pipe_recv(self):
'''The child end of the pipe for receiving data from the parent'''
pass
@property
def parent_pipe_send(self):
'''The parent end of the pipe for sending data to the child'''
pass
@property
def close_event(self):
'''A multiprocessing close event'''
pass
@property
def child_task(self):
'''The child process'''
pass
def close_event(self):
'''Set the close event and join the process'''
pass
def is_alive(self):
'''Returns True if the child process is alive'''
pass
| 17 | 12 | 6 | 1 | 4 | 1 | 1 | 0.67 | 1 | 1 | 0 | 1 | 12 | 4 | 12 | 12 | 105 | 25 | 48 | 20 | 31 | 32 | 42 | 16 | 29 | 3 | 1 | 3 | 15 |
7,118 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/multiproc.py
|
MAVProxy.modules.lib.multiproc.PipeQueue
|
class PipeQueue(object):
'''simulate a queue using a pipe. This is used to avoid a problem with
pipes on MacOS, while still keeping similar syntax'''
def __init__(self):
(self.sender,self.receiver) = Pipe()
self.alive = True
self.pending = []
def close(self):
self.alive = False
self.sender.close()
self.receiver.close()
def put(self, *args):
if not self.alive:
return
try:
self.sender.send(*args)
except Exception:
self.close()
def fill(self):
if not self.alive:
return
try:
while self.receiver.poll():
m = self.receiver.recv()
self.pending.append(m)
except Exception:
self.alive = False
self.close()
def get(self):
if not self.alive:
return None
self.fill()
if len(self.pending) > 0:
return self.pending.pop(0)
return None
def qsize(self):
self.fill()
return len(self.pending)
def empty(self):
return self.qsize() == 0
|
class PipeQueue(object):
'''simulate a queue using a pipe. This is used to avoid a problem with
pipes on MacOS, while still keeping similar syntax'''
def __init__(self):
pass
def close(self):
pass
def put(self, *args):
pass
def fill(self):
pass
def get(self):
pass
def qsize(self):
pass
def empty(self):
pass
| 8 | 1 | 5 | 0 | 5 | 0 | 2 | 0.05 | 1 | 1 | 0 | 0 | 7 | 4 | 7 | 7 | 46 | 6 | 38 | 12 | 30 | 2 | 38 | 12 | 30 | 4 | 1 | 2 | 14 |
7,119 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_widgets.py
|
MAVProxy.modules.lib.mp_widgets.ImagePanel
|
class ImagePanel(wx.Panel):
'''a resizable panel containing an image'''
def __init__(self, parent, img):
wx.Panel.__init__(self, parent, -1, size=(1, 1))
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.set_image(img)
self.Bind(wx.EVT_PAINT, self.on_paint)
def on_paint(self, event):
'''repaint the image'''
dc = wx.AutoBufferedPaintDC(self)
dc.DrawBitmap(self._bmp, 0, 0)
def set_image(self, img):
'''set the image to be displayed'''
with warnings.catch_warnings():
warnings.simplefilter('ignore')
if hasattr(img, 'shape'):
(width, height) = (img.shape[1], img.shape[0])
self._bmp = wx.BitmapFromBuffer(width, height, np.uint8(img)) # http://stackoverflow.com/a/16866833/2559632
elif hasattr(img, 'GetHeight'):
self._bmp = wx.BitmapFromImage(img)
else:
print("Unsupported image type: %s" % type(img))
return
self.SetMinSize((self._bmp.GetWidth(), self._bmp.GetHeight()))
|
class ImagePanel(wx.Panel):
'''a resizable panel containing an image'''
def __init__(self, parent, img):
pass
def on_paint(self, event):
'''repaint the image'''
pass
def set_image(self, img):
'''set the image to be displayed'''
pass
| 4 | 3 | 7 | 0 | 7 | 1 | 2 | 0.19 | 1 | 2 | 0 | 0 | 3 | 1 | 3 | 3 | 26 | 2 | 21 | 7 | 17 | 4 | 19 | 7 | 15 | 3 | 1 | 2 | 5 |
7,120 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_util.py
|
MAVProxy.modules.lib.mp_util.object_container
|
class object_container:
'''return a picklable object from an existing object,
containing all of the normal attributes of the original'''
def __init__(self, object, debug=False):
for v in dir(object):
if not v.startswith('__') and v not in ['this', 'ClassInfo', 'EventObject']:
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
a = getattr(object, v)
if (hasattr(a, '__call__') or
hasattr(a, '__swig_destroy__') or
str(a).find('Swig Object') != -1):
continue
if debug:
print(v, a)
setattr(self, v, a)
except Exception:
pass
|
class object_container:
'''return a picklable object from an existing object,
containing all of the normal attributes of the original'''
def __init__(self, object, debug=False):
pass
| 2 | 1 | 16 | 0 | 16 | 0 | 6 | 0.12 | 0 | 3 | 0 | 0 | 1 | 0 | 1 | 1 | 19 | 0 | 17 | 4 | 15 | 2 | 15 | 4 | 13 | 6 | 0 | 5 | 6 |
7,121 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_util.py
|
MAVProxy.modules.lib.mp_util.mp_position
|
class mp_position(object):
'''a position object from a local provider such as a NMEA GPS module'''
def __init__(self):
self.timestamp = None
self.latitude = None
self.longitude = None
self.altitude = None
self.ground_course = None
self.ground_speed = None
self.num_sats = None
def __str__(self):
return "%u satellites age=%.1fs lat=%.9f lon=%.9f alt=%.3f m spd=%.2f m/s course=%.2f deg" % (
self.num_sats,
time.time() - self.timestamp,
self.latitude, self.longitude, self.altitude,
self.ground_speed, self.ground_course)
|
class mp_position(object):
'''a position object from a local provider such as a NMEA GPS module'''
def __init__(self):
pass
def __str__(self):
pass
| 3 | 1 | 7 | 0 | 7 | 0 | 1 | 0.07 | 1 | 0 | 0 | 0 | 2 | 7 | 2 | 2 | 17 | 1 | 15 | 10 | 12 | 1 | 11 | 10 | 8 | 1 | 1 | 0 | 2 |
7,122 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_util.py
|
MAVProxy.modules.lib.mp_util.UTMGrid
|
class UTMGrid:
'''class to hold UTM grid position'''
def __init__(self, zone, easting, northing, hemisphere='S'):
self.zone = zone
self.easting = easting
self.northing = northing
self.hemisphere = hemisphere
def __str__(self):
return "%s %u %u %u" % (self.hemisphere, self.zone, self.easting, self.northing)
def latlon(self):
'''return (lat,lon) for the grid coordinates'''
from MAVProxy.modules.lib.ANUGA import lat_long_UTM_conversion
(lat, lon) = lat_long_UTM_conversion.UTMtoLL(self.northing, self.easting, self.zone, isSouthernHemisphere=(self.hemisphere=='S'))
lon = wrap_180(lon)
return (lat, lon)
|
class UTMGrid:
'''class to hold UTM grid position'''
def __init__(self, zone, easting, northing, hemisphere='S'):
pass
def __str__(self):
pass
def latlon(self):
'''return (lat,lon) for the grid coordinates'''
pass
| 4 | 2 | 4 | 0 | 4 | 0 | 1 | 0.15 | 0 | 0 | 0 | 0 | 3 | 4 | 3 | 3 | 17 | 2 | 13 | 10 | 8 | 2 | 13 | 10 | 8 | 1 | 0 | 0 | 3 |
7,123 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_example.py
|
MAVProxy.modules.mavproxy_example.example
|
class example(mp_module.MPModule):
def __init__(self, mpstate):
"""Initialise module"""
super(example, self).__init__(mpstate, "example", "")
self.status_callcount = 0
self.boredom_interval = 10 # seconds
self.last_bored = time.time()
self.packets_mytarget = 0
self.packets_othertarget = 0
self.example_settings = mp_settings.MPSettings(
[ ('verbose', bool, False),
])
self.add_command('example', self.cmd_example, "example module", ['status','set (LOGSETTING)'])
def usage(self):
'''show help on command line options'''
return "Usage: example <status|set>"
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())
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,
})
def boredom_message(self):
if self.example_settings.verbose:
return ("I'm very bored")
return ("I'm bored")
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)
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
|
class example(mp_module.MPModule):
def __init__(self, mpstate):
'''Initialise module'''
pass
def usage(self):
'''show help on command line options'''
pass
def cmd_example(self, args):
'''control behaviour of the module'''
pass
def status(self):
'''returns information about module'''
pass
def boredom_message(self):
pass
def idle_task(self):
'''called rapidly by mavproxy'''
pass
def mavlink_packet(self, m):
'''handle mavlink packets'''
pass
| 8 | 6 | 8 | 0 | 7 | 1 | 2 | 0.18 | 1 | 3 | 1 | 0 | 7 | 6 | 7 | 45 | 64 | 8 | 49 | 16 | 41 | 9 | 38 | 16 | 30 | 4 | 2 | 2 | 14 |
7,124 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_substitute.py
|
MAVProxy.modules.lib.mp_substitute.MAVSubstituteError
|
class MAVSubstituteError(Exception):
def __init__(self, message, inner_exception=None):
self.message = message
self.inner_exception = inner_exception
self.exception_info = sys.exc_info()
def __str__(self):
return self.message
|
class MAVSubstituteError(Exception):
def __init__(self, message, inner_exception=None):
pass
def __str__(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 12 | 7 | 0 | 7 | 6 | 4 | 0 | 7 | 6 | 4 | 1 | 3 | 0 | 2 |
7,125 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_substitute.py
|
MAVProxy.modules.lib.mp_substitute.MAVSubstitute
|
class MAVSubstitute(object):
'''simple templating system'''
def __init__(self,
start_var_token="${",
end_var_token="}",
checkmissing=True):
self.start_var_token = start_var_token
self.end_var_token = end_var_token
self.checkmissing = checkmissing
def find_end(self, text, start_token, end_token, ignore_end_token=None):
'''find the of a token.
Returns the offset in the string immediately after the matching end_token'''
if not text.startswith(start_token):
raise MAVSubstituteError("invalid token start")
offset = len(start_token)
nesting = 1
while nesting > 0:
idx1 = text[offset:].find(start_token)
idx2 = text[offset:].find(end_token)
# Check for false positives due to another similar token
# For example, make sure idx2 points to the second '}' in ${{field: ${name}}}
if ignore_end_token:
combined_token = ignore_end_token + end_token
if text[offset+idx2:offset+idx2+len(combined_token)] == combined_token:
idx2 += len(ignore_end_token)
if idx1 == -1 and idx2 == -1:
raise MAVSubstituteError("token nesting error")
if idx1 == -1 or idx1 > idx2:
offset += idx2 + len(end_token)
nesting -= 1
else:
offset += idx1 + len(start_token)
nesting += 1
return offset
def find_var_end(self, text):
'''find the of a variable'''
return self.find_end(text, self.start_var_token, self.end_var_token)
def substitute(self, text, subvars={},
checkmissing=None):
'''substitute variables in a string'''
if checkmissing is None:
checkmissing = self.checkmissing
while True:
idx = text.find(self.start_var_token)
if idx == -1:
return text
endidx = text[idx:].find(self.end_var_token)
if endidx == -1:
raise MAVSubstituteError('missing end of variable: %s' % text[idx:idx+10])
varname = text[idx+2:idx+endidx]
fullvar = varname
# allow default value after a :
def_value = None
colon = varname.find(':')
if colon != -1:
def_value = varname[colon+1:]
varname = varname[:colon]
if varname in subvars:
value = subvars[varname]
elif def_value is not None:
value = def_value
elif checkmissing:
raise MAVSubstituteError("unknown variable in '%s%s%s'" % (
self.start_var_token, varname, self.end_var_token))
else:
return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, checkmissing=False)
text = text.replace("%s%s%s" % (self.start_var_token, fullvar, self.end_var_token), str(value))
return text
|
class MAVSubstitute(object):
'''simple templating system'''
def __init__(self,
start_var_token="${",
end_var_token="}",
checkmissing=True):
pass
def find_end(self, text, start_token, end_token, ignore_end_token=None):
'''find the of a token.
Returns the offset in the string immediately after the matching end_token'''
pass
def find_var_end(self, text):
'''find the of a variable'''
pass
def substitute(self, text, subvars={},
checkmissing=None):
'''substitute variables in a string'''
pass
| 5 | 4 | 18 | 1 | 15 | 2 | 5 | 0.13 | 1 | 2 | 1 | 0 | 4 | 3 | 4 | 4 | 75 | 7 | 60 | 24 | 51 | 8 | 51 | 20 | 46 | 9 | 1 | 3 | 18 |
7,126 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_settings.py
|
MAVProxy.modules.lib.mp_settings.MPSettings
|
class MPSettings(object):
def __init__(self, vars, title='Settings'):
self._vars = {}
self._title = title
self._default_tab = 'Settings'
self._keys = []
self._callback = None
self._last_change = time.time()
for v in vars:
self.append(v)
def get_title(self):
'''return the title'''
return self._title
def get_setting(self, name):
'''return a MPSetting object'''
return self._vars[name]
def append(self, v):
'''add a new setting'''
if isinstance(v, MPSetting):
setting = v
else:
(name,type,default) = v
label = name
tab = None
if len(v) > 3:
label = v[3]
if len(v) > 4:
tab = v[4]
setting = MPSetting(name, type, default, label=label, tab=tab)
# when a tab name is set, cascade it to future settings
if setting.tab is None:
setting.tab = self._default_tab
else:
self._default_tab = setting.tab
self._vars[setting.name] = setting
self._keys.append(setting.name)
self._last_change = time.time()
def __getattr__(self, name):
try:
return self._vars[name].value
except Exception:
raise AttributeError
def __setattr__(self, name, value):
if name[0] == '_':
self.__dict__[name] = value
return
if name in self._vars:
self._vars[name].value = value
return
raise AttributeError
def set(self, name, value):
'''set a setting'''
if not name in self._vars:
raise AttributeError
setting = self._vars[name]
oldvalue = setting.value
if not setting.set(value):
print("Unable to set %s (want type=%s)" % (value, setting.type))
return False
if oldvalue != setting.value:
self._last_change = time.time()
if self._callback:
self._callback(setting)
return True
def get(self, name):
'''get a setting'''
if not name in self._vars:
raise AttributeError
setting = self._vars[name]
return setting.value
def show(self, v):
'''show settings'''
print("%20s %s" % (v, self._vars[v].describe()))
def show_pattern(self, pattern):
'''show all settings'''
for setting in sorted(self._vars):
if fnmatch.fnmatch(setting, pattern):
self.show(setting)
def show_all(self):
'''show all settings'''
self.show_pattern('*')
def list(self):
'''list all settings'''
return self._keys
def completion(self, text):
'''completion function for cmdline completion'''
return self.list()
def command(self, args):
'''control options from cmdline'''
if len(args) == 0:
self.show_all()
return
if args[0].find('*') != -1:
self.show_pattern(args[0])
return
if getattr(self, args[0], [None]) == [None]:
print("Unknown setting '%s'" % args[0])
return
if len(args) == 1:
self.show(args[0])
else:
self.set(args[0], args[1])
def set_callback(self, callback):
'''set a callback to be called on set()'''
self._callback = callback
def save(self, filename):
'''save settings to a file. Return True/False on success/failure'''
try:
f = open(filename, mode='w')
except Exception:
return False
for k in self.list():
f.write("%s=%s\n" % (k, self.get(k)))
f.close()
return True
def load(self, filename):
'''load settings from a file. Return True/False on success/failure'''
try:
f = open(filename, mode='r')
except Exception:
return False
while True:
line = f.readline()
if not line:
break
line = line.rstrip()
eq = line.find('=')
if eq == -1:
continue
name = line[:eq]
value = line[eq+1:]
self.set(name, value)
f.close()
return True
def last_change(self):
'''return last change time'''
return self._last_change
|
class MPSettings(object):
def __init__(self, vars, title='Settings'):
pass
def get_title(self):
'''return the title'''
pass
def get_setting(self, name):
'''return a MPSetting object'''
pass
def append(self, v):
'''add a new setting'''
pass
def __getattr__(self, name):
pass
def __setattr__(self, name, value):
pass
def set(self, name, value):
'''set a setting'''
pass
def get_title(self):
'''get a setting'''
pass
def show(self, v):
'''show settings'''
pass
def show_pattern(self, pattern):
'''show all settings'''
pass
def show_all(self):
'''show all settings'''
pass
def list(self):
'''list all settings'''
pass
def completion(self, text):
'''completion function for cmdline completion'''
pass
def command(self, args):
'''control options from cmdline'''
pass
def set_callback(self, callback):
'''set a callback to be called on set()'''
pass
def save(self, filename):
'''save settings to a file. Return True/False on success/failure'''
pass
def load(self, filename):
'''load settings from a file. Return True/False on success/failure'''
pass
def last_change(self):
'''return last change time'''
pass
| 19 | 15 | 8 | 0 | 7 | 1 | 2 | 0.13 | 1 | 3 | 1 | 0 | 18 | 6 | 18 | 18 | 158 | 21 | 121 | 41 | 102 | 16 | 118 | 41 | 99 | 5 | 1 | 2 | 43 |
7,127 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/ntrip.py
|
MAVProxy.modules.lib.ntrip.NtripError
|
class NtripError(Exception):
def __init__(self, message, inner_exception=None):
self.message = message
self.inner_exception = inner_exception
self.exception_info = sys.exc_info()
def __str__(self):
return self.message
|
class NtripError(Exception):
def __init__(self, message, inner_exception=None):
pass
def __str__(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 12 | 8 | 1 | 7 | 6 | 4 | 0 | 7 | 6 | 4 | 1 | 3 | 0 | 2 |
7,128 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_settings.py
|
MAVProxy.modules.lib.mp_settings.MPSetting
|
class MPSetting:
def __init__(self, name, type, default, label=None, tab=None,
range=None, increment=None, format=None,
digits=None, choice=None):
if label is None:
label = name
self.name = name
self.type = type
self.default = default
self.label = label
self.value = default
self.tab = tab
self.range = range
if range is not None:
# check syntax
(minv, maxv) = range
self.increment = increment
self.choice = choice
self.format = format
self.digits = digits
def describe(self):
if self.choice is not None:
for v in self.choice:
if isinstance(v, tuple):
(v, thisvalue) = v
if thisvalue == self.value:
return "%s(%d)" % (v, thisvalue)
return "%s" % self.value
def set(self, value):
'''set a setting'''
if value == 'None' and self.default is None:
value = None
if value is not None:
if self.type == bool:
if str(value).lower() in ['1', 'true', 'yes']:
value = True
elif str(value).lower() in ['0', 'false', 'no']:
value = False
else:
return False
else:
try:
value = self.type(value)
except:
return False
if self.range is not None:
(minv,maxv) = self.range
if value < minv or value > maxv:
print("Out of range (min=%f max=%f)" % (minv, maxv))
return False
if self.choice is not None:
found = False
options = []
for v in self.choice:
if isinstance(v, tuple):
(v, thisvalue) = v
else:
thisvalue = v
options.append(v)
if isinstance(value, self.type):
if thisvalue == value:
found = True
break
if isinstance(value, str) and v.lower() == value.lower():
found = True
value = thisvalue
break
if not found:
print("Must be one of %s" % str(options))
return False
self.value = value
return True
|
class MPSetting:
def __init__(self, name, type, default, label=None, tab=None,
range=None, increment=None, format=None,
digits=None, choice=None):
pass
def describe(self):
pass
def set(self, value):
'''set a setting'''
pass
| 4 | 1 | 24 | 0 | 23 | 1 | 8 | 0.03 | 0 | 3 | 0 | 0 | 3 | 11 | 3 | 3 | 74 | 2 | 70 | 25 | 64 | 2 | 64 | 23 | 60 | 16 | 0 | 4 | 24 |
7,129 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuTop
|
class MPMenuTop(object):
'''a MP top level menu'''
def __init__(self, items):
self.items = items
def add(self, items):
'''add a submenu'''
if not isinstance(items, list):
items = [items]
for m in items:
updated = False
for i in range(len(self.items)):
if self.items[i].name == m.name:
self.items[i] = m
updated = True
if not updated:
self.items.append(m)
def remove(self, items):
if not isinstance(items, list):
items = [items]
names = set([x.name for x in items])
self.items = list(filter(lambda x : x.name not in names, self.items))
def add_to_submenu(self, submenu_path, item):
'''
add an item to a submenu using a menu path array
'''
for m in self.items:
if m.name == submenu_path[0]:
m.add_to_submenu(submenu_path[1:], item)
return
# new submenu
if len(submenu_path) > 1:
self.add(MPMenuSubMenu(submenu_path[0], []))
self.add_to_submenu(submenu_path, item)
else:
self.add(MPMenuSubMenu(submenu_path[0], [item]))
def wx_menu(self):
'''return a wx.MenuBar() for the menu'''
from MAVProxy.modules.lib.wx_loader import wx
menubar = wx.MenuBar()
for i in range(len(self.items)):
m = self.items[i]
menubar.Append(m.wx_menu(), m.name)
return menubar
def find_selected(self, event):
'''find the selected menu item'''
for i in range(len(self.items)):
m = self.items[i]
ret = m.find_selected(event)
if ret is not None:
return ret
return None
|
class MPMenuTop(object):
'''a MP top level menu'''
def __init__(self, items):
pass
def add(self, items):
'''add a submenu'''
pass
def remove(self, items):
pass
def add_to_submenu(self, submenu_path, item):
'''
add an item to a submenu using a menu path array
'''
pass
def wx_menu(self):
'''return a wx.MenuBar() for the menu'''
pass
def find_selected(self, event):
'''find the selected menu item'''
pass
| 7 | 5 | 8 | 0 | 7 | 1 | 3 | 0.19 | 1 | 5 | 1 | 0 | 6 | 1 | 6 | 6 | 57 | 6 | 43 | 20 | 35 | 8 | 42 | 20 | 34 | 6 | 1 | 3 | 18 |
7,130 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuSubMenu
|
class MPMenuSubMenu(MPMenuGeneric):
'''a MP menu item'''
def __init__(self, name, items):
MPMenuGeneric.__init__(self)
self.name = name
self.items = items
def add(self, items, addto=None):
'''add more items to a sub-menu'''
if not isinstance(items, list):
items = [items]
for m in items:
updated = False
for i in range(len(self.items)):
try:
if self.items[i].name == m.name:
self.items[i] = m
updated = True
except Exception:
pass
if not updated:
self.items.append(m)
def remove(self, items):
'''remove items from a sub-menu'''
if not isinstance(items, list):
items = [items]
names = set([x.name for x in items])
self.items = list(filter(lambda x : x.name not in names, self.items))
def add_to_submenu(self, submenu_path, item):
'''add an item to a submenu using a menu path array'''
if len(submenu_path) == 0:
self.add(item)
return
for m in self.items:
if isinstance(m, MPMenuSubMenu) and submenu_path[0] == m.name:
m.add_to_submenu(submenu_path[1:], item)
return
self.add(MPMenuSubMenu(submenu_path[0], []))
self.add_to_submenu(submenu_path, item)
def combine(self, submenu):
'''combine a new menu with an existing one'''
self.items.extend(submenu.items)
def wx_menu(self):
'''return a wx.Menu() for this menu'''
from MAVProxy.modules.lib.wx_loader import wx
menu = wx.Menu()
for i in range(len(self.items)):
m = self.items[i]
m._append(menu)
return menu
def find_selected(self, event):
'''find the selected menu item'''
for m in self.items:
ret = m.find_selected(event)
if ret is not None:
return ret
return None
def _append(self, menu):
'''append this menu item to a menu'''
menu.AppendSubMenu(self.wx_menu(), self.name) #use wxPython_phoenix
def __str__(self):
return "MPMenuSubMenu(%s)" % (self.name)
|
class MPMenuSubMenu(MPMenuGeneric):
'''a MP menu item'''
def __init__(self, name, items):
pass
def add(self, items, addto=None):
'''add more items to a sub-menu'''
pass
def remove(self, items):
'''remove items from a sub-menu'''
pass
def add_to_submenu(self, submenu_path, item):
'''add an item to a submenu using a menu path array'''
pass
def combine(self, submenu):
'''combine a new menu with an existing one'''
pass
def wx_menu(self):
'''return a wx.Menu() for this menu'''
pass
def find_selected(self, event):
'''find the selected menu item'''
pass
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
pass
| 10 | 8 | 7 | 0 | 6 | 1 | 2 | 0.17 | 1 | 5 | 0 | 0 | 9 | 2 | 9 | 14 | 69 | 8 | 53 | 23 | 42 | 9 | 53 | 23 | 42 | 7 | 2 | 4 | 22 |
7,131 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuSeparator
|
class MPMenuSeparator(MPMenuGeneric):
'''a MP menu separator'''
def __init__(self):
MPMenuGeneric.__init__(self)
def _append(self, menu):
'''append this menu item to a menu'''
menu.AppendSeparator()
def __str__(self):
return "MPMenuSeparator()"
|
class MPMenuSeparator(MPMenuGeneric):
'''a MP menu separator'''
def __init__(self):
pass
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
pass
| 4 | 2 | 2 | 0 | 2 | 0 | 1 | 0.29 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 8 | 11 | 2 | 7 | 4 | 3 | 2 | 7 | 4 | 3 | 1 | 2 | 0 | 3 |
7,132 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuRadio
|
class MPMenuRadio(MPMenuItem):
'''a MP menu item as a radio item'''
def __init__(self, name, description='', returnkey=None, selected=None, items=[], handler=None):
MPMenuItem.__init__(self, name, description=description, returnkey=returnkey, handler=handler)
self.items = items
self.choice = 0
self.initial = selected
def __getstate__(self):
attr = self.__dict__.copy()
if hasattr(attr,'_ids'):
del attr['_ids']
return attr
def set_choices(self, items):
'''set radio item choices'''
self.items = items
def get_choice(self):
'''return the chosen item'''
return self.items[self.choice]
def find_selected(self, event):
'''find the selected menu item'''
if not hasattr(self, '_ids'):
return None
evid = event.GetId()
if evid in self._ids:
self.choice = self._ids.index(evid)
return self
return None
def _append(self, menu):
'''append this menu item to a menu'''
from MAVProxy.modules.lib.wx_loader import wx
submenu = wx.Menu()
if not hasattr(self, '_ids') or len(self._ids) != len(self.items):
self._ids = []
for i in range(len(self.items)):
self._ids.append(wx.NewId())
for i in range(len(self.items)):
submenu.AppendRadioItem(self._ids[i], self.items[i], self.description)
if self.items[i] == self.initial:
submenu.Check(self._ids[i], True)
menu.AppendSubMenu(submenu, self.name)
def __str__(self):
return "MPMenuRadio(%s,%s,%s,%s)" % (self.name, self.description, self.returnkey, self.get_choice())
|
class MPMenuRadio(MPMenuItem):
'''a MP menu item as a radio item'''
def __init__(self, name, description='', returnkey=None, selected=None, items=[], handler=None):
pass
def __getstate__(self):
pass
def set_choices(self, items):
'''set radio item choices'''
pass
def get_choice(self):
'''return the chosen item'''
pass
def find_selected(self, event):
'''find the selected menu item'''
pass
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
pass
| 8 | 5 | 6 | 0 | 5 | 1 | 2 | 0.14 | 1 | 1 | 0 | 0 | 7 | 4 | 7 | 19 | 48 | 6 | 37 | 17 | 28 | 5 | 37 | 17 | 28 | 5 | 3 | 2 | 14 |
7,133 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuOpenWeblink
|
class MPMenuOpenWeblink(object):
'''used to open a weblink in the default webbrowser'''
def __init__(self, url='www.google.com'):
self.url = url
def call(self):
'''show the dialog as a child process'''
import webbrowser
webbrowser.open_new_tab(self.url)
|
class MPMenuOpenWeblink(object):
'''used to open a weblink in the default webbrowser'''
def __init__(self, url='www.google.com'):
pass
def call(self):
'''show the dialog as a child process'''
pass
| 3 | 2 | 3 | 0 | 3 | 1 | 1 | 0.33 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 9 | 1 | 6 | 5 | 2 | 2 | 6 | 5 | 2 | 1 | 1 | 0 | 2 |
7,134 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuItem
|
class MPMenuItem(MPMenuGeneric):
'''a MP menu item'''
def __init__(self, name, description='', returnkey=None, handler=None):
MPMenuGeneric.__init__(self)
self.name = name
self.description = description
self.returnkey = returnkey
self.handler = handler
self.handler_result = None
def __getstate__(self):
'''use __getstate__ to override pickle so that we don't propogate IDs across process boundaries'''
attr = self.__dict__.copy()
if hasattr(attr,'_id'):
del attr['_id']
return attr
def find_selected(self, event):
'''find the selected menu item'''
if event.GetId() == self.id():
return self
return None
def call_handler(self):
'''optionally call a handler function'''
if self.handler is None:
return
call = getattr(self.handler, 'call', None)
if call is not None:
self.handler_result = call()
def id(self):
'''id used to identify the returned menu items uses a 16 bit signed integer. We allocate these
on use, and use __getstate__ to avoid them crossing processs boundaries'''
if getattr(self, '_id', None) is None:
global idmap
import os
key_tuple = (os.getpid(), self.name, self.returnkey)
if key_tuple in idmap:
self._id = idmap[key_tuple]
else:
from MAVProxy.modules.lib.wx_loader import wx
self._id = wx.NewId()
idmap[key_tuple] = self._id
return self._id
def _append(self, menu):
'''append this menu item to a menu'''
if not self.name:
return
menu.Append(self.id(), self.name, self.description)
def __str__(self):
return "MPMenuItem(%s,%s,%s)" % (self.name, self.description, self.returnkey)
|
class MPMenuItem(MPMenuGeneric):
'''a MP menu item'''
def __init__(self, name, description='', returnkey=None, handler=None):
pass
def __getstate__(self):
'''use __getstate__ to override pickle so that we don't propogate IDs across process boundaries'''
pass
def find_selected(self, event):
'''find the selected menu item'''
pass
def call_handler(self):
'''optionally call a handler function'''
pass
def id(self):
'''id used to identify the returned menu items uses a 16 bit signed integer. We allocate these
on use, and use __getstate__ to avoid them crossing processs boundaries'''
pass
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
pass
| 8 | 6 | 7 | 0 | 6 | 1 | 2 | 0.17 | 1 | 0 | 0 | 2 | 7 | 6 | 7 | 12 | 54 | 6 | 41 | 20 | 30 | 7 | 40 | 20 | 29 | 3 | 2 | 2 | 14 |
7,135 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuGeneric
|
class MPMenuGeneric(object):
'''a MP menu separator'''
def __init__(self):
pass
def find_selected(self, event):
return None
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
return "MPMenuGeneric()"
def __repr__(self):
return str(self.__str__())
|
class MPMenuGeneric(object):
'''a MP menu separator'''
def __init__(self):
pass
def find_selected(self, event):
pass
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
pass
def __repr__(self):
pass
| 6 | 2 | 2 | 0 | 2 | 0 | 1 | 0.18 | 1 | 1 | 0 | 3 | 5 | 0 | 5 | 5 | 17 | 4 | 11 | 6 | 5 | 2 | 11 | 6 | 5 | 1 | 1 | 0 | 5 |
7,136 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuConfirmDialog
|
class MPMenuConfirmDialog(object):
'''used to create a confirmation dialog'''
def __init__(self, title='Confirmation', message='', callback=None, args=None):
self.title = title
self.message = message
self.callback = callback
self.args = args
t = multiproc.Process(target=self.thread)
t.start()
def thread(self):
mp_util.child_close_fds()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
app = wx.App(False)
dlg = wx.MessageDialog(None, self.title, self.message, wx.YES|wx.NO)
ret = dlg.ShowModal()
if ret == wx.ID_YES and self.callback is not None:
self.callback(self.args)
|
class MPMenuConfirmDialog(object):
'''used to create a confirmation dialog'''
def __init__(self, title='Confirmation', message='', callback=None, args=None):
pass
def thread(self):
pass
| 3 | 1 | 8 | 0 | 8 | 0 | 2 | 0.06 | 1 | 0 | 0 | 0 | 2 | 4 | 2 | 2 | 19 | 1 | 17 | 13 | 12 | 1 | 17 | 13 | 12 | 2 | 1 | 1 | 3 |
7,137 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuChildMessageDialog
|
class MPMenuChildMessageDialog(object):
'''used to create a message dialog in a child process'''
def __init__(self, title='Information', message='', font_size=18):
self.title = title
self.message = message
self.font_size = font_size
def show(self):
t = multiproc.Process(target=self.call)
t.start()
def call(self):
'''show the dialog as a child process'''
mp_util.child_close_fds()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from wx.lib.agw.genericmessagedialog import GenericMessageDialog
app = wx.App(False)
# note! font size change is not working. I don't know why yet
font = wx.Font(self.font_size, wx.MODERN, wx.NORMAL, wx.NORMAL)
dlg = GenericMessageDialog(None, self.message, self.title, wx.ICON_INFORMATION|wx.OK)
dlg.SetFont(font)
dlg.ShowModal()
app.MainLoop()
|
class MPMenuChildMessageDialog(object):
'''used to create a message dialog in a child process'''
def __init__(self, title='Information', message='', font_size=18):
pass
def show(self):
pass
def call(self):
'''show the dialog as a child process'''
pass
| 4 | 2 | 7 | 0 | 6 | 1 | 1 | 0.16 | 1 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 24 | 2 | 19 | 14 | 12 | 3 | 19 | 14 | 12 | 1 | 1 | 0 | 3 |
7,138 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuCheckbox
|
class MPMenuCheckbox(MPMenuItem):
'''a MP menu item as a checkbox'''
def __init__(self, name, description='', returnkey=None, checked=False, handler=None):
MPMenuItem.__init__(self, name, description=description, returnkey=returnkey, handler=handler)
self.checked = checked
def find_selected(self, event):
'''find the selected menu item'''
if event.GetId() == self.id():
self.checked = event.IsChecked()
return self
return None
def IsChecked(self):
'''return true if item is checked'''
return self.checked
def _append(self, menu):
'''append this menu item to a menu'''
try:
menu.AppendCheckItem(self.id(), self.name, self.description)
menu.Check(self.id(), self.checked)
except Exception:
pass
def __str__(self):
return "MPMenuCheckbox(%s,%s,%s,%s)" % (self.name, self.description, self.returnkey, str(self.checked))
|
class MPMenuCheckbox(MPMenuItem):
'''a MP menu item as a checkbox'''
def __init__(self, name, description='', returnkey=None, checked=False, handler=None):
pass
def find_selected(self, event):
'''find the selected menu item'''
pass
def IsChecked(self):
'''return true if item is checked'''
pass
def _append(self, menu):
'''append this menu item to a menu'''
pass
def __str__(self):
pass
| 6 | 4 | 4 | 0 | 4 | 1 | 1 | 0.21 | 1 | 2 | 0 | 0 | 5 | 1 | 5 | 17 | 27 | 4 | 19 | 7 | 13 | 4 | 19 | 7 | 13 | 2 | 3 | 1 | 7 |
7,139 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuCallTextDialog
|
class MPMenuCallTextDialog(object):
'''used to create a value dialog callback'''
def __init__(self, title='Enter Value', default='', settings=None):
self.title = title
self.default = default
self.settings = settings
def call(self):
'''show a value dialog'''
from MAVProxy.modules.lib.wx_loader import wx
title = self.title
if title.find('FLYTOFRAMEUNITS') != -1 and self.settings is not None:
frameunits = "%s %s" % (self.settings.flytoframe, self.settings.height_unit)
title = title.replace('FLYTOFRAMEUNITS', frameunits)
try:
dlg = wx.TextEntryDialog(None, title, title, defaultValue=str(self.default))
except TypeError:
dlg = wx.TextEntryDialog(None, title, title, value=str(self.default))
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetValue()
|
class MPMenuCallTextDialog(object):
'''used to create a value dialog callback'''
def __init__(self, title='Enter Value', default='', settings=None):
pass
def call(self):
'''show a value dialog'''
pass
| 3 | 2 | 9 | 0 | 9 | 1 | 3 | 0.11 | 1 | 2 | 0 | 0 | 2 | 3 | 2 | 2 | 21 | 1 | 18 | 10 | 14 | 2 | 18 | 10 | 14 | 4 | 1 | 1 | 5 |
7,140 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuCallFileDialog
|
class MPMenuCallFileDialog(object):
'''used to create a file dialog callback'''
def __init__(self, flags=None, title='Filename', wildcard='*.*'):
self.flags = flags or ('open',)
self.title = title
self.wildcard = wildcard
def call(self):
'''show a file dialog'''
from MAVProxy.modules.lib.wx_loader import wx
# remap flags to wx descriptors
flag_map = {
'open': wx.FD_OPEN,
'save': wx.FD_SAVE,
'overwrite_prompt': wx.FD_OVERWRITE_PROMPT,
}
flagsMapped = list(map(lambda x: flag_map[x], self.flags))
#need to OR together the elements of the flagsMapped tuple
if len(flagsMapped) == 1:
dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flagsMapped[0])
else:
dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flagsMapped[0]|flagsMapped[1])
if dlg.ShowModal() != wx.ID_OK:
return None
return "\"" + dlg.GetPath() + "\""
|
class MPMenuCallFileDialog(object):
'''used to create a file dialog callback'''
def __init__(self, flags=None, title='Filename', wildcard='*.*'):
pass
def call(self):
'''show a file dialog'''
pass
| 3 | 2 | 12 | 1 | 10 | 2 | 2 | 0.2 | 1 | 2 | 0 | 0 | 2 | 3 | 2 | 2 | 27 | 3 | 20 | 10 | 16 | 4 | 15 | 10 | 11 | 3 | 1 | 1 | 4 |
7,141 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_menu.py
|
MAVProxy.modules.lib.mp_menu.MPMenuCallDirDialog
|
class MPMenuCallDirDialog(object):
'''used to create a file folder dialog callback'''
def __init__(self, flags=None, title='Directory'):
self.title = title
def call(self):
'''show a directory chooser dialog'''
from MAVProxy.modules.lib.wx_loader import wx
dlg = wx.DirDialog(None, self.title, '')
if dlg.ShowModal() != wx.ID_OK:
return None
return "\"" + dlg.GetPath() + "\""
|
class MPMenuCallDirDialog(object):
'''used to create a file folder dialog callback'''
def __init__(self, flags=None, title='Directory'):
pass
def call(self):
'''show a directory chooser dialog'''
pass
| 3 | 2 | 5 | 1 | 4 | 1 | 2 | 0.22 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 13 | 2 | 9 | 6 | 5 | 2 | 9 | 6 | 5 | 2 | 1 | 1 | 3 |
7,142 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_instructor.py
|
MAVProxy.modules.lib.mp_instructor.InstructorUI
|
class InstructorUI:
"""
Instructor UI for MAVProxy
"""
def __init__(self, title='Instructor Station'):
self.title = title
self.menu_callback = None
self.pipe_to_gui, self.gui_pipe = multiproc.Pipe()
self.close_event = multiproc.Event()
self.close_event.clear()
self.child = multiproc.Process(target=self.child_task)
self.child.start()
def child_task(self):
"""child process - this holds all the GUI elements"""
mp_util.child_close_fds()
from MAVProxy.modules.lib.wx_loader import wx
app = wx.App(False)
app.frame = InstructorFrame(self.gui_pipe, state=self, title=self.title)
app.frame.Show()
app.MainLoop()
def close(self):
"""close the UI"""
self.close_event.set()
if self.is_alive():
self.child.join(2)
print("closed")
def is_alive(self):
"""check if child is still going"""
return self.child.is_alive()
def set_check(self, name, state):
"""set a status value"""
if self.child.is_alive():
self.pipe_to_gui.send(CheckboxItemState(name, state))
|
class InstructorUI:
'''
Instructor UI for MAVProxy
'''
def __init__(self, title='Instructor Station'):
pass
def child_task(self):
'''child process - this holds all the GUI elements'''
pass
def close(self):
'''close the UI'''
pass
def is_alive(self):
'''check if child is still going'''
pass
def set_check(self, name, state):
'''set a status value'''
pass
| 6 | 5 | 6 | 0 | 5 | 1 | 1 | 0.27 | 0 | 2 | 2 | 0 | 5 | 6 | 5 | 5 | 38 | 5 | 26 | 13 | 19 | 7 | 26 | 13 | 19 | 2 | 0 | 1 | 7 |
7,143 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_module.py
|
MAVProxy.modules.lib.mp_module.MPModule
|
class MPModule(object):
'''
The base class for all modules
'''
def __init__(self, mpstate, name, description=None, public=False, multi_instance=False, multi_vehicle=False):
'''
Constructor
if public is true other modules can find this module instance with module('name')
'''
self.mpstate = mpstate
self.name = name
self.needs_unloading = False
self.multi_instance = multi_instance
self.multi_vehicle = multi_vehicle
self.named_float_seq = 0
if description is None:
self.description = name + " handling"
else:
self.description = description
if multi_instance:
if not name in mpstate.multi_instance:
mpstate.multi_instance[name] = []
mpstate.instance_count[name] = 0
mpstate.multi_instance[name].append(self)
mpstate.instance_count[name] += 1
self.instance = mpstate.instance_count[name]
if self.instance > 1:
# make the name distincitive, so self.module('map2') works
self.name += str(self.instance)
if public:
mpstate.public_modules[self.name] = self
#
# Overridable hooks follow...
#
def idle_task(self):
pass
def unload(self):
if self.multi_instance and self.name in self.mpstate.multi_instance:
self.mpstate.multi_instance.pop(self.name)
def unknown_command(self, args):
'''Return True if we have handled the unknown command'''
return False
def mavlink_packet(self, packet):
pass
#
# Methods for subclass use
#
def module(self, name):
'''Find a public module (most modules are private)'''
return self.mpstate.module(name)
def module_matching(self, name):
'''Find a list of modules matching a wildcard pattern'''
import fnmatch
ret = []
for mname in self.mpstate.public_modules.keys():
if fnmatch.fnmatch(mname, name):
ret.append(self.mpstate.public_modules[mname])
return ret
def get_time(self):
'''get time, using ATTITUDE.time_boot_ms if in SITL with SIM_SPEEDUP != 1'''
systime = time.time() - self.mpstate.start_time_s
if not self.mpstate.is_sitl:
return systime
try:
speedup = int(self.get_mav_param('SIM_SPEEDUP',1))
except Exception:
return systime
if speedup != 1:
return self.mpstate.attitude_time_s
return systime
@property
def console(self):
return self.mpstate.console
@property
def status(self):
return self.mpstate.status
@property
def mav_param(self):
return self.mpstate.mav_param
@property
def settings(self):
return self.mpstate.settings
@property
def vehicle_type(self):
return self.mpstate.vehicle_type
@property
def vehicle_name(self):
return self.mpstate.vehicle_name
@property
def sitl_output(self):
return self.mpstate.sitl_output
@property
def target_system(self):
return self.settings.target_system
@property
def target_component(self):
return self.settings.target_component
@property
def master(self):
return self.mpstate.master()
@property
def continue_mode(self):
return self.mpstate.continue_mode
@property
def logdir(self):
return self.mpstate.status.logdir
def say(self, msg, priority='important'):
return self.mpstate.functions.say(msg)
def get_mav_param(self, param_name, default=None):
return self.mpstate.functions.get_mav_param(param_name, default)
def param_set(self, name, value, retries=3):
self.mpstate.functions.param_set(name, value, retries)
def add_command(self, name, callback, description, completions=None):
self.mpstate.command_map[name] = (callback, description)
if completions is not None:
self.mpstate.completions[name] = completions
def remove_command(self, name):
if name in self.mpstate.command_map:
del self.mpstate.command_map[name]
if name in self.mpstate.completions:
del self.mpstate.completions[name]
def add_completion_function(self, name, callback):
self.mpstate.completion_functions[name] = callback
def flyto_frame_units(self):
'''return a frame string and unit'''
return "%s %s" % (self.settings.height_unit, self.settings.flytoframe)
def flyto_frame(self):
'''return mavlink frame flyto frame setting'''
if self.settings.flytoframe == "AGL":
return mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT
if self.settings.flytoframe == "AMSL":
return mavutil.mavlink.MAV_FRAME_GLOBAL
return mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT
def dist_string(self, val_meters):
'''return a distance as a string'''
if self.settings.dist_unit == 'nm':
return "%.1fnm" % (val_meters * 0.000539957)
if self.settings.dist_unit == 'miles':
return "%.1fmiles" % (val_meters * 0.000621371)
return "%um" % val_meters
def height_convert_units(self, val_meters):
'''return a height in configured units'''
if self.settings.height_unit == 'feet':
return val_meters * 3.28084
return val_meters
def height_convert_from_units(self, val):
'''convert a height from configured units'''
if self.settings.height_unit == 'feet':
return val / 3.28084
return val
def height_string(self, val_meters):
'''return a height as a string'''
if self.settings.height_unit == 'feet':
return "%uft" % (val_meters * 3.28084)
return "%um" % val_meters
def speed_convert_units(self, val_ms):
'''return a speed in configured units'''
if self.settings.speed_unit == 'knots':
return val_ms * 1.94384
elif self.settings.speed_unit == 'mph':
return val_ms * 2.23694
return val_ms
def speed_string(self, val_ms):
'''return a speed as a string'''
if self.settings.speed_unit == 'knots':
return "%ukn" % (val_ms * 1.94384)
elif self.settings.speed_unit == 'mph':
return "%umph" % (val_ms * 2.23694)
return "%um/s" % val_ms
def set_prompt(self, prompt):
'''set prompt for command line'''
if prompt and self.settings.vehicle_name:
# add in optional vehicle name
prompt = self.settings.vehicle_name + ':' + prompt
self.mpstate.rl.set_prompt(prompt)
@staticmethod
def link_label(link):
'''return a link label as a string'''
if hasattr(link, 'label'):
label = link.label
else:
label = str(link.linknum+1)
return label
def message_is_from_primary_vehicle(self, msg):
'''see if a msg is from our primary vehicle'''
sysid = msg.get_srcSystem()
compid = msg.get_srcComponent()
if ((self.target_system == 0 or self.target_system == sysid) and
(self.target_component == 0 or self.target_component == compid)):
return True
return False
def send_named_float(self, name, value):
'''inject a NAMED_VALUE_FLOAT into the local master input, so it becomes available
for graphs, logging and status command'''
# use the ATTITUDE message for time stamp
att = self.master.messages.get('ATTITUDE',None)
if att is None:
return
msec = att.time_boot_ms
ename = name.encode('ASCII')
if len(ename) < 10:
ename += bytes([0] * (10-len(ename)))
m = self.master.mav.named_value_float_encode(msec, bytearray(ename), value)
m.pack(self.master.mav)
m._header.srcSystem = att._header.srcSystem
m._header.srcComponent = mavutil.mavlink.MAV_COMP_ID_TELEMETRY_RADIO
m._header.seq = self.named_float_seq
self.named_float_seq = (self.named_float_seq+1) % 256
m.name = name
self.mpstate.module('link').master_callback(m, self.master)
|
class MPModule(object):
'''
The base class for all modules
'''
def __init__(self, mpstate, name, description=None, public=False, multi_instance=False, multi_vehicle=False):
'''
Constructor
if public is true other modules can find this module instance with module('name')
'''
pass
def idle_task(self):
pass
def unload(self):
pass
def unknown_command(self, args):
'''Return True if we have handled the unknown command'''
pass
def mavlink_packet(self, packet):
pass
def module(self, name):
'''Find a public module (most modules are private)'''
pass
def module_matching(self, name):
'''Find a list of modules matching a wildcard pattern'''
pass
def get_time(self):
'''get time, using ATTITUDE.time_boot_ms if in SITL with SIM_SPEEDUP != 1'''
pass
@property
def console(self):
pass
@property
def status(self):
pass
@property
def mav_param(self):
pass
@property
def settings(self):
pass
@property
def vehicle_type(self):
pass
@property
def vehicle_name(self):
pass
@property
def sitl_output(self):
pass
@property
def target_system(self):
pass
@property
def target_component(self):
pass
@property
def master(self):
pass
@property
def continue_mode(self):
pass
@property
def logdir(self):
pass
def say(self, msg, priority='important'):
pass
def get_mav_param(self, param_name, default=None):
pass
def param_set(self, name, value, retries=3):
pass
def add_command(self, name, callback, description, completions=None):
pass
def remove_command(self, name):
pass
def add_completion_function(self, name, callback):
pass
def flyto_frame_units(self):
'''return a frame string and unit'''
pass
def flyto_frame_units(self):
'''return mavlink frame flyto frame setting'''
pass
def dist_string(self, val_meters):
'''return a distance as a string'''
pass
def height_convert_units(self, val_meters):
'''return a height in configured units'''
pass
def height_convert_from_units(self, val):
'''convert a height from configured units'''
pass
def height_string(self, val_meters):
'''return a height as a string'''
pass
def speed_convert_units(self, val_ms):
'''return a speed in configured units'''
pass
def speed_string(self, val_ms):
'''return a speed as a string'''
pass
def set_prompt(self, prompt):
'''set prompt for command line'''
pass
@staticmethod
def link_label(link):
'''return a link label as a string'''
pass
def message_is_from_primary_vehicle(self, msg):
'''see if a msg is from our primary vehicle'''
pass
def send_named_float(self, name, value):
'''inject a NAMED_VALUE_FLOAT into the local master input, so it becomes available
for graphs, logging and status command'''
pass
| 52 | 18 | 5 | 0 | 4 | 1 | 2 | 0.19 | 1 | 5 | 0 | 97 | 37 | 8 | 38 | 38 | 253 | 43 | 177 | 72 | 124 | 33 | 159 | 59 | 119 | 6 | 1 | 2 | 68 |
7,144 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_instructor.py
|
MAVProxy.modules.lib.mp_instructor.CheckboxItemState
|
class CheckboxItemState:
def __init__(self, name, state):
self.name = name
self.state = state
|
class CheckboxItemState:
def __init__(self, name, state):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 4 | 0 | 4 | 4 | 2 | 0 | 4 | 4 | 2 | 1 | 0 | 0 | 1 |
7,145 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Camera
|
class Camera(object):
def __init__(self):
# Base must be orthonormal
self.base = (
Vector3(1.0, 0.0, 0.0),
Vector3(0.0, 1.0, 0.0),
Vector3(0.0, 0.0, 1.0)
)
self.position = Vector3(0.0, 0.0, 0.0)
self.position_transform = Transform()
self.base_transform = Transform()
def view_mat4(self):
p = self.position_transform.apply(self.position)
i = self.base_transform.apply(self.base[0])
j = self.base_transform.apply(self.base[1])
k = self.base_transform.apply(self.base[2])
tx, ty, tz = p * i, p * j, p * k
return (c_float * 16)(
i.x, j.x, k.x, 0,
i.y, j.y, k.y, 0,
i.z, j.z, k.z, 0,
-tx, -ty, -tz, 1
)
|
class Camera(object):
def __init__(self):
pass
def view_mat4(self):
pass
| 3 | 0 | 12 | 1 | 11 | 1 | 1 | 0.05 | 1 | 1 | 1 | 0 | 2 | 4 | 2 | 2 | 25 | 2 | 22 | 12 | 19 | 1 | 13 | 12 | 10 | 1 | 1 | 0 | 2 |
7,146 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Material
|
class Material(object):
def __init__(self,
ambient=Vector3(.5, .5, .5),
diffuse=Vector3(.5, .5, .5),
specular=Vector3(.5, .5, .5),
specular_exponent=32.0,
alpha=1.0):
self.ambient = ambient
self.diffuse = diffuse
self.specular = specular
self.specular_exponent = specular_exponent
self.alpha = alpha
def set_color(self, color):
self.ambient = color
self.diffuse = color
self.specular = color
|
class Material(object):
def __init__(self,
ambient=Vector3(.5, .5, .5),
diffuse=Vector3(.5, .5, .5),
specular=Vector3(.5, .5, .5),
specular_exponent=32.0,
alpha=1.0):
pass
def set_color(self, color):
pass
| 3 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 5 | 2 | 2 | 17 | 1 | 16 | 13 | 8 | 0 | 11 | 8 | 8 | 1 | 1 | 0 | 2 |
7,147 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_adsb.py
|
MAVProxy.modules.mavproxy_adsb.ADSBVehicle
|
class ADSBVehicle(object):
'''a generic ADS-B threat'''
def __init__(self, id, state):
self.id = id
self.state = state
self.vehicle_colour = 'green' # use plane icon for now
self.vehicle_type = 'plane'
self.icon = self.vehicle_colour + self.vehicle_type + '.png'
self.update_time = 0
self.is_evading_threat = False
self.v_distance = None
self.h_distance = None
self.distance = None
def update(self, state, tnow):
'''update the threat state'''
self.state = state
self.update_time = tnow
|
class ADSBVehicle(object):
'''a generic ADS-B threat'''
def __init__(self, id, state):
pass
def update(self, state, tnow):
'''update the threat state'''
pass
| 3 | 2 | 8 | 0 | 7 | 1 | 1 | 0.2 | 1 | 0 | 0 | 0 | 2 | 10 | 2 | 2 | 19 | 2 | 15 | 13 | 12 | 3 | 15 | 13 | 12 | 1 | 1 | 0 | 2 |
7,148 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_ais.py
|
MAVProxy.modules.mavproxy_ais.AISModule
|
class AISModule(mp_module.MPModule):
def __init__(self, mpstate):
super(AISModule, self).__init__(mpstate, "ais", "AIS data support", public=True)
self.threat_vehicles = {}
self.add_command('ais', self.cmd_AIS, "ais control",
["<status>", "set (AISSETTING)"])
self.AIS_settings = mp_settings.MPSettings([("timeout", int, 60), # seconds
("threat_radius", int, 200)]) # meters
self.add_completion_function('(AISSETTING)',
self.AIS_settings.completion)
self.threat_timeout_timer = mavutil.periodic_event(2)
self.update_map_timer = mavutil.periodic_event(1)
self.tnow = self.get_time()
def cmd_AIS(self, args):
'''ais command parser'''
usage = "usage: ais <set>"
if len(args) == 0:
print(usage)
elif args[0] == "set":
self.AIS_settings.command(args[1:])
else:
print(usage)
def check_threat_timeout(self):
'''check and handle threat time out'''
for id in self.threat_vehicles:
if self.threat_vehicles[id].update_time == 0:
self.threat_vehicles[id].update_time = self.get_time()
dt = self.get_time() - self.threat_vehicles[id].update_time
if dt > self.AIS_settings.timeout:
# if the threat has timed out...
del self.threat_vehicles[id] # remove the threat from the dict
for mp in self.module_matching('map*'):
# remove the threat from the map
mp.map.remove_object(id)
mp.map.remove_object(id+":circle")
# we've modified the dict we're iterating over, so
# we'll get any more timed-out threats next time we're
# called:
return
def update_map(self):
'''update the map graphics'''
for mp in self.module_matching('map*'):
for id in self.threat_vehicles.keys():
mstate = self.threat_vehicles[id].state
threat_radius = self.threat_vehicles[id].getThreatRadius(self.AIS_settings.threat_radius)
# update if existing object on map, else create
if self.threat_vehicles[id].onMap:
mp.map.set_position(id, (mstate.lat * 1e-7, mstate.lon * 1e-7), 3, rotation=mstate.heading*0.01, label=str(mstate.callsign))
# Turns out we can't edit the circle's radius, so have to remove and re-add
mp.map.remove_object(id+":circle")
mp.map.add_object(mp_slipmap.SlipCircle(id+":circle", 3,
(mstate.lat * 1e-7, mstate.lon * 1e-7),
threat_radius, (0, 255, 255), linewidth=1))
else:
self.threat_vehicles[id].menu_item = mp_menu.MPMenuItem(name=id, returnkey=None)
# draw the vehicle on the map
popup = mp_menu.MPMenuSubMenu('AIS', items=[self.threat_vehicles[id].menu_item])
icon = mp_slipmap.SlipIcon(
id,
(mstate.lat * 1e-7, mstate.lon * 1e-7),
mp.map.icon(self.threat_vehicles[id].icon),
3,
rotation=mstate.heading*0.01,
follow=False,
trail=mp_slipmap.SlipTrail(colour=(0, 255, 255)),
popup_menu=popup,
)
mp.map.add_object(icon)
mp.map.add_object(mp_slipmap.SlipCircle(id+":circle", 3,
(mstate.lat * 1e-7, mstate.lon * 1e-7),
threat_radius, (0, 255, 255), linewidth=1))
self.threat_vehicles[id].onMap = True
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == "AIS_VESSEL":
id = 'AIS-' + str(m.MMSI)
if id not in self.threat_vehicles.keys(): # check to see if the vehicle is in the dict
# if not then add it
self.threat_vehicles[id] = AISVehicle(id=id, state=m)
else: # the vehicle is in the dict
# update the dict entry
self.threat_vehicles[id].update(m, self.get_time())
def idle_task(self):
'''called on idle'''
if self.threat_timeout_timer.trigger():
self.check_threat_timeout()
if self.update_map_timer.trigger():
self.update_map()
|
class AISModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_AIS(self, args):
'''ais command parser'''
pass
def check_threat_timeout(self):
'''check and handle threat time out'''
pass
def update_map(self):
'''update the map graphics'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def idle_task(self):
'''called on idle'''
pass
| 7 | 5 | 16 | 1 | 12 | 3 | 3 | 0.27 | 1 | 10 | 7 | 0 | 6 | 5 | 6 | 44 | 101 | 13 | 73 | 22 | 66 | 20 | 53 | 22 | 46 | 5 | 2 | 3 | 19 |
7,149 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_ais.py
|
MAVProxy.modules.mavproxy_ais.AISVehicle
|
class AISVehicle():
'''a generic AIS threat'''
def __init__(self, id, state):
self.id = id
self.state = state
self.vehicle_colour = 'green' # use boat icon for now
self.vehicle_type = 'boat'
self.icon = self.vehicle_colour + self.vehicle_type + '.png'
self.update_time = 0
self.onMap = False
def update(self, state, tnow):
self.state = state
self.update_time = tnow
def getThreatRadius(self, default_radius):
''' get threat radius, based on ship type'''
# threat radius is the maximum of distance to AIS location
if self.state.flags & mavutil.mavlink.AIS_FLAGS_LARGE_BOW_DIMENSION or self.state.flags & mavutil.mavlink.AIS_FLAGS_LARGE_STERN_DIMENSION:
threat_radius = 511
elif self.state.flags & mavutil.mavlink.AIS_FLAGS_LARGE_PORT_DIMENSION or self.state.flags & mavutil.mavlink.AIS_FLAGS_LARGE_STARBOARD_DIMENSION:
threat_radius = 63
else:
threat_radius = max(self.state.dimension_bow, self.state.dimension_stern, self.state.dimension_port, self.state.dimension_starboard)
#default to threat_radius setting
if threat_radius == 0:
return default_radius
|
class AISVehicle():
'''a generic AIS threat'''
def __init__(self, id, state):
pass
def update(self, state, tnow):
pass
def getThreatRadius(self, default_radius):
''' get threat radius, based on ship type'''
pass
| 4 | 2 | 8 | 0 | 7 | 1 | 2 | 0.24 | 0 | 0 | 0 | 0 | 3 | 7 | 3 | 3 | 28 | 3 | 21 | 12 | 17 | 5 | 19 | 12 | 15 | 4 | 0 | 1 | 6 |
7,150 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_antenna.py
|
MAVProxy.modules.mavproxy_antenna.AntennaModule
|
class AntennaModule(mp_module.MPModule):
def __init__(self, mpstate):
super(AntennaModule, self).__init__(mpstate, "antenna", "antenna pointing module")
self.gcs_location = None
self.last_bearing = 0
self.last_announce = 0
self.add_command('antenna', self.cmd_antenna, "antenna link control")
def cmd_antenna(self, args):
'''set gcs location'''
if len(args) != 2:
if self.gcs_location is None:
print("GCS location not set")
else:
print("GCS location %s" % str(self.gcs_location))
return
self.gcs_location = (float(args[0]), float(args[1]))
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if self.gcs_location is None and self.module('wp').wploader.count() > 0:
home = self.module('wp').get_home()
self.gcs_location = (home.x, home.y)
print("Antenna home set")
if self.gcs_location is None:
return
if m.get_type() == 'GPS_RAW' and self.gcs_location is not None:
(gcs_lat, gcs_lon) = self.gcs_location
bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
elif m.get_type() == 'GPS_RAW_INT' and self.gcs_location is not None:
(gcs_lat, gcs_lon) = self.gcs_location
bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat / 1.0e7, m.lon / 1.0e7)
else:
return
self.console.set_status('Antenna', 'Antenna %.0f' % bearing, row=0)
if abs(bearing - self.last_bearing) > 5 and (time.time() - self.last_announce) > 15:
self.last_bearing = bearing
self.last_announce = time.time()
self.say("Antenna %u" % int(bearing + 0.5))
|
class AntennaModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_antenna(self, args):
'''set gcs location'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
| 4 | 2 | 12 | 0 | 11 | 1 | 3 | 0.06 | 1 | 4 | 0 | 0 | 3 | 3 | 3 | 41 | 41 | 4 | 35 | 10 | 31 | 2 | 32 | 10 | 28 | 6 | 2 | 2 | 10 |
7,151 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_anufireproject/__init__.py
|
MAVProxy.modules.mavproxy_anufireproject.ANUFireProject
|
class ANUFireProject(mp_module.MPModule):
def __init__(self, mpstate):
super(ANUFireProject, self).__init__(mpstate, "anufireproject", "")
self.kml_module_initialised = False
# stores the directory into which our persistent state should
# be dropped:
self.dot_mavproxy_path = mp_util.dot_mavproxy("anufp")
pathlib.Path(self.dot_mavproxy_path).mkdir(parents=True, exist_ok=True)
self.add_command(
'anufp',
self.cmd,
"ANU FireProject utility functions",
["<burnkml>", "<burnkml> (BURNID)"],
)
self.burn_data_url = 'https://services1.arcgis.com/E5n4f1VY84i0xSjy/arcgis/rest/services/Prescribed_Burns_Public/FeatureServer/0/query?f=json&where=1%3D1&spatialRel=esriSpatialRelIntersects&geometry=%7B%22xmin%22%3A16505903.50821903%2C%22ymin%22%3A-4198481.646243979%2C%22xmax%22%3A16627897.005362216%2C%22ymax%22%3A-4144822.852387765%2C%22spatialReference%22%3A%7B%22wkid%22%3A102100%7D%7D&geometryType=esriGeometryEnvelope&inSR=102100&outFields=BURN_NAME%2CBOP_ID%2CHECTARES%2CWORKS_DESCRIPTION%2CBURN_TIMEFRAME%2CESRI_OID&orderByFields=ESRI_OID%20ASC&outSR=102100' # noqa
self.burn_json = None
self.burn_json_time = 0
self.burn_json_lifetime = 600 # seconds we cache the json for
self.burn_json_refresh_attempt_time = 0
try:
# try not to set one variable without setting the other here.
cache_path = self.burn_data_cache_path()
content = cache_path.read_bytes()
mtime = cache_path.stat().st_mtime
self.burn_json = content
self.burn_json_time = mtime
except FileNotFoundError:
pass
def burn_data_cache_path(self):
'''returns a pathlib object corresponding to the filepath where we
cache the downloaded burn JSON'''
return pathlib.Path(os.path.join(self.dot_mavproxy_path, "burn_json.txt"))
def usage(self):
'''returns usage string'''
return "Usage: anufp <burnkml (BURNID)>"
def cmd(self, args):
'''handle commands from stdin'''
if len(args) < 1:
print(self.usage())
return
if args[0] == "burnkml":
return self.cmd_burnkml(args[1:])
print(self.usage())
def get_burn_json_object(self):
'''returns a json object containing the burn data'''
self.ensure_burn_json()
return json.loads(self.burn_json)
def cmd_burnkml(self, args):
'''command to trigger creation of a KML layer from a burn ID (e.g. FB511)'''
kml = self.module('kmlread')
if kml is None:
self.message("Need kmlread module")
return
if len(args) != 1:
print(self.usage())
print("BURNID is usually of the form FBxxx e.g. FB511")
return
burn_name = args[0]
burn_json = self.get_burn_json_object()
if burn_json is None:
return
found_feature = None
seen_bops = []
for feature in burn_json["features"]:
bop_id = feature["attributes"]["BOP_ID"]
seen_bops.append(bop_id)
if bop_id == burn_name:
found_feature = feature
break
if found_feature is None:
self.message(f"Burn {burn_name} not found in downloaded JSON (found {seen_bops})")
return
if "geometry" not in feature:
self.message(f"geometry missing from feature {burn_name}")
return
rings = feature["geometry"]["rings"]
for ring in rings:
coordinates = []
for item in ring:
lat, lon = self.MetersToLatLon(item[0], item[1])
coordinates.append((lat, lon))
kml.add_polygon(burn_name, coordinates)
# from: https://gist.githubusercontent.com/maptiler/fddb5ce33ba995d5523de9afdf8ef118/raw/d7565390d2480bfed3c439df5826f1d9e4b41761/globalmaptiles.py # noqa
def MetersToLatLon(self, mx, my):
"Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum"
originShift = 2 * math.pi * 6378137 / 2.0
# 20037508.342789244
lon = (mx / originShift) * 180.0
lat = (my / originShift) * 180.0
lat = 180 / math.pi * (2 * math.atan(math.exp(lat * math.pi / 180.0)) - math.pi / 2.0)
return lat, lon
def should_refresh_burn_json(self):
'''returns true if we should download the data from the ACT government
website again'''
now = time.time()
if now - self.burn_json_refresh_attempt_time < 60:
return False
if self.burn_json is None:
return True
if now - self.burn_json_time > self.burn_json_lifetime:
return True
return False
def message(self, msg):
'''simply emit msg prefixed with an identifying string'''
print(f"anufp: {msg}")
def refresh_burn_json(self):
'''downloads content from ACT Government URL, caches it in the
filesystem'''
tstart = time.time()
self.message("Refreshing burn data JSON")
self.burn_json_refresh_attempt_time = tstart
content = mp_util.download_url(self.burn_data_url)
if content is None:
return
self.burn_json = content
tstop = time.time()
self.burn_json_time = tstop
# cache the data:
cache_path = self.burn_data_cache_path()
cache_path.write_bytes(content)
self.message(f"Refreshed burn data JSON ({tstop-tstart}s)")
def ensure_burn_json(self):
'''checks to see if we should refresh the JSON data, and does that if
required'''
if not self.should_refresh_burn_json():
return
self.refresh_burn_json()
def idle_task(self):
# download the burn JSON once at startup to avoid delay on
# first kml command.
if self.burn_json is None:
self.ensure_burn_json()
|
class ANUFireProject(mp_module.MPModule):
def __init__(self, mpstate):
pass
def burn_data_cache_path(self):
'''returns a pathlib object corresponding to the filepath where we
cache the downloaded burn JSON'''
pass
def usage(self):
'''returns usage string'''
pass
def cmd(self, args):
'''handle commands from stdin'''
pass
def get_burn_json_object(self):
'''returns a json object containing the burn data'''
pass
def cmd_burnkml(self, args):
'''command to trigger creation of a KML layer from a burn ID (e.g. FB511)'''
pass
def MetersToLatLon(self, mx, my):
'''Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum'''
pass
def should_refresh_burn_json(self):
'''returns true if we should download the data from the ACT government
website again'''
pass
def message(self, msg):
'''simply emit msg prefixed with an identifying string'''
pass
def refresh_burn_json(self):
'''downloads content from ACT Government URL, caches it in the
filesystem'''
pass
def ensure_burn_json(self):
'''checks to see if we should refresh the JSON data, and does that if
required'''
pass
def idle_task(self):
pass
| 13 | 10 | 13 | 2 | 9 | 2 | 3 | 0.22 | 1 | 3 | 0 | 0 | 12 | 7 | 12 | 50 | 165 | 33 | 110 | 43 | 97 | 24 | 105 | 43 | 92 | 10 | 2 | 2 | 30 |
7,152 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_arm.py
|
MAVProxy.modules.mavproxy_arm.ArmModule
|
class ArmModule(mp_module.MPModule):
def __init__(self, mpstate):
super(ArmModule, self).__init__(mpstate, "arm", "arm/disarm handling", public=True)
checkables = "<" + "|".join(arming_masks.keys()) + ">"
self.add_command('arm', self.cmd_arm, 'arm motors', ['check ' + self.checkables(),
'uncheck ' + self.checkables(),
'list',
'throttle',
'safetyon',
'safetystatus',
'safetyoff',
'bits',
'prearms'])
self.add_command('disarm', self.cmd_disarm, 'disarm motors')
self.was_armed = False
def checkables(self):
return "<" + "|".join(arming_masks.keys()) + ">"
def cmd_arm(self, args):
'''arm commands'''
usage = "usage: arm <check|uncheck|list|throttle|safetyon|safetyoff|safetystatus|bits|prearms>"
if len(args) <= 0:
print(usage)
return
if args[0] == "check":
if (len(args) < 2):
print("usage: arm check " + self.checkables())
return
arming_mask = int(self.get_mav_param("ARMING_CHECK"))
name = args[1].lower()
if name == 'all':
arming_mask = 1
elif name in arming_masks:
arming_mask |= arming_masks[name]
else:
print("unrecognized arm check:", name)
return
if (arming_mask & ~0x1) == full_arming_mask:
arming_mask = 0x1
self.param_set("ARMING_CHECK", arming_mask)
return
if args[0] == "uncheck":
if (len(args) < 2):
print("usage: arm uncheck " + self.checkables())
return
arming_mask = int(self.get_mav_param("ARMING_CHECK"))
name = args[1].lower()
if name == 'all':
arming_mask = 0
elif name in arming_masks:
if arming_mask == arming_masks["all"]:
arming_mask = full_arming_mask
arming_mask &= ~arming_masks[name]
else:
print("unrecognized arm check:", args[1])
return
self.param_set("ARMING_CHECK", arming_mask)
return
if args[0] == "list":
arming_mask = int(self.get_mav_param("ARMING_CHECK"))
if arming_mask == 0:
print("NONE")
for name in sorted(arming_masks, key=lambda x : arming_masks[x]):
if arming_masks[name] & arming_mask:
print(name)
return
if args[0] == "bits":
for mask in sorted(arming_masks, key=lambda x : arming_masks[x]):
print("%s" % mask)
return
if args[0] == "prearms":
self.master.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavutil.mavlink.MAV_CMD_RUN_PREARM_CHECKS, # command
0, # confirmation
0, # param1
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
return
if args[0] == "throttle":
p2 = 0
if len(args) == 2 and args[1] == 'force':
p2 = 2989
self.master.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command
0, # confirmation
1, # param1 (1 to indicate arm)
p2, # param2 (all other params meaningless)
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
return
if args[0] == "safetyon":
self.master.mav.set_mode_send(self.target_system,
mavutil.mavlink.MAV_MODE_FLAG_DECODE_POSITION_SAFETY,
1)
return
if args[0] == "safetystatus":
try:
sys_status = self.master.messages['SYS_STATUS']
except KeyError:
print("Unknown; no SYS_STATUS")
return
if sys_status.onboard_control_sensors_enabled & mavutil.mavlink.MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS:
print("Safety is OFF (vehicle is dangerous)")
else:
print("Safety is ON (vehicle allegedly safe)")
return
if args[0] == "safetyoff":
self.master.mav.set_mode_send(self.target_system,
mavutil.mavlink.MAV_MODE_FLAG_DECODE_POSITION_SAFETY,
0)
return
print(usage)
def cmd_disarm(self, args):
'''disarm motors'''
p2 = 0
if len(args) == 1 and args[0] == 'force':
p2 = 21196
self.master.mav.command_long_send(
self.target_system, # target_system
0,
mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command
0, # confirmation
0, # param1 (0 to indicate disarm)
p2, # param2 (all other params meaningless)
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
def all_checks_enabled(self):
''' returns true if the UAV is skipping any arming checks'''
arming_check = self.get_mav_param("ARMING_CHECK")
if arming_check is None:
# AntennaTracker doesn't have arming checks
return False
arming_mask = int(arming_check)
if arming_mask == 1:
return True
for bit in arming_masks.values():
if not arming_mask & bit and bit != 1:
return False
return True
def mavlink_packet(self, m):
mtype = m.get_type()
if mtype == 'HEARTBEAT' and m.type != mavutil.mavlink.MAV_TYPE_GCS:
armed = self.master.motors_armed()
if armed != self.was_armed:
self.was_armed = armed
if armed and not self.all_checks_enabled():
self.say("Arming checks disabled")
ice_enable = self.get_mav_param('ICE_ENABLE', 0)
if ice_enable == 1:
rc = self.master.messages["RC_CHANNELS"]
v = self.mav_param.get('ICE_START_CHAN', None)
if v is None:
return
v = getattr(rc, 'chan%u_raw' % v)
if v <= 1300:
self.say("ICE Disabled")
|
class ArmModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def checkables(self):
pass
def cmd_arm(self, args):
'''arm commands'''
pass
def cmd_disarm(self, args):
'''disarm motors'''
pass
def all_checks_enabled(self):
''' returns true if the UAV is skipping any arming checks'''
pass
def mavlink_packet(self, m):
pass
| 7 | 3 | 30 | 2 | 27 | 6 | 7 | 0.21 | 1 | 3 | 0 | 0 | 6 | 1 | 6 | 44 | 188 | 19 | 165 | 24 | 158 | 34 | 115 | 24 | 108 | 26 | 2 | 4 | 42 |
7,153 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_asterix.py
|
MAVProxy.modules.mavproxy_asterix.AsterixModule
|
class AsterixModule(mp_module.MPModule):
def __init__(self, mpstate):
super(AsterixModule, self).__init__(mpstate, "asterix", "asterix SDPS data support")
self.threat_vehicles = {}
self.active_threat_ids = [] # holds all threat ids the vehicle is evading
self.add_command('asterix', self.cmd_asterix, "asterix control",
["<start|stop>","set (ASTERIXSETTING)"])
# filter_dist is distance in metres
self.asterix_settings = mp_settings.MPSettings([("port", int, 45454),
('debug', int, 0),
('filter_dist_xy', int, 1000),
('filter_dist_z', int, 250),
('filter_time', int, 20),
('wgs84_to_AMSL', float, -41.2),
('filter_use_vehicle2', bool, True),
])
self.add_completion_function('(ASTERIXSETTING)',
self.asterix_settings.completion)
self.sock = None
self.tracks = {}
self.start_listener()
# storage for vehicle positions, used for filtering
self.vehicle_pos = None
self.vehicle2_pos = None
self.adsb_packets_sent = 0
self.adsb_packets_not_sent = 0
self.adsb_byterate = 0 # actually bytes...
self.adsb_byterate_update_timestamp = 0
self.adsb_last_packets_sent = 0
if self.logdir is not None:
logpath = os.path.join(self.logdir, 'asterix.log')
else:
logpath = 'asterix.log'
self.logfile = open(logpath, 'wb')
self.pkt_count = 0
self.console.set_status('ASTX', 'ASTX --/--', row=6)
def print_status(self):
print("ADSB packets sent: %u" % self.adsb_packets_sent)
print("ADSB packets not sent: %u" % self.adsb_packets_not_sent)
print("ADSB bitrate: %u bytes/s" % int(self.adsb_byterate))
def cmd_asterix(self, args):
'''asterix command parser'''
usage = "usage: asterix <set|start|stop|restart|status>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
self.asterix_settings.command(args[1:])
elif args[0] == "start":
self.start_listener()
elif args[0] == "stop":
self.stop_listener()
elif args[0] == "restart":
self.stop_listener()
self.start_listener()
elif args[0] == "status":
self.print_status()
else:
print(usage)
def start_listener(self):
'''start listening for packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', self.asterix_settings.port))
self.sock.setblocking(False)
print("Started on port %u" % self.asterix_settings.port)
def stop_listener(self):
'''stop listening for packets'''
if self.sock is not None:
self.sock.close()
self.sock = None
self.tracks = {}
def set_secondary_vehicle_position(self, m):
'''store second vehicle position for filtering purposes'''
if m.get_type() != 'GLOBAL_POSITION_INT':
return
(lat, lon, heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01)
if abs(lat) < 1.0e-3 and abs(lon) < 1.0e-3:
return
self.vehicle2_pos = VehiclePos(m)
def could_collide_hor(self, vpos, adsb_pkt):
'''return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds'''
margin = self.asterix_settings.filter_dist_xy
timeout = self.asterix_settings.filter_time
alat = adsb_pkt.lat * 1.0e-7
alon = adsb_pkt.lon * 1.0e-7
avel = adsb_pkt.hor_velocity * 0.01
vvel = sqrt(vpos.vx**2 + vpos.vy**2)
dist = mp_util.gps_distance(vpos.lat, vpos.lon, alat, alon)
dist -= avel * timeout
dist -= vvel * timeout
if dist <= margin:
return True
return False
def could_collide_ver(self, vpos, adsb_pkt):
'''return true if vehicle could come within filter_dist_z meters of adsb vehicle in timeout seconds'''
if adsb_pkt.emitter_type < 100 or adsb_pkt.emitter_type > 104:
return True
margin = self.asterix_settings.filter_dist_z
vtype = adsb_pkt.emitter_type - 100
valt = vpos.alt
aalt1 = adsb_pkt.altitude * 0.001
if vtype == 2:
# weather, always yes
return True
if vtype == 4:
# bird of prey, always true
return True
# planes and migrating birds have 150m margin
aalt2 = aalt1 + adsb_pkt.ver_velocity * 0.01 * self.asterix_settings.filter_time
altsep1 = abs(valt - aalt1)
altsep2 = abs(valt - aalt2)
if altsep1 > 150 + margin and altsep2 > 150 + margin:
return False
return True
def should_send_adsb_pkt(self, adsb_pkt):
if self.vehicle_pos is not None:
if self.could_collide_hor(self.vehicle_pos, adsb_pkt) and self.could_collide_ver(self.vehicle_pos, adsb_pkt):
return True
if self.vehicle2_pos is not None:
if self.could_collide_hor(self.vehicle2_pos, adsb_pkt) and self.could_collide_ver(self.vehicle2_pos, adsb_pkt):
return True
return False
def idle_task(self):
'''called on idle'''
if self.sock is None:
return
try:
pkt = self.sock.recv(10240)
except Exception:
return
try:
if pkt.startswith(b'PICKLED:'):
pkt = pkt[8:]
# pickled packet
try:
amsg = [pickle.loads(pkt)]
except pickle.UnpicklingError:
amsg = asterix.parse(pkt)
else:
amsg = asterix.parse(pkt)
self.pkt_count += 1
self.console.set_status('ASTX', 'ASTX %u/%u' % (self.pkt_count, self.adsb_packets_sent), row=6)
except Exception:
print("bad packet")
return
try:
logpkt = b'AST:' + struct.pack('<dI', time.time(), len(pkt)) + pkt
self.logfile.write(logpkt)
except Exception:
pass
for m in amsg:
if self.asterix_settings.debug > 1:
print(m)
lat = m['I105']['Lat']['val']
lon = m['I105']['Lon']['val']
alt_f = m['I130']['Alt']['val']
climb_rate_fps = m['I220']['RoC']['val']
sac = m['I010']['SAC']['val']
sic = m['I010']['SIC']['val']
trkn = m['I040']['TrkN']['val']
# fake ICAO_address
icao_address = trkn & 0xFFFF
# use squawk for time in 0.1 second increments. This allows for old msgs to be discarded on vehicle
# when using more than one link to vehicle
squawk = (int(self.mpstate.attitude_time_s * 10) & 0xFFFF)
alt_m = alt_f * 0.3048
# asterix is WGS84, ArduPilot uses AMSL, which is EGM96
alt_m += self.asterix_settings.wgs84_to_AMSL
# consider filtering this packet out; if it's not close to
# either home or the vehicle position don't send it
adsb_pkt = self.master.mav.adsb_vehicle_encode(icao_address,
int(lat*1e7),
int(lon*1e7),
mavutil.mavlink.ADSB_ALTITUDE_TYPE_GEOMETRIC,
int(alt_m*1000), # mm
0, # heading
0, # hor vel
int(climb_rate_fps * 0.3048 * 100), # cm/s
("%08x" % icao_address).encode("ascii"),
100 + (trkn // 10000),
1,
(mavutil.mavlink.ADSB_FLAGS_VALID_COORDS |
mavutil.mavlink.ADSB_FLAGS_VALID_ALTITUDE |
mavutil.mavlink.ADSB_FLAGS_VALID_VELOCITY |
mavutil.mavlink.ADSB_FLAGS_VALID_HEADING),
squawk)
if icao_address in self.tracks:
self.tracks[icao_address].update(adsb_pkt, self.get_time())
else:
self.tracks[icao_address] = Track(adsb_pkt)
if self.asterix_settings.debug > 0:
print(adsb_pkt)
# send on all links
if self.should_send_adsb_pkt(adsb_pkt):
self.adsb_packets_sent += 1
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
#if adsb_pkt.hor_velocity < 1:
# print(adsb_pkt)
conn.mav.send(adsb_pkt)
else:
self.adsb_packets_not_sent += 1
adsb_mod = self.module('adsb')
if adsb_mod:
# the adsb module is loaded, display on the map
adsb_mod.mavlink_packet(adsb_pkt)
try:
for sysid in self.mpstate.sysid_outputs:
# fwd to sysid clients
adsb_pkt.pack(self.mpstate.sysid_outputs[sysid].mav)
self.mpstate.sysid_outputs[sysid].write(adsb_pkt.get_msgbuf())
except Exception:
pass
now = time.time()
delta = now - self.adsb_byterate_update_timestamp
if delta > 5:
self.adsb_byterate_update_timestamp = now
bytes_per_adsb_packet = 38 # FIXME: find constant
self.adsb_byterate = (self.adsb_packets_sent - self.adsb_last_packets_sent)/delta * bytes_per_adsb_packet
self.adsb_last_packets_sent = self.adsb_packets_sent
def mavlink_packet(self, m):
'''get time from mavlink ATTITUDE'''
if m.get_type() == 'GLOBAL_POSITION_INT':
if abs(m.lat) < 1000 and abs(m.lon) < 1000:
return
self.vehicle_pos = VehiclePos(m)
|
class AsterixModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def print_status(self):
pass
def cmd_asterix(self, args):
'''asterix command parser'''
pass
def start_listener(self):
'''start listening for packets'''
pass
def stop_listener(self):
'''stop listening for packets'''
pass
def set_secondary_vehicle_position(self, m):
'''store second vehicle position for filtering purposes'''
pass
def could_collide_hor(self, vpos, adsb_pkt):
'''return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds'''
pass
def could_collide_ver(self, vpos, adsb_pkt):
'''return true if vehicle could come within filter_dist_z meters of adsb vehicle in timeout seconds'''
pass
def should_send_adsb_pkt(self, adsb_pkt):
pass
def idle_task(self):
'''called on idle'''
pass
def mavlink_packet(self, m):
'''get time from mavlink ATTITUDE'''
pass
| 12 | 8 | 22 | 1 | 18 | 3 | 4 | 0.16 | 1 | 11 | 3 | 0 | 11 | 14 | 11 | 49 | 254 | 25 | 204 | 65 | 192 | 32 | 171 | 65 | 159 | 17 | 2 | 3 | 49 |
7,154 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_asterix.py
|
MAVProxy.modules.mavproxy_asterix.Track
|
class Track:
def __init__(self, adsb_pkt):
self.pkt = adsb_pkt
self.last_time = 0
def update(self, pkt, tnow):
dt = tnow - self.last_time
if dt < 0 or dt > 10:
self.last_time = tnow
return
if dt < 0.1:
return
self.last_time = tnow
dist = mp_util.gps_distance(self.pkt.lat*1e-7, self.pkt.lon*1e-7,
pkt.lat*1e-7, pkt.lon*1e-7)
if dist > 0.01:
heading = mp_util.gps_bearing(self.pkt.lat*1e-7, self.pkt.lon*1e-7,
pkt.lat*1e-7, pkt.lon*1e-7)
spd = dist / dt
pkt.heading = int(heading*100)
new_vel = int(spd * 100)
#print(pkt.ICAO_address, new_vel*0.01, pkt.hor_velocity*0.01)
pkt.hor_velocity = new_vel
if pkt.hor_velocity > 65535:
pkt.hor_velocity = 65535
self.pkt = pkt
|
class Track:
def __init__(self, adsb_pkt):
pass
def update(self, pkt, tnow):
pass
| 3 | 0 | 12 | 0 | 12 | 1 | 3 | 0.04 | 0 | 1 | 0 | 0 | 2 | 2 | 2 | 2 | 26 | 1 | 24 | 10 | 21 | 1 | 22 | 10 | 19 | 5 | 0 | 1 | 6 |
7,155 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_asterix.py
|
MAVProxy.modules.mavproxy_asterix.VehiclePos
|
class VehiclePos(object):
def __init__(self, GPI):
self.lat = GPI.lat * 1.0e-7
self.lon = GPI.lon * 1.0e-7
self.alt = GPI.alt * 1.0e-3
self.vx = GPI.vx * 1.0e-2
self.vy = GPI.vy * 1.0e-2
|
class VehiclePos(object):
def __init__(self, GPI):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 5 | 1 | 1 | 7 | 0 | 7 | 7 | 5 | 0 | 7 | 7 | 5 | 1 | 1 | 0 | 1 |
7,156 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_auxopt.py
|
MAVProxy.modules.mavproxy_auxopt.AuxoptModule
|
class AuxoptModule(mp_module.MPModule):
def __init__(self, mpstate):
super(AuxoptModule, self).__init__(mpstate, "auxopt", "auxopt command handling")
self.add_command('auxopt', self.cmd_auxopt, 'select option for aux switches on CH7 and CH8 (ArduCopter only)',
['set <7|8> <Nothing|Flip|SimpleMode|RTL|SaveTrim|SaveWP|MultiMode|CameraTrigger|Sonar|Fence|ResetYaw|SuperSimpleMode|AcroTrainer|Acro|Auto|AutoTune|Land>',
'reset <7|8|all>',
'<show|list>'])
def aux_show(self, channel):
param = "CH%s_OPT" % channel
opt_num = str(int(self.get_mav_param(param)))
option = None
for k in aux_options.keys():
if opt_num == aux_options[k]:
option = k
break
else:
print("AUX Channel is currently set to unknown value " + opt_num)
return
print("AUX Channel is currently set to " + option)
def aux_option_validate(self, option):
for k in aux_options:
if option.upper() == k.upper():
return k
return None
def cmd_auxopt(self, args):
'''handle AUX switches (CH7, CH8) settings'''
if self.mpstate.vehicle_type != 'copter':
print("This command is only available for copter")
return
if len(args) == 0 or args[0] not in ('set', 'show', 'reset', 'list'):
print("Usage: auxopt set|show|reset|list")
return
if args[0] == 'list':
print("Options available:")
for s in sorted(aux_options.keys()):
print(' ' + s)
elif args[0] == 'show':
if len(args) > 2 and args[1] not in ['7', '8', 'all']:
print("Usage: auxopt show [7|8|all]")
return
if len(args) < 2 or args[1] == 'all':
self.aux_show('7')
self.aux_show('8')
return
self.aux_show(args[1])
elif args[0] == 'reset':
if len(args) < 2 or args[1] not in ['7', '8', 'all']:
print("Usage: auxopt reset 7|8|all")
return
if args[1] == 'all':
self.param_set('CH7_OPT', '0')
self.param_set('CH8_OPT', '0')
return
param = "CH%s_OPT" % args[1]
self.param_set(param, '0')
elif args[0] == 'set':
if len(args) < 3 or args[1] not in ['7', '8']:
print("Usage: auxopt set 7|8 OPTION")
return
option = self.aux_option_validate(args[2])
if not option:
print("Invalid option " + args[2])
return
param = "CH%s_OPT" % args[1]
self.param_set(param, aux_options[option])
else:
print("Usage: auxopt set|show|list")
|
class AuxoptModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def aux_show(self, channel):
pass
def aux_option_validate(self, option):
pass
def cmd_auxopt(self, args):
'''handle AUX switches (CH7, CH8) settings'''
pass
| 5 | 1 | 17 | 0 | 16 | 0 | 5 | 0.02 | 1 | 3 | 0 | 0 | 4 | 0 | 4 | 42 | 70 | 3 | 66 | 13 | 61 | 1 | 59 | 13 | 54 | 14 | 2 | 2 | 21 |
7,157 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_battery.py
|
MAVProxy.modules.mavproxy_battery.BatteryModule
|
class BatteryModule(mp_module.MPModule):
def __init__(self, mpstate):
super(BatteryModule, self).__init__(mpstate, "battery", "battery commands")
self.add_command('bat', self.cmd_bat, "show battery information")
self.last_battery_announce = 0
self.last_battery_announce_time = 0
self.last_battery_cell_announce_time = 0
self.battery_level = {}
self.voltage_level = {}
self.current_battery = {}
self.per_cell = {}
self.servo_voltage = -1
self.high_servo_voltage = -1
self.last_servo_warn_time = 0
self.last_vcc_warn_time = 0
self.settings.append(
MPSetting('battwarn', int, 1, 'Battery Warning Time', tab='Battery'))
self.settings.append(
MPSetting('batwarncell', float, 3.7, 'Battery cell Warning level'))
self.settings.append(
MPSetting('servowarn', float, 4.3, 'Servo voltage warning level'))
self.settings.append(
MPSetting('vccwarn', float, 4.3, 'Vcc voltage warning level'))
self.settings.append(MPSetting('numcells', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells2', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells3', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells4', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells5', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells6', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells7', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells8', int, 0, range=(0,50), increment=1))
self.settings.append(MPSetting('numcells9', int, 0, range=(0,50), increment=1))
self.battery_period = mavutil.periodic_event(5)
def idstr(self, id):
return "" if id == 0 else "%u" % (id+1)
def numcells(self, id):
ncells = "numcells" + self.idstr(id)
return self.settings.get_setting(ncells).value
def cmd_bat(self, args):
'''show battery levels'''
if 0 not in self.battery_level:
print("No battery information")
return
print("Flight battery: %u%%" % self.battery_level[0])
for id in range(9):
if self.numcells(id) != 0 and id in self.voltage_level:
print("Bat%u %.2f V/cell for %u cells %.1fA %.2f%%" % (id+1,
self.per_cell[id],
self.numcells(id),
self.current_battery[id],
self.battery_level[id]))
def battery_report(self):
battery_string = ''
for id in range(9):
if not id in self.voltage_level:
continue
batt_mon = int(self.get_mav_param('BATT%s_MONITOR' % self.idstr(id),0))
if batt_mon == 0:
continue
# show per-cell voltage if number of cells is set
if self.numcells(id) != 0:
#this is a workaround for the race condition since self.per_cell only gets filled in once the setting is set
if not id in self.per_cell:
continue
if batt_mon == 3:
battery_string += 'Batt%u: %.2fV*%uS ' % (id+1, self.per_cell[id], self.numcells(id))
continue
if batt_mon >= 4:
battery_string += 'Batt%u: %u%%/%.2fV*%uS %.1fA ' % (id+1, self.battery_level[id], self.per_cell[id], self.numcells(id), self.current_battery[id])
continue
#show full battery voltage when number of cells is not set
if batt_mon == 3:
battery_string += 'Batt%u: %.2fV ' % (id+1, self.voltage_level[id])
elif batt_mon >= 4:
battery_string += 'Batt%u: %u%%/%.2fV %.1fA ' % (id+1,
self.battery_level[id],
self.voltage_level[id],
self.current_battery[id])
self.console.set_status('Battery', battery_string, row=1)
# only announce first battery
if not 0 in self.battery_level:
return
batt_mon = int(self.get_mav_param('BATT_MONITOR',0))
if batt_mon == 0:
return
rbattery_level = int((self.battery_level[0]+5)/10)*10
if batt_mon >= 4 and self.settings.battwarn > 0 and time.time() > self.last_battery_announce_time + 60*self.settings.battwarn:
if rbattery_level != self.last_battery_announce:
self.say("Flight battery %u percent" % rbattery_level, priority='notification')
if rbattery_level <= 20:
self.say("Flight battery warning")
self.last_battery_announce_time = time.time()
if (self.numcells(0) != 0 and 0 in self.per_cell and self.per_cell[0] < self.settings.batwarncell and
self.settings.battwarn > 0 and time.time() > self.last_battery_cell_announce_time + 60*self.settings.battwarn):
self.say("Cell warning")
self.last_battery_cell_announce_time = time.time()
def battery_update(self, BATTERY_STATUS):
'''update battery level'''
# main flight battery
id = BATTERY_STATUS.id
self.battery_level[id] = BATTERY_STATUS.battery_remaining
self.voltage_level[id] = 0.0
for vraw in BATTERY_STATUS.voltages:
if vraw != 65535:
self.voltage_level[id] += vraw * 0.001
self.current_battery[id] = BATTERY_STATUS.current_battery*0.01
if self.numcells(id) > 0:
self.per_cell[id] = self.voltage_level[id] / self.numcells(id)
def power_status_update(self, POWER_STATUS):
'''update POWER_STATUS warnings level'''
now = time.time()
Vservo = POWER_STATUS.Vservo * 0.001
Vcc = POWER_STATUS.Vcc * 0.001
self.high_servo_voltage = max(self.high_servo_voltage, Vservo)
if self.high_servo_voltage > 1 and Vservo < self.settings.servowarn:
if now - self.last_servo_warn_time > 30:
self.last_servo_warn_time = now
self.say("Servo volt %.1f" % Vservo)
if Vservo < 1:
# prevent continuous announcements on power down
self.high_servo_voltage = Vservo
if Vcc > 0 and Vcc < self.settings.vccwarn:
if now - self.last_vcc_warn_time > 30:
self.last_vcc_warn_time = now
self.say("Vcc %.1f" % Vcc)
def mavlink_packet(self, m):
'''handle a mavlink packet'''
mtype = m.get_type()
if mtype == "BATTERY_STATUS":
self.battery_update(m)
if mtype == "BATTERY2":
self.battery2_voltage = m.voltage * 0.001
if mtype == "POWER_STATUS":
self.power_status_update(m)
if self.battery_period.trigger():
self.battery_report()
|
class BatteryModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def idstr(self, id):
pass
def numcells(self, id):
pass
def cmd_bat(self, args):
'''show battery levels'''
pass
def battery_report(self):
pass
def battery_update(self, BATTERY_STATUS):
'''update battery level'''
pass
def power_status_update(self, POWER_STATUS):
'''update POWER_STATUS warnings level'''
pass
def mavlink_packet(self, m):
'''handle a mavlink packet'''
pass
| 9 | 4 | 18 | 1 | 16 | 1 | 5 | 0.08 | 1 | 5 | 1 | 0 | 8 | 13 | 8 | 46 | 153 | 17 | 126 | 33 | 117 | 10 | 113 | 33 | 104 | 16 | 2 | 3 | 39 |
7,158 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_calibration.py
|
MAVProxy.modules.mavproxy_calibration.CalibrationModule
|
class CalibrationModule(mp_module.MPModule):
def __init__(self, mpstate):
super(CalibrationModule, self).__init__(mpstate, "calibration")
self.add_command('ground', self.cmd_ground, 'do a ground start')
self.add_command('level', self.cmd_level, 'set level on a multicopter')
self.add_command('compassmot', self.cmd_compassmot, 'do compass/motor interference calibration')
self.add_command('calpress', self.cmd_calpressure,'calibrate pressure sensors')
self.add_command('accelcal', self.cmd_accelcal, 'do 3D accelerometer calibration')
self.add_command('accelcalsimple', self.cmd_accelcal_simple, 'do simple accelerometer calibration')
self.add_command('gyrocal', self.cmd_gyrocal, 'do gyro calibration')
self.add_command('ahrstrim', self.cmd_ahrstrim, 'do AHRS trim')
self.add_command('magcal', self.cmd_magcal, "magcal")
self.add_command('forcecal', self.cmd_forcecal, "force calibration save")
self.accelcal_count = -1
self.accelcal_wait_enter = False
self.compassmot_running = False
self.empty_input_count = 0
self.magcal_progess = []
def cmd_ground(self, args):
'''do a ground start mode'''
self.master.calibrate_imu()
def cmd_level(self, args):
'''run a accel level'''
print("level is no longer supported; use ahrstrim, accelcal or accelcalsimple")
def cmd_accelcal(self, args):
'''do a full 3D accel calibration'''
mav = self.master
# ack the APM to begin 3D calibration of accelerometers
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 0, 0, 1, 0, 0)
self.accelcal_count = 0
self.accelcal_wait_enter = False
def cmd_accelcal_simple(self, args):
'''do a simple accel calibration'''
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 0, 0, 4, 0, 0)
def cmd_forcecal(self, args):
'''force calibration save'''
usage = "usage: forcecal accel|compass|both"
if len(args) < 1:
print(usage)
return
param2 = 0
param5 = 0
if args[0].lower() == "accel":
param5 = 76
elif args[0].lower() == "compass":
param2 = 76
elif args[0].lower() == "both":
param2 = 76
param5 = 76
else:
print(usage)
return
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, param2, 0, 0, param5, 0, 0)
def cmd_gyrocal(self, args):
'''do a full gyro calibration'''
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
1, 0, 0, 0, 0, 0, 0)
def cmd_ahrstrim(self, args):
'''do a AHRS trim'''
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 0, 0, 2, 0, 0)
def mavlink_packet(self, m):
'''handle mavlink packets'''
mtype = m.get_type()
if self.accelcal_count != -1:
if mtype == 'STATUSTEXT':
# handle accelcal packet
text = str(m.text)
if text.startswith('Place '):
self.accelcal_wait_enter = True
self.empty_input_count = self.mpstate.empty_input_count
if mtype == 'MAG_CAL_PROGRESS':
while m.compass_id >= len(self.magcal_progess):
self.magcal_progess.append("")
self.magcal_progess[m.compass_id] = "%u%%" % m.completion_pct
self.console.set_status('Progress', 'Calibration Progress: ' + " ".join(self.magcal_progess), row=4)
elif mtype == 'MAG_CAL_REPORT':
if m.cal_status == mavutil.mavlink.MAG_CAL_SUCCESS:
result = "SUCCESS"
else:
result = "FAILED"
self.magcal_progess[m.compass_id] = result
self.console.set_status('Progress', 'Calibration Progress: ' + " ".join(self.magcal_progess), row=4)
print("Calibration of compass %u %s: fitness %.3f" % (m.compass_id, result, m.fitness))
mav = self.master
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_DO_ACCEPT_MAG_CAL, 0,
1<<m.compass_id, 0, 0, 0, 0, 0, 0)
def idle_task(self):
'''handle mavlink packets'''
if self.accelcal_count != -1:
if self.accelcal_wait_enter and self.empty_input_count != self.mpstate.empty_input_count:
self.accelcal_wait_enter = False
self.accelcal_count += 1
# tell the APM that user has done as requested
self.master.mav.command_ack_send(self.accelcal_count, 1)
if self.accelcal_count >= 6:
self.accelcal_count = -1
if self.compassmot_running:
if self.mpstate.empty_input_count != self.empty_input_count:
# user has hit enter, stop the process
self.compassmot_running = False
print("sending stop")
self.master.mav.command_ack_send(0, 1)
def cmd_compassmot(self, args):
'''do a compass/motor interference calibration'''
mav = self.master
print("compassmot starting")
mav.mav.command_long_send(mav.target_system, mav.target_component,
mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 0, 0, 0, 1, 0)
self.compassmot_running = True
self.empty_input_count = self.mpstate.empty_input_count
def cmd_calpressure(self, args):
'''calibrate pressure sensors'''
self.master.calibrate_pressure()
def print_magcal_usage(self):
print("Usage: magcal <start|accept|cancel|yaw>")
def cmd_magcal(self, args):
'''control magnetometer calibration'''
if len(args) < 1:
self.print_magcal_usage()
return
if args[0] == 'start':
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_START_MAG_CAL, # command
0, # confirmation
0, # p1: mag_mask
0, # p2: retry
1, # p3: autosave
0, # p4: delay
0, # param5
0, # param6
0) # param7
elif args[0] == 'accept':
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_ACCEPT_MAG_CAL, # command
0, # confirmation
0, # p1: mag_mask
0, # param2
1, # param3
0, # param4
0, # param5
0, # param6
0) # param7
elif args[0] == 'cancel':
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_CANCEL_MAG_CAL, # command
0, # confirmation
0, # p1: mag_mask
0, # param2
1, # param3
0, # param4
0, # param5
0, # param6
0) # param7
elif args[0] == 'yaw':
if len(args) < 2:
print("Usage: magcal yaw YAW_DEGREES <mask>")
return
yaw_deg = float(args[1])
mask = 0
if len(args) > 2:
mask = int(args[2])
print("Calibrating for yaw %.1f degrees with mask 0x%02x" % (yaw_deg, mask))
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_FIXED_MAG_CAL_YAW, # command
0, # confirmation
yaw_deg, # p1: yaw in degrees
mask, # p2: mask
0, # p3: lat_deg
0, # p4: lon_deg
0, # param5
0, # param6
0) # param7
else:
self.print_magcal_usage()
return
|
class CalibrationModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_ground(self, args):
'''do a ground start mode'''
pass
def cmd_level(self, args):
'''run a accel level'''
pass
def cmd_accelcal(self, args):
'''do a full 3D accel calibration'''
pass
def cmd_accelcal_simple(self, args):
'''do a simple accel calibration'''
pass
def cmd_forcecal(self, args):
'''force calibration save'''
pass
def cmd_gyrocal(self, args):
'''do a full gyro calibration'''
pass
def cmd_ahrstrim(self, args):
'''do a AHRS trim'''
pass
def mavlink_packet(self, m):
'''handle mavlink packets'''
pass
def idle_task(self):
'''handle mavlink packets'''
pass
def cmd_compassmot(self, args):
'''do a compass/motor interference calibration'''
pass
def cmd_calpressure(self, args):
'''calibrate pressure sensors'''
pass
def print_magcal_usage(self):
pass
def cmd_magcal(self, args):
'''control magnetometer calibration'''
pass
| 15 | 12 | 14 | 0 | 13 | 4 | 3 | 0.33 | 1 | 4 | 0 | 0 | 14 | 5 | 14 | 52 | 214 | 16 | 182 | 35 | 167 | 60 | 115 | 35 | 100 | 8 | 2 | 3 | 37 |
7,159 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_cameraview.py
|
MAVProxy.modules.mavproxy_cameraview.CameraViewModule
|
class CameraViewModule(mp_module.MPModule):
def __init__(self, mpstate):
super(CameraViewModule, self).__init__(mpstate, "cameraview")
self.add_command('cameraview', self.cmd_cameraview, "camera view")
self.roll = 0
self.pitch = 0
self.yaw = 0
self.mount_roll = 0
self.mount_pitch = 0
self.mount_yaw = 0
self.height = 0
self.lat = 0
self.lon = 0
self.home_height = 0
self.hdg = 0
self.camera_params = CameraParams() # TODO how to get actual camera params
self.view_settings = mp_settings.MPSettings(
[ ('r', float, 0.5),
('g', float, 0.5),
('b', float, 1.0),
])
self.update_col()
def update_col(self):
self.col = tuple(int(255*c) for c in (self.view_settings.r, self.view_settings.g, self.view_settings.b))
def cmd_cameraview(self, args):
'''camera view commands'''
state = self
if args and args[0] == 'set':
if len(args) < 3:
state.view_settings.show_all()
else:
state.view_settings.set(args[1], args[2])
state.update_col()
else:
print('usage: cameraview set')
def unload(self):
'''unload module'''
pass
def scale_rc(self, servo, min, max, param):
'''scale a PWM value'''
# default to servo range of 1000 to 2000
min_pwm = self.get_mav_param('%s_MIN' % param, 0)
max_pwm = self.get_mav_param('%s_MAX' % param, 0)
if min_pwm == 0 or max_pwm == 0:
return 0
if max_pwm == min_pwm:
p = 0.0
else:
p = (servo-min_pwm) / float(max_pwm-min_pwm)
v = min + p*(max-min)
if v < min:
v = min
if v > max:
v = max
return v
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
state = self
mtype = m.get_type()
if mtype == 'GLOBAL_POSITION_INT':
state.lat, state.lon = m.lat*scale_latlon, m.lon*scale_latlon
state.hdg = m.hdg*scale_hdg
agl = self.module('terrain').ElevationModel.GetElevation(state.lat, state.lon)
if agl is not None:
state.height = m.relative_alt*scale_relative_alt + state.home_height - agl
elif mtype == 'ATTITUDE':
state.roll, state.pitch, state.yaw = math.degrees(m.roll), math.degrees(m.pitch), math.degrees(m.yaw)
elif mtype in ['GPS_RAW', 'GPS_RAW_INT']:
if self.module('wp').wploader.count() > 0:
home = self.module('wp').wploader.wp(0).x, self.module('wp').wploader.wp(0).y
else:
home = [self.master.field('HOME', c)*scale_latlon for c in ['lat', 'lon']]
old = state.home_height # TODO TMP
agl = self.module('terrain').ElevationModel.GetElevation(*home)
if agl is None:
return
state.home_height = agl
# TODO TMP
if state.home_height != old:
# tridge said to get home pos from wploader,
# but this is not the same as from master() below...!!
# using master() gives the right coordinates
# (i.e. matches GLOBAL_POSITION_INT coords, and $IMHOME in sim_arduplane.sh)
# and wploader is a bit off
print('home height changed from',old,'to',state.home_height)
elif mtype == 'SERVO_OUTPUT_RAW':
for (axis, attr) in [('ROLL', 'mount_roll'), ('TILT', 'mount_pitch'), ('PAN', 'mount_yaw')]:
channel = int(self.get_mav_param('MNT_RC_IN_{0}'.format(axis), 0))
if self.get_mav_param('MNT_STAB_{0}'.format(axis), 0) and channel:
# enabled stabilisation on this axis
# TODO just guessing that RC_IN_ROLL gives the servo number, but no idea if this is really the case
servo = 'servo{0}_raw'.format(channel)
centidegrees = self.scale_rc(getattr(m, servo),
self.get_mav_param('MNT_ANGMIN_{0}'.format(axis[:3])),
self.get_mav_param('MNT_ANGMAX_{0}'.format(axis[:3])),
param='RC{0}'.format(channel))
setattr(state, attr, centidegrees*0.01)
#state.mount_roll = min(max(-state.roll,-45),45)#TODO TMP
#state.mount_yaw = min(max(-state.yaw,-45),45)#TODO TMP
#state.mount_pitch = min(max(-state.pitch,-45),45)#TODO TMP
else:
return
if self.mpstate.map: # if the map module is loaded, redraw polygon
# get rid of the old polygon
self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('CameraView'))
# camera view polygon determined by projecting corner pixels of the image onto the ground
pixel_positions = [cuav_util.pixel_position(px[0],px[1], state.height, state.pitch+state.mount_pitch, state.roll+state.mount_roll, state.yaw+state.mount_yaw, state.camera_params) for px in [(0,0), (state.camera_params.xresolution,0), (state.camera_params.xresolution,state.camera_params.yresolution), (0,state.camera_params.yresolution)]]
if any(pixel_position is None for pixel_position in pixel_positions):
# at least one of the pixels is not on the ground
# so it doesn't make sense to try to draw the polygon
return
gps_positions = [mp_util.gps_newpos(state.lat, state.lon, math.degrees(math.atan2(*pixel_position)), math.hypot(*pixel_position)) for pixel_position in pixel_positions]
# draw new polygon
self.mpstate.map.add_object(mp_slipmap.SlipPolygon('cameraview', gps_positions+[gps_positions[0]], # append first element to close polygon
layer='CameraView', linewidth=2, colour=state.col))
|
class CameraViewModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def update_col(self):
pass
def cmd_cameraview(self, args):
'''camera view commands'''
pass
def unload(self):
'''unload module'''
pass
def scale_rc(self, servo, min, max, param):
'''scale a PWM value'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
| 7 | 4 | 20 | 1 | 16 | 4 | 4 | 0.27 | 1 | 7 | 3 | 0 | 6 | 14 | 6 | 44 | 123 | 8 | 94 | 37 | 87 | 25 | 78 | 37 | 71 | 13 | 2 | 3 | 24 |
7,160 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_chat/__init__.py
|
MAVProxy.modules.mavproxy_chat.chat
|
class chat(mp_module.MPModule):
def __init__(self, mpstate):
# call parent class
super(chat, self).__init__(mpstate, "chat", "OpenAI chat support")
# register module and commands
self.add_command('chat', self.cmd_chat, "chat module", ["show"])
# keep reference to mpstate
self.mpstate = mpstate
# a dictionary of command_ack mavcmds we are waiting for
# key is the mavcmd, value is None or the MAV_RESULT (e.g. 0 to 9)
# we assume we will never be waiting for two of the same mavcmds at the same time
self.command_ack_waiting = {}
# run chat window in a separate thread
self.thread = Thread(target=self.create_chat_window)
self.thread.start()
# create chat window (should be called from a new thread)
def create_chat_window(self):
if mp_util.has_wxpython:
# create chat window
self.chat_window = chat_window.chat_window(self.mpstate, self.wait_for_command_ack)
else:
print("chat: wx support required")
# show help on command line options
def usage(self):
return "Usage: chat <show>"
# control behaviour of the module
def cmd_chat(self, args):
if len(args) == 0:
print(self.usage())
elif args[0] == "show":
self.show()
else:
print(self.usage())
# show chat input window
def show(self):
self.chat_window.show()
# handle mavlink packet
def mavlink_packet(self, m):
if m.get_type() == 'COMMAND_ACK':
self.handle_command_ack(m)
# handle_command_ack. should be called if module receives a COMMAND_ACK command
def handle_command_ack(self, m):
# return immediately if we are not waiting for this command ack
if m.command not in self.command_ack_waiting:
return
# throw away value if result in progress
if m.result == mavutil.mavlink.MAV_RESULT_IN_PROGRESS:
return
# set the mav result for this command
self.command_ack_waiting[m.command] = m.result
# wait for COMMAND_ACK with the specified mav_cmd
# this should be called immediately after sending a command_long or command_int
# mav_cmd should be set to the command id that was sent
# returns MAV_RESULT if command ack received, False if timed out
# Note: this should not be called from the main thread because it blocks for up to "timeout" seconds
def wait_for_command_ack(self, mav_cmd, timeout=1):
# error if we are already waiting for this command ack
if mav_cmd in self.command_ack_waiting:
print("chat: already waiting for command ack for mavcmd:" + str(mav_cmd))
return False
# add to list of commands we are waiting for (None indicates we don't know result yet)
self.command_ack_waiting[mav_cmd] = None
# wait for ack, checking for a response every 0.1 seconds
start_time = time.time()
while time.time() - start_time < timeout:
# check if we got the ack we were waiting for
result = self.command_ack_waiting.get(mav_cmd, None)
if result is not None:
# remove from list of commands we are waiting for
del self.command_ack_waiting[mav_cmd]
return result
time.sleep(0.1)
# timeout, remove from list of commands we are waiting for
# return False indicating timeout
del self.command_ack_waiting[mav_cmd]
return False
|
class chat(mp_module.MPModule):
def __init__(self, mpstate):
pass
def create_chat_window(self):
pass
def usage(self):
pass
def cmd_chat(self, args):
pass
def show(self):
pass
def mavlink_packet(self, m):
pass
def handle_command_ack(self, m):
pass
def wait_for_command_ack(self, mav_cmd, timeout=1):
pass
| 9 | 0 | 9 | 1 | 6 | 2 | 2 | 0.62 | 1 | 3 | 0 | 0 | 8 | 4 | 8 | 46 | 93 | 17 | 47 | 15 | 38 | 29 | 44 | 15 | 35 | 4 | 2 | 2 | 17 |
7,161 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Light
|
class Light(object):
def __init__(self,
position=Vector3(0.0, 0.0, 1.0),
ambient=Vector3(1.0, 1.0, 1.0),
diffuse=Vector3(1.0, 1.0, 1.0),
specular=Vector3(1.0, 1.0, 1.0),
att_linear=0.0,
att_quad=0.0):
self.position = position
self.ambient = ambient
self.diffuse = diffuse
self.specular = specular
self.att_linear = att_linear
self.att_quad = att_quad
|
class Light(object):
def __init__(self,
position=Vector3(0.0, 0.0, 1.0),
ambient=Vector3(1.0, 1.0, 1.0),
diffuse=Vector3(1.0, 1.0, 1.0),
specular=Vector3(1.0, 1.0, 1.0),
att_linear=0.0,
att_quad=0.0):
pass
| 2 | 0 | 13 | 0 | 13 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 6 | 1 | 1 | 14 | 0 | 14 | 14 | 6 | 0 | 8 | 8 | 6 | 1 | 1 | 0 | 1 |
7,162 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_chat/chat_openai.py
|
MAVProxy.modules.mavproxy_chat.chat_openai.EventHandler
|
class EventHandler(AssistantEventHandler):
def __init__(self, chat_openai):
# record reference to chat_openai object
self.chat_openai = chat_openai
# initialise parent class (assistant event handler)
super().__init__()
@override
def on_event(self, event):
# record run id so that it can be cancelled if required
self.chat_openai.latest_run_id = event.data.id
# display the event in the status field
event_string_array = event.event.split(".")
event_string = event_string_array[-1]
self.chat_openai.send_status(event_string)
# requires_action events handled by function calls
if event.event == 'thread.run.requires_action':
self.chat_openai.handle_function_call(event)
# display reply text in the reply window
if (event.event == "thread.message.delta"):
stream_text = event.data.delta.content[0].text.value
self.chat_openai.send_reply(stream_text)
|
class EventHandler(AssistantEventHandler):
def __init__(self, chat_openai):
pass
@override
def on_event(self, event):
pass
| 4 | 0 | 12 | 2 | 7 | 3 | 2 | 0.4 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 26 | 5 | 15 | 8 | 11 | 6 | 14 | 7 | 11 | 3 | 1 | 1 | 4 |
7,163 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_chat/chat_voice_to_text.py
|
MAVProxy.modules.mavproxy_chat.chat_voice_to_text.chat_voice_to_text
|
class chat_voice_to_text():
def __init__(self):
# initialise variables
self.client = None
self.assistant = None
# set the OpenAI API key
def set_api_key(self, api_key_str):
self.client = OpenAI(api_key=api_key_str)
# check connection to OpenAI assistant and connect if necessary
# returns True if connection is good, False if not
def check_connection(self):
# create connection object
if self.client is None:
try:
self.client = OpenAI()
except Exception:
print("chat: failed to connect to OpenAI")
return False
# return True if connected
return self.client is not None
# record audio from microphone
# returns filename of recording or None if failed
def record_audio(self):
# Initialize PyAudio
p = pyaudio.PyAudio()
# Open stream
try:
stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
except Exception:
print("chat: failed to connect to microphone")
return None
# record until specified time
frames = []
while not stop_recording[0]:
data = stream.read(1024)
frames.append(data)
# Stop and close the stream
stream.stop_stream()
stream.close()
p.terminate()
# update the recording state back to false globally
stop_recording[0] = False
# Save audio file
wf = wave.open("recording.wav", "wb")
wf.setnchannels(1)
wf.setsampwidth(pyaudio.PyAudio().get_sample_size(pyaudio.paInt16))
wf.setframerate(44100)
wf.writeframes(b''.join(frames))
wf.close()
return "recording.wav"
# convert audio to text
# returns transcribed text on success or None if failed
def convert_audio_to_text(self, audio_filename):
# check connection
if not self.check_connection():
return None
# Process with Whisper
audio_file = open(audio_filename, "rb")
transcript = self.client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
response_format="text")
return transcript
|
class chat_voice_to_text():
def __init__(self):
pass
def set_api_key(self, api_key_str):
pass
def check_connection(self):
pass
def record_audio(self):
pass
def convert_audio_to_text(self, audio_filename):
pass
| 6 | 0 | 12 | 1 | 9 | 2 | 2 | 0.4 | 0 | 1 | 0 | 0 | 5 | 2 | 5 | 5 | 74 | 11 | 45 | 15 | 39 | 18 | 42 | 15 | 36 | 3 | 0 | 2 | 10 |
7,164 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_chat/chat_window.py
|
MAVProxy.modules.mavproxy_chat.chat_window.chat_window
|
class chat_window():
def __init__(self, mpstate, wait_for_command_ack_fn):
# keep reference to mpstate
self.mpstate = mpstate
# create chat_openai object
self.chat_openai = chat_openai.chat_openai(self.mpstate, self.set_status_text, self.append_chat_replies,
wait_for_command_ack_fn)
# create chat_voice_to_text object
self.chat_voice_to_text = chat_voice_to_text.chat_voice_to_text()
# create chat window
self.app = wx.App()
self.frame = wx.Frame(None, title="Chat", size=(650, 200))
self.frame.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))
# add menu
self.menu = wx.Menu()
self.menu.Append(1, "Set API Key", "Set OpenAI API Key")
self.menu_bar = wx.MenuBar()
self.menu_bar.Append(self.menu, "Menu")
self.frame.SetMenuBar(self.menu_bar)
self.frame.Bind(wx.EVT_MENU, self.menu_set_api_key_show, id=1)
# add api key input window
self.apikey_frame = wx.Frame(None, title="Input OpenAI API Key", size=(560, 50))
self.apikey_text_input = wx.TextCtrl(self.apikey_frame, id=-1, pos=(10, 10), size=(450, -1),
style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER)
self.apikey_set_button = wx.Button(self.apikey_frame, id=-1, label="Set", pos=(470, 10), size=(75, 25))
self.apikey_frame.Bind(wx.EVT_BUTTON, self.apikey_set_button_click, self.apikey_set_button)
self.apikey_frame.Bind(wx.EVT_TEXT_ENTER, self.apikey_set_button_click, self.apikey_text_input)
self.apikey_frame.Bind(wx.EVT_CLOSE, self.apikey_close_button_click)
# add a vertical and horizontal sizers
self.vert_sizer = wx.BoxSizer(wx.VERTICAL)
self.horiz_sizer = wx.BoxSizer(wx.HORIZONTAL)
# add a read-only reply text box
self.text_reply = wx.TextCtrl(self.frame, id=-1, size=(600, 80), style=wx.TE_READONLY | wx.TE_MULTILINE | wx.TE_RICH)
# add a read-only status text box
self.text_status = wx.TextCtrl(self.frame, id=-1, size=(600, -1), style=wx.TE_READONLY)
# add a record button
self.record_button = wx.Button(self.frame, id=-1, label="Rec", size=(75, 25))
self.record_button.Bind(wx.EVT_LEFT_DOWN, self.record_button_pushed, self.record_button)
self.record_button.Bind(wx.EVT_LEFT_UP, self.record_button_released, self.record_button)
self.horiz_sizer.Add(self.record_button, proportion=0, flag=wx.ALIGN_TOP | wx.ALL, border=5)
# add an input text box
self.text_input = wx.TextCtrl(self.frame, id=-1, value="", size=(450, -1), style=wx.TE_PROCESS_ENTER)
self.frame.Bind(wx.EVT_TEXT_ENTER, self.text_input_change, self.text_input)
self.horiz_sizer.Add(self.text_input, proportion=1, flag=wx.ALIGN_TOP | wx.ALL, border=5)
# add a send button
self.send_button = wx.Button(self.frame, id=-1, label="Send", size=(75, 25))
self.frame.Bind(wx.EVT_BUTTON, self.send_button_click, self.send_button)
self.horiz_sizer.Add(self.send_button, proportion=0, flag=wx.ALIGN_TOP | wx.ALL, border=5)
# add a cancel button
self.cancel_button = wx.Button(self.frame, id=-1, label="cancel", size=(75, 25))
self.frame.Bind(wx.EVT_BUTTON, self.cancel_button_click , self.cancel_button)
self.horiz_sizer.Add(self.cancel_button, proportion=0, flag=wx.ALIGN_TOP | wx.ALL, border=5)
wx.CallAfter(self.cancel_button.Disable)
# set size hints and add sizer to frame
self.vert_sizer.Add(self.text_reply, proportion=1, flag=wx.EXPAND, border=5)
self.vert_sizer.Add(self.text_status, proportion=0, flag=wx.EXPAND, border=5)
self.vert_sizer.Add(self.horiz_sizer, proportion=0, flag=wx.EXPAND)
self.frame.SetSizer(self.vert_sizer)
# set focus on the input text box
self.text_input.SetFocus()
# show frame
self.frame.Show()
# chat window loop (this does not return until the window is closed)
self.app.MainLoop()
# show the chat window
def show(self):
wx.CallAfter(self.frame.Show())
# hide the chat window
def hide(self):
self.frame.Hide()
# close the chat window
# this is called when the module is unloaded
def close(self):
self.frame.Close()
# menu set API key handling. Shows the API key input window
def menu_set_api_key_show(self, event):
self.apikey_frame.Show()
# set API key set button clicked
def apikey_set_button_click(self, event):
self.chat_openai.set_api_key(self.apikey_text_input.GetValue())
self.chat_voice_to_text.set_api_key(self.apikey_text_input.GetValue())
self.apikey_frame.Hide()
# API key close button clicked
def apikey_close_button_click(self, event):
self.apikey_frame.Hide()
# record button clicked
def record_button_click_execute(self, event):
# record audio
self.set_status_text("recording audio")
rec_filename = self.chat_voice_to_text.record_audio()
if rec_filename is None:
self.set_status_text("audio recording failed")
return
# convert audio to text and place in input box
self.set_status_text("converting audio to text")
text = self.chat_voice_to_text.convert_audio_to_text(rec_filename)
if text is None or len(text) == 0:
self.set_status_text("audio to text conversion failed")
return
wx.CallAfter(self.text_input.SetValue, text)
# send text to assistant
self.set_status_text("sending text to assistasnt")
self.send_text_to_assistant()
# record button pushed
def record_button_pushed(self, event):
# run record_button_click_execute in a new thread
th = Thread(target=self.record_button_click_execute, args=(event,))
th.start()
# record button released
def record_button_released(self, event):
# Run when mouse click is released
# set the stop_recording status to True
chat_voice_to_text.stop_recording[0] = True
# cancel button clicked
def cancel_button_click(self, event):
self.chat_openai.cancel_run()
# send button clicked
def send_button_click(self, event):
self.text_input_change(event)
# handle text input
def text_input_change(self, event):
# protect against sending empty text
if self.text_input.GetValue() == "":
return
# send text to assistant in a separate thread
th = Thread(target=self.send_text_to_assistant)
th.start()
# send text to assistant. should be called from a separate thread to avoid blocking
def send_text_to_assistant(self):
# store current focus so it can be restored later
focus = wx.Window.FindFocus()
if focus is not None and focus == self.send_button:
# if send button has focus, override to text input
focus = self.text_input
# disable buttons and text input to stop multiple inputs (can't be done from a thread or must use CallAfter)
# enable the cancel button to cancel the current run
wx.CallAfter(self.cancel_button.Enable)
wx.CallAfter(self.record_button.Disable)
wx.CallAfter(self.text_input.Disable)
wx.CallAfter(self.send_button.Disable)
# get text from text input and clear text input
send_text = self.text_input.GetValue()
wx.CallAfter(self.text_input.Clear)
# copy user input text to reply box
wx.CallAfter(self.text_reply.SetDefaultStyle, wx.TextAttr(wx.RED))
wx.CallAfter(self.text_reply.AppendText, "\n" + send_text + "\n")
# send text to assistant. replies will be handled by append_chat_replies
self.chat_openai.send_to_assistant(send_text)
# reenable buttons and text input (can't be done from a thread or must use CallAfter)
# disable the cancel button
wx.CallAfter(self.cancel_button.Disable)
wx.CallAfter(self.record_button.Enable)
wx.CallAfter(self.text_input.Enable)
wx.CallAfter(self.send_button.Enable)
# restore focus
if focus is not None:
wx.CallAfter(focus.SetFocus)
# set status text
def set_status_text(self, text):
wx.CallAfter(self.text_status.SetValue, text)
# append chat to reply box
def append_chat_replies(self, text):
wx.CallAfter(self.text_reply.SetDefaultStyle, wx.TextAttr(wx.BLACK))
wx.CallAfter(self.text_reply.AppendText, text)
|
class chat_window():
def __init__(self, mpstate, wait_for_command_ack_fn):
pass
def show(self):
pass
def hide(self):
pass
def close(self):
pass
def menu_set_api_key_show(self, event):
pass
def apikey_set_button_click(self, event):
pass
def apikey_close_button_click(self, event):
pass
def record_button_click_execute(self, event):
pass
def record_button_pushed(self, event):
pass
def record_button_released(self, event):
pass
def cancel_button_click(self, event):
pass
def send_button_click(self, event):
pass
def text_input_change(self, event):
pass
def send_text_to_assistant(self):
pass
def set_status_text(self, text):
pass
def append_chat_replies(self, text):
pass
| 17 | 0 | 11 | 2 | 7 | 2 | 1 | 0.45 | 0 | 1 | 0 | 0 | 16 | 18 | 16 | 16 | 203 | 39 | 113 | 41 | 96 | 51 | 111 | 41 | 94 | 3 | 0 | 1 | 21 |
7,165 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_checklist.py
|
MAVProxy.modules.mavproxy_checklist.ChecklistModule
|
class ChecklistModule(mp_module.MPModule):
def __init__(self, mpstate):
super(ChecklistModule, self).__init__(mpstate, "checklist", "checklist module")
checklist_file = None
if mpstate.aircraft_dir is not None:
path = os.path.join(mpstate.aircraft_dir, "checklist.txt")
if os.path.exists(path):
checklist_file = path
self.checklist = mp_checklist.CheckUI(checklist_file=checklist_file)
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if self.checklist is None:
return
if not isinstance(self.checklist, mp_checklist.CheckUI):
return
if not self.checklist.is_alive():
self.needs_unloading = True
return
type = msg.get_type()
master = self.master
if type == 'HEARTBEAT':
'''beforeEngineList - APM booted'''
if self.mpstate.status.heartbeat_error == True:
self.checklist.set_check("Pixhawk Booted", 0)
else:
self.checklist.set_check("Pixhawk Booted", 1)
'''beforeEngineList - Flight mode MANUAL'''
if self.mpstate.status.flightmode == "MANUAL":
self.checklist.set_check("Flight mode MANUAL", 1)
else:
self.checklist.set_check("Flight mode MANUAL", 0)
if type in [ 'GPS_RAW', 'GPS_RAW_INT' ]:
'''beforeEngineList - GPS lock'''
if ((msg.fix_type >= 3 and master.mavlink10()) or
(msg.fix_type == 2 and not master.mavlink10())):
self.checklist.set_check("GPS lock", 1)
else:
self.checklist.set_check("GPS lock", 0)
'''beforeEngineList - Radio Links > 6db margin TODO: figure out how to read db levels'''
if type in ['RADIO', 'RADIO_STATUS']:
if msg.rssi < msg.noise+6 or msg.remrssi < msg.remnoise+6:
self.checklist.set_check("Radio links > 6db margin", 0)
else:
self.checklist.set_check("Radio Links > 6db margin", 0)
if type == 'HWSTATUS':
'''beforeEngineList - Avionics Battery'''
if msg.Vcc >= 4600 and msg.Vcc <= 5300:
self.checklist.set_check("Avionics Power", 1)
else:
self.checklist.set_check("Avionics Power", 0)
if type == 'POWER_STATUS':
'''beforeEngineList - Servo Power'''
if msg.Vservo >= 4900 and msg.Vservo <= 6500:
self.checklist.set_check("Servo Power", 1)
else:
self.checklist.set_check("Servo Power", 0)
'''beforeEngineList - Waypoints Loaded'''
if type == 'HEARTBEAT':
if self.module('wp').wploader.count() == 0:
self.checklist.set_check("Waypoints Loaded", 0)
else:
self.checklist.set_check("Waypoints Loaded", 1)
'''beforeTakeoffList - Compass active'''
if type == 'GPS_RAW':
if math.fabs(msg.hdg - master.field('VFR_HUD', 'heading', '-')) < 10 or math.fabs(msg.hdg - master.field('VFR_HUD', 'heading', '-')) > 355:
self.checklist.set_check("Compass active", 1)
else:
self.checklist.set_check("Compass active", 0)
'''beforeCruiseList - Airspeed > 10 m/s , Altitude > 30 m'''
if type == 'VFR_HUD':
rel_alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 1.0e-3
if rel_alt > 30:
self.checklist.set_check("Altitude > 30 m", 1)
else:
self.checklist.set_check("Altitude > 30 m", 0)
if msg.airspeed > 10 or msg.groundspeed > 10:
self.checklist.set_check("Airspeed > 10 m/s", 1)
else:
self.checklist.set_check("Airspeed > 10 m/s", 0)
'''beforeEngineList - IMU'''
if type in ['SYS_STATUS']:
sensors = { 'AS' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE,
'MAG' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_MAG,
'INS' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_ACCEL | mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_GYRO,
'AHRS' : mavutil.mavlink.MAV_SYS_STATUS_AHRS}
bits = sensors['INS']
present = ((msg.onboard_control_sensors_enabled & bits) == bits)
healthy = ((msg.onboard_control_sensors_health & bits) == bits)
if not present or not healthy:
self.checklist.set_check("IMU Check", 1)
else:
self.checklist.set_check("IMU Check", 0)
def unload(self):
'''unload module'''
if self.checklist is not None:
self.checklist.close()
self.checklist = None
|
class ChecklistModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def unload(self):
'''unload module'''
pass
| 4 | 2 | 36 | 4 | 28 | 4 | 10 | 0.14 | 1 | 2 | 1 | 0 | 3 | 2 | 3 | 41 | 110 | 13 | 85 | 15 | 81 | 12 | 70 | 15 | 66 | 24 | 2 | 2 | 29 |
7,166 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_cmdlong.py
|
MAVProxy.modules.mavproxy_cmdlong.CmdlongModule
|
class CmdlongModule(mp_module.MPModule):
def __init__(self, mpstate):
super(CmdlongModule, self).__init__(mpstate, "cmdlong", public=True)
self.add_command('setspeed', self.cmd_do_change_speed, "do_change_speed")
self.add_command('setyaw', self.cmd_condition_yaw, "condition_yaw")
self.add_command('takeoff', self.cmd_takeoff, "takeoff")
self.add_command('velocity', self.cmd_velocity, "velocity")
self.add_command('position', self.cmd_position, "position")
self.add_command('attitude', self.cmd_attitude, "attitude")
self.add_command('cammsg', self.cmd_cammsg, "cammsg")
self.add_command('cammsg_old', self.cmd_cammsg_old, "cammsg_old")
self.add_command('camctrlmsg', self.cmd_camctrlmsg, "camctrlmsg")
self.add_command('posvel', self.cmd_posvel, "posvel")
self.add_command('parachute', self.cmd_parachute, "parachute",
['<enable|disable|release>'])
self.add_command('long', self.cmd_long, "execute mavlink long command",
self.cmd_long_commands())
self.add_command('command_int', self.cmd_command_int, "execute mavlink command_int",
self.cmd_long_commands())
self.add_command('engine', self.cmd_engine, "engine")
self.add_command('pause', self.cmd_pause, "pause AUTO/GUIDED modes")
self.add_command('resume', self.cmd_resume, "resume AUTO/GUIDED modes")
def cmd_long_commands(self):
atts = dir(mavutil.mavlink)
atts = filter( lambda x : x.lower().startswith("mav_cmd"), atts)
ret = []
for att in atts:
ret.append(att)
ret.append(str(att[8:]))
return ret
def cmd_takeoff(self, args):
'''take off'''
if ( len(args) != 1):
print("Usage: takeoff ALTITUDE_IN_METERS")
return
if (len(args) == 1):
altitude = float(args[0])
print("Take Off started")
self.master.mav.command_long_send(
self.settings.target_system, # target_system
self.settings.target_component, # target_component
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, # command
0, # confirmation
0, # param1
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
altitude) # param7
def cmd_parachute(self, args):
'''parachute control'''
usage = "Usage: parachute <enable|disable|release>"
if len(args) != 1:
print(usage)
return
cmds = {
'enable' : mavutil.mavlink.PARACHUTE_ENABLE,
'disable' : mavutil.mavlink.PARACHUTE_DISABLE,
'release' : mavutil.mavlink.PARACHUTE_RELEASE
}
if not args[0] in cmds:
print(usage)
return
cmd = cmds[args[0]]
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_PARACHUTE,
0,
cmd,
0, 0, 0, 0, 0, 0)
def cmd_camctrlmsg(self, args):
'''camctrlmsg'''
print("Sent DIGICAM_CONFIGURE CMD_LONG")
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONFIGURE, # command
0, # confirmation
10, # param1
20, # param2
30, # param3
40, # param4
50, # param5
60, # param6
70) # param7
def cmd_cammsg(self, args):
'''cammsg'''
params = [0, 0, 0, 0, 1, 0, 0]
# fill in any args passed by user
for i in range(min(len(args),len(params))):
params[i] = float(args[i])
print("Sent DIGICAM_CONTROL CMD_LONG")
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL, # command
0, # confirmation
params[0], # param1
params[1], # param2
params[2], # param3
params[3], # param4
params[4], # param5
params[5], # param6
params[6]) # param7
def cmd_engine(self, args):
'''engine control'''
if len(args) < 1:
print("usage: engine <1|0>")
return
params = [0, 0, 0, 0, 0, 0, 0]
if args[0] == 'start':
args[0] = '1'
if args[0] == 'stop':
args[0] = '0'
# fill in any args passed by user
for i in range(min(len(args),len(params))):
params[i] = float(args[i])
self.master.mav.command_long_send(
self.settings.target_system, # target_system
0, # target_component
mavutil.mavlink.MAV_CMD_DO_ENGINE_CONTROL, # command
0, # confirmation
params[0], # param1
params[1], # param2
params[2], # param3
params[3], # param4
params[4], # param5
params[5], # param6
params[6]) # param7
def cmd_cammsg_old(self, args):
'''cammsg_old'''
print("Sent old DIGICAM_CONTROL")
self.master.mav.digicam_control_send(
self.settings.target_system, # target_system
0, # target_component
0, 0, 0, 0, 1, 0, 0, 0)
def cmd_do_change_speed(self, args):
'''speed value'''
if ( len(args) != 1):
print("Usage: setspeed SPEED_VALUE")
return
if (len(args) == 1):
speed = float(args[0])
print("SPEED %s" % (str(speed)))
self.master.mav.command_long_send(
self.settings.target_system, # target_system
self.settings.target_component, # target_component
mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, # command
0, # confirmation
0, # param1
speed, # param2 (Speed value)
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
def cmd_condition_yaw(self, args):
'''yaw angle angular_speed angle_mode'''
if ( len(args) != 3):
print("Usage: yaw ANGLE ANGULAR_SPEED MODE:[0 absolute / 1 relative]")
return
if (len(args) == 3):
angle = float(args[0])
angular_speed = float(args[1])
angle_mode = float(args[2])
print("ANGLE %s" % (str(angle)))
self.master.mav.command_long_send(
self.settings.target_system, # target_system
self.settings.target_component, # target_component
mavutil.mavlink.MAV_CMD_CONDITION_YAW, # command
0, # confirmation
angle, # param1 (angle value)
angular_speed, # param2 (angular speed value)
0, # param3
angle_mode, # param4 (mode: 0->absolute / 1->relative)
0, # param5
0, # param6
0) # param7
def cmd_velocity(self, args):
'''velocity x-ms y-ms z-ms'''
if (len(args) != 3):
print("Usage: velocity x y z (m/s)")
return
if (len(args) == 3):
x_mps = float(args[0])
y_mps = float(args[1])
z_mps = float(args[2])
print("x:%f, y:%f, z:%f" % (x_mps, y_mps, z_mps))
self.master.mav.set_position_target_local_ned_send(
0, # system time in milliseconds
self.settings.target_system, # target system
0, # target component
8, # coordinate frame MAV_FRAME_BODY_NED
4039, # type mask (vel only)
0, 0, 0, # position x,y,z
x_mps, y_mps, z_mps, # velocity x,y,z
0, 0, 0, # accel x,y,z
0, 0) # yaw, yaw rate
def cmd_position(self, args):
'''position x-m y-m z-m'''
if (len(args) != 3):
print("Usage: position x y z (meters)")
return
if (len(args) == 3):
x_m = float(args[0])
y_m = float(args[1])
z_m = float(args[2])
print("x:%f, y:%f, z:%f" % (x_m, y_m, z_m))
self.master.mav.set_position_target_local_ned_send(
0, # system time in milliseconds
self.settings.target_system, # target system
0, # target component
8, # coordinate frame MAV_FRAME_BODY_NED
3576, # type mask (pos only)
x_m, y_m, z_m, # position x,y,z
0, 0, 0, # velocity x,y,z
0, 0, 0, # accel x,y,z
0, 0) # yaw, yaw rate
def cmd_attitude(self, args):
'''attitude mask q0 q1 q2 q3 roll_rate pitch_rate yaw_rate thrust'''
if len(args) < 5:
print("Usage: attitude q0 q1 q2 q3 thrust")
print("q0 q1 q2 q3: [w, x, y, z] order, zero-rotation is [1, 0, 0, 0], unit-length")
print("thrust: (0~1)")
return
elif len(args) not in [5, 9]:
print("Usage: attitude mask q0 q1 q2 q3 roll_rate pitch_rate yaw_rate thrust")
print("mask : Example 7 (0b00000111): Ignore roll rate, pitch rate, yaw rate")
print("mask : Example 128 (0b10000000): Ignore attitude")
print("mask : Example 132 (0b10000100): Ignore yaw rate, Ignore attitude")
print(" : See https://mavlink.io/en/messages/common.html#ATTITUDE_TARGET_TYPEMASK")
print("q0 q1 q2 q3: [w, x, y, z] order, zero-rotation is [1, 0, 0, 0], unit-length")
print("roll_rate pitch_rate yaw_rate: in degrees per second")
print("thrust: (0~1)")
return
if len(args) == 5:
mask = 7 # ignore angular rates
q0 = float(args[0])
q1 = float(args[1])
q2 = float(args[2])
q3 = float(args[3])
thrust = float(args[4])
roll_rate = 0.0
pitch_rate = 0.0
yaw_rate = 0.0
print("q0:%.3f, q1:%.3f, q2:%.3f q3:%.3f, thrust:%.3f" % (q0, q1, q2, q3, thrust))
elif len(args) == 9:
mask = int(args[0])
q0 = float(args[1])
q1 = float(args[2])
q2 = float(args[3])
q3 = float(args[4])
roll_rate = float(args[5])
pitch_rate = float(args[6])
yaw_rate = float(args[7])
thrust = float(args[8])
print("mask:%i, q0:%.3f, q1:%.3f, q2:%.3f q3:%.3f, roll_rate:%.3f, pitch_rate:%.3f, yaw_rate:%.3f, thrust:%.3f" %
(mask, q0, q1, q2, q3, roll_rate, pitch_rate, yaw_rate, thrust))
att_target = [q0, q1, q2, q3]
self.master.mav.set_attitude_target_send(
0, # system time in milliseconds
self.settings.target_system, # target system
0, # target component
mask, # type mask
att_target, # quaternion attitude
radians(roll_rate), # body roll rate
radians(pitch_rate), # body pitch rate
radians(yaw_rate), # body yaw rate
thrust) # thrust
def cmd_posvel(self, args):
'''posvel mapclick vN vE vD'''
ignoremask = 511
latlon = None
latlon = self.mpstate.click_location
if latlon is None:
print("set latlon to zeros")
latlon = [0, 0]
else:
ignoremask = ignoremask & 504
print("found latlon", ignoremask)
vN = 0
vE = 0
vD = 0
if (len(args) == 3):
vN = float(args[0])
vE = float(args[1])
vD = float(args[2])
ignoremask = ignoremask & 455
print("ignoremask",ignoremask)
print(latlon)
self.master.mav.set_position_target_global_int_send(
0, # system time in ms
self.settings.target_system, # target system
0, # target component
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
ignoremask, # ignore
int(latlon[0] * 1e7),
int(latlon[1] * 1e7),
10,
vN, vE, vD, # velocity
0, 0, 0, # accel x,y,z
0, 0) # yaw, yaw rate
def cmd_pause(self, args):
'''pause AUTO/GUIDED modes'''
self.master.mav.command_long_send(
self.settings.target_system, # target_system
self.settings.target_component, # target_component
mavutil.mavlink.MAV_CMD_DO_PAUSE_CONTINUE, # command
0, # confirmation
0, # 0: pause, 1: continue
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
def cmd_resume(self, args):
'''resume AUTO/GUIDED modes'''
self.master.mav.command_long_send(
self.settings.target_system, # target_system
self.settings.target_component, # target_component
mavutil.mavlink.MAV_CMD_DO_PAUSE_CONTINUE, # command
0, # confirmation
1, # 0: pause, 1: continue
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
def cmd_long(self, args):
'''execute supplied command long'''
if len(args) < 1:
print("Usage: long <command> [arg1] [arg2]...")
return
command = None
if args[0].isdigit():
command = int(args[0])
else:
try:
command = getattr(mavutil.mavlink, args[0])
except AttributeError as e:
try:
command = getattr(mavutil.mavlink, "MAV_CMD_" + args[0])
except AttributeError as e:
pass
if command is None:
print("Unknown command long ({0})".format(args[0]))
return
if command == mavutil.mavlink.MAV_CMD_REQUEST_MESSAGE:
if not args[1].isdigit():
try:
args[1] = getattr(mavutil.mavlink, "MAVLINK_MSG_ID_" + args[1])
except AttributeError as e:
pass
floating_args = [ float(x) for x in args[1:] ]
while len(floating_args) < 7:
floating_args.append(float(0))
self.master.mav.command_long_send(self.settings.target_system,
self.settings.target_component,
command,
0,
*floating_args)
def cmd_command_int(self, args):
'''execute supplied command_int'''
want_args = 11
if len(args) != want_args:
print("Argument count issue: want={0} got={1}".format(want_args, len(args)))
print("Usage: command_int frame command current autocontinue param1 param2 param3 param4 x y z")
print("e.g. command_int GLOBAL_RELATIVE_ALT DO_SET_HOME 0 0 0 0 0 0 -353632120 1491659330 0")
print("e.g. command_int GLOBAL MAV_CMD_DO_SET_ROI 0 0 0 0 0 0 5000000 5000000 500")
return
frame = None
if args[0].isdigit():
frame = int(args[0])
else:
try:
# attempt to allow MAV_FRAME_GLOBAL for frame
frame = getattr(mavutil.mavlink, args[0])
except AttributeError as e:
try:
# attempt to allow GLOBAL for frame
frame = getattr(mavutil.mavlink, "MAV_FRAME_" + args[0])
except AttributeError as e:
pass
if frame is None:
print("Unknown frame ({0})".format(args[0]))
return
command = None
if args[1].isdigit():
command = int(args[1])
else:
# let "command_int ... MAV_CMD_DO_SET_HOME ..." work
try:
command = getattr(mavutil.mavlink, args[1])
except AttributeError as e:
try:
# let "command_int ... DO_SET_HOME" work
command = getattr(mavutil.mavlink, "MAV_CMD_" + args[1])
except AttributeError as e:
pass
current = int(args[2])
autocontinue = int(args[3])
param1 = float(args[4])
param2 = float(args[5])
param3 = float(args[6])
param4 = float(args[7])
x = int(args[8])
y = int(args[9])
z = float(args[10])
self.master.mav.command_int_send(self.settings.target_system,
self.settings.target_component,
frame,
command,
0,
0,
param1,
param2,
param3,
param4,
x,
y,
z)
|
class CmdlongModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_long_commands(self):
pass
def cmd_takeoff(self, args):
'''take off'''
pass
def cmd_parachute(self, args):
'''parachute control'''
pass
def cmd_camctrlmsg(self, args):
'''camctrlmsg'''
pass
def cmd_cammsg(self, args):
'''cammsg'''
pass
def cmd_engine(self, args):
'''engine control'''
pass
def cmd_cammsg_old(self, args):
'''cammsg_old'''
pass
def cmd_do_change_speed(self, args):
'''speed value'''
pass
def cmd_condition_yaw(self, args):
'''yaw angle angular_speed angle_mode'''
pass
def cmd_velocity(self, args):
'''velocity x-ms y-ms z-ms'''
pass
def cmd_position(self, args):
'''position x-m y-m z-m'''
pass
def cmd_attitude(self, args):
'''attitude mask q0 q1 q2 q3 roll_rate pitch_rate yaw_rate thrust'''
pass
def cmd_posvel(self, args):
'''posvel mapclick vN vE vD'''
pass
def cmd_pause(self, args):
'''pause AUTO/GUIDED modes'''
pass
def cmd_resume(self, args):
'''resume AUTO/GUIDED modes'''
pass
def cmd_long_commands(self):
'''execute supplied command long'''
pass
def cmd_command_int(self, args):
'''execute supplied command_int'''
pass
| 19 | 16 | 25 | 1 | 22 | 8 | 3 | 0.37 | 1 | 7 | 0 | 0 | 18 | 0 | 18 | 56 | 467 | 42 | 403 | 69 | 384 | 150 | 238 | 69 | 219 | 10 | 2 | 3 | 59 |
7,167 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_console.py
|
MAVProxy.modules.mavproxy_console.ConsoleModule
|
class ConsoleModule(mp_module.MPModule):
def __init__(self, mpstate):
super(ConsoleModule, self).__init__(mpstate, "console", "GUI console", public=True, multi_vehicle=True)
self.in_air = False
self.start_time = 0.0
self.total_time = 0.0
self.speed = 0
self.max_link_num = 0
self.last_sys_status_health = 0
self.last_sys_status_errors_announce = 0
self.user_added = {}
self.safety_on = False
self.unload_check_interval = 5 # seconds
self.last_unload_check_time = time.time()
self.add_command('console', self.cmd_console, "console module", ['add','list','remove'])
mpstate.console = wxconsole.MessageConsole(title='Console')
# setup some default status information
mpstate.console.set_status('Mode', 'UNKNOWN', row=0, fg='blue')
mpstate.console.set_status('SysID', '', row=0, fg='blue')
mpstate.console.set_status('ARM', 'ARM', fg='grey', row=0)
mpstate.console.set_status('GPS', 'GPS: --', fg='red', row=0)
mpstate.console.set_status('GPS2', '', fg='red', row=0)
mpstate.console.set_status('Vcc', 'Vcc: --', fg='red', row=0)
mpstate.console.set_status('Radio', 'Radio: --', row=0)
mpstate.console.set_status('INS', 'INS', fg='grey', row=0)
mpstate.console.set_status('MAG', 'MAG', fg='grey', row=0)
mpstate.console.set_status('AS', 'AS', fg='grey', row=0)
mpstate.console.set_status('RNG', 'RNG', fg='grey', row=0)
mpstate.console.set_status('AHRS', 'AHRS', fg='grey', row=0)
mpstate.console.set_status('EKF', 'EKF', fg='grey', row=0)
mpstate.console.set_status('LOG', 'LOG', fg='grey', row=0)
mpstate.console.set_status('Heading', 'Hdg ---/---', row=2)
mpstate.console.set_status('Alt', 'Alt ---', row=2)
mpstate.console.set_status('AGL', 'AGL ---/---', row=2)
mpstate.console.set_status('AirSpeed', 'AirSpeed --', row=2)
mpstate.console.set_status('GPSSpeed', 'GPSSpeed --', row=2)
mpstate.console.set_status('Thr', 'Thr ---', row=2)
mpstate.console.set_status('Roll', 'Roll ---', row=2)
mpstate.console.set_status('Pitch', 'Pitch ---', row=2)
mpstate.console.set_status('Wind', 'Wind ---/---', row=2)
mpstate.console.set_status('WP', 'WP --', row=3)
mpstate.console.set_status('WPDist', 'Distance ---', row=3)
mpstate.console.set_status('WPBearing', 'Bearing ---', row=3)
mpstate.console.set_status('AltError', 'AltError --', row=3)
mpstate.console.set_status('AspdError', 'AspdError --', row=3)
mpstate.console.set_status('FlightTime', 'FlightTime --', row=3)
mpstate.console.set_status('ETR', 'ETR --', row=3)
mpstate.console.set_status('Params', 'Param ---/---', row=3)
mpstate.console.set_status('Mission', 'Mission --/--', row=3)
self.console_settings = mp_settings.MPSettings([
('debug_level', int, 0),
])
self.vehicle_list = []
self.vehicle_heartbeats = {} # map from (sysid,compid) tuple to most recent HEARTBEAT nessage
self.vehicle_menu = None
self.vehicle_name_by_sysid = {}
self.component_name = {}
self.last_param_sysid_timestamp = None
# create the main menu
if mp_util.has_wxpython:
self.menu = MPMenuTop([])
self.add_menu(MPMenuSubMenu('MAVProxy',
items=[MPMenuItem('Settings', 'Settings', 'menuSettings'),
MPMenuItem('Show Map', 'Load Map', '# module load map'),
MPMenuItem('Show HUD', 'Load HUD', '# module load horizon'),
MPMenuItem('Show Checklist', 'Load Checklist', '# module load checklist')]))
self.vehicle_menu = MPMenuSubMenu('Vehicle', items=[])
self.add_menu(self.vehicle_menu)
self.shown_agl = False
def cmd_console(self, args):
usage = 'usage: console <add|list|remove|menu|set>'
if len(args) < 1:
print(usage)
return
cmd = args[0]
if cmd == 'add':
if len(args) < 4:
print("usage: console add ID FORMAT EXPRESSION <row>")
return
if len(args) > 4:
row = int(args[4])
else:
row = 4
self.user_added[args[1]] = DisplayItem(args[2], args[3], row)
self.console.set_status(args[1], "", row=row)
elif cmd == 'list':
for k in sorted(self.user_added.keys()):
d = self.user_added[k]
print("%s : FMT=%s EXPR=%s ROW=%u" % (k, d.format, d.expression, d.row))
elif cmd == 'remove':
if len(args) < 2:
print("usage: console remove ID")
return
id = args[1]
if id in self.user_added:
self.user_added.pop(id)
elif cmd == 'menu':
self.cmd_menu(args[1:])
elif cmd == 'set':
self.cmd_set(args[1:])
else:
print(usage)
def add_menu(self, menu):
'''add a new menu'''
self.menu.add(menu)
self.mpstate.console.set_menu(self.menu, self.menu_callback)
def cmd_menu_add(self, args):
'''add to console menus'''
if len(args) < 2:
print("Usage: console menu add MenuPath command")
return
menupath = args[0].strip('"').split(':')
name = menupath[-1]
cmd = '# ' + ' '.join(args[1:])
self.menu.add_to_submenu(menupath[:-1], MPMenuItem(name, name, cmd))
self.mpstate.console.set_menu(self.menu, self.menu_callback)
def cmd_menu(self, args):
'''control console menus'''
if len(args) < 2:
print("Usage: console menu <add>")
return
if args[0] == 'add':
self.cmd_menu_add(args[1:])
def cmd_set(self, args):
'''set console options'''
self.console_settings.command(args)
def remove_menu(self, menu):
'''add a new menu'''
self.menu.remove(menu)
self.mpstate.console.set_menu(self.menu, self.menu_callback)
def unload(self):
'''unload module'''
self.mpstate.console.close()
self.mpstate.console = textconsole.SimpleConsole()
def menu_callback(self, m):
'''called on menu selection'''
if m.returnkey.startswith('# '):
cmd = m.returnkey[2:]
if m.handler is not None:
if m.handler_result is None:
return
cmd += m.handler_result
self.mpstate.functions.process_stdin(cmd)
if m.returnkey == 'menuSettings':
wxsettings.WXSettings(self.settings)
def estimated_time_remaining(self, lat, lon, wpnum, speed):
'''estimate time remaining in mission in seconds'''
if self.module('wp') is None:
return 0
idx = wpnum
if wpnum >= self.module('wp').wploader.count():
return 0
distance = 0
done = set()
while idx < self.module('wp').wploader.count():
if idx in done:
break
done.add(idx)
w = self.module('wp').wploader.wp(idx)
if w.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
idx = int(w.param1)
continue
idx += 1
if (w.x != 0 or w.y != 0) and w.command in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM,
mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,
mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,
mavutil.mavlink.MAV_CMD_NAV_LAND,
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF]:
distance += mp_util.gps_distance(lat, lon, w.x, w.y)
lat = w.x
lon = w.y
if w.command == mavutil.mavlink.MAV_CMD_NAV_LAND:
break
return distance / speed
def vehicle_type_string(self, hb):
'''return vehicle type string from a heartbeat'''
if hb.type in [mavutil.mavlink.MAV_TYPE_FIXED_WING,
mavutil.mavlink.MAV_TYPE_VTOL_DUOROTOR,
mavutil.mavlink.MAV_TYPE_VTOL_QUADROTOR,
mavutil.mavlink.MAV_TYPE_VTOL_TILTROTOR]:
return 'Plane'
if hb.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER:
return 'Rover'
if hb.type == mavutil.mavlink.MAV_TYPE_SURFACE_BOAT:
return 'Boat'
if hb.type == mavutil.mavlink.MAV_TYPE_SUBMARINE:
return 'Sub'
if hb.type in [mavutil.mavlink.MAV_TYPE_QUADROTOR,
mavutil.mavlink.MAV_TYPE_COAXIAL,
mavutil.mavlink.MAV_TYPE_HEXAROTOR,
mavutil.mavlink.MAV_TYPE_OCTOROTOR,
mavutil.mavlink.MAV_TYPE_TRICOPTER,
mavutil.mavlink.MAV_TYPE_DODECAROTOR]:
return "Copter"
if hb.type == mavutil.mavlink.MAV_TYPE_HELICOPTER:
return "Heli"
if hb.type == mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER:
return "Tracker"
if hb.type == mavutil.mavlink.MAV_TYPE_AIRSHIP:
return "Blimp"
elif hb.type == mavutil.mavlink.MAV_TYPE_ADSB:
return "ADSB"
elif hb.type == mavutil.mavlink.MAV_TYPE_ODID:
return "ODID"
return "UNKNOWN(%u)" % hb.type
def component_type_string(self, hb):
# note that we rely on vehicle_type_string for basic vehicle types
if hb.type == mavutil.mavlink.MAV_TYPE_GCS:
return "GCS"
elif hb.type == mavutil.mavlink.MAV_TYPE_GIMBAL:
return "Gimbal"
elif hb.type == mavutil.mavlink.MAV_TYPE_ONBOARD_CONTROLLER:
return "CC"
elif hb.type == mavutil.mavlink.MAV_TYPE_ADSB:
return "ADSB"
elif hb.type == mavutil.mavlink.MAV_TYPE_ODID:
return "ODID"
elif hb.type == mavutil.mavlink.MAV_TYPE_GENERIC:
return "Generic"
return self.vehicle_type_string(hb)
def update_vehicle_menu(self):
'''update menu for new vehicles'''
self.vehicle_menu.items = []
for s in sorted(self.vehicle_list):
clist = self.module('param').get_component_id_list(s)
if len(clist) == 1:
name = 'SysID %u: %s' % (s, self.vehicle_name_by_sysid[s])
self.vehicle_menu.items.append(MPMenuItem(name, name, '# vehicle %u' % s))
else:
for c in sorted(clist):
try:
name = 'SysID %u[%u]: %s' % (s, c, self.component_name[s][c])
except KeyError as e:
name = 'SysID %u[%u]: ?' % (s,c)
self.vehicle_menu.items.append(MPMenuItem(name, name, '# vehicle %u:%u' % (s,c)))
self.mpstate.console.set_menu(self.menu, self.menu_callback)
def add_new_vehicle(self, hb):
'''add a new vehicle'''
if hb.type == mavutil.mavlink.MAV_TYPE_GCS:
return
sysid = hb.get_srcSystem()
self.vehicle_list.append(sysid)
self.vehicle_name_by_sysid[sysid] = self.vehicle_type_string(hb)
self.update_vehicle_menu()
def check_critical_error(self, msg):
'''check for any error bits being set in SYS_STATUS'''
sysid = msg.get_srcSystem()
compid = msg.get_srcComponent()
hb = self.vehicle_heartbeats.get((sysid, compid), None)
if hb is None:
return
# only ArduPilot populates the fields with internal error stuff:
if hb.autopilot != mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA:
return
errors = msg.errors_count1 | (msg.errors_count2<<16)
if errors == 0:
return
now = time.time()
if now - self.last_sys_status_errors_announce > self.mpstate.settings.sys_status_error_warn_interval:
self.last_sys_status_errors_announce = now
self.say("Critical failure 0x%x sysid=%u compid=%u" % (errors, sysid, compid))
def set_component_name(self, sysid, compid, name):
if sysid not in self.component_name:
self.component_name[sysid] = {}
if compid not in self.component_name[sysid]:
self.component_name[sysid][compid] = name
self.update_vehicle_menu()
# this method is called when a HEARTBEAT arrives from any source:
def handle_heartbeat_anysource(self, msg):
sysid = msg.get_srcSystem()
compid = msg.get_srcComponent()
type = msg.get_type()
if type == 'HEARTBEAT':
self.vehicle_heartbeats[(sysid, compid)] = msg
if not sysid in self.vehicle_list:
self.add_new_vehicle(msg)
self.set_component_name(sysid, compid, self.component_type_string(msg))
# this method is called when a GIMBAL_DEVICE_INFORMATION arrives
# from any source:
def handle_gimbal_device_information_anysource(self, msg):
sysid = msg.get_srcSystem()
compid = msg.get_srcComponent()
self.set_component_name(sysid, compid, "%s-%s" %
(msg.vendor_name, msg.model_name))
def handle_radio_status(self, msg):
# handle RADIO msgs from all vehicles
if msg.rssi < msg.noise+10 or msg.remrssi < msg.remnoise+10:
fg = 'red'
else:
fg = 'black'
self.console.set_status('Radio', 'Radio %u/%u %u/%u' % (msg.rssi, msg.noise, msg.remrssi, msg.remnoise), fg=fg)
def handle_gps_raw(self, msg):
master = self.master
type = msg.get_type()
if type == 'GPS_RAW_INT':
field = 'GPS'
prefix = 'GPS:'
else:
field = 'GPS2'
prefix = 'GPS2'
nsats = msg.satellites_visible
fix_type = msg.fix_type
if fix_type >= 3:
self.console.set_status(field, '%s OK%s (%u)' % (prefix, fix_type, nsats), fg=green)
else:
self.console.set_status(field, '%s %u (%u)' % (prefix, fix_type, nsats), fg='red')
if type == 'GPS_RAW_INT':
vfr_hud_heading = master.field('VFR_HUD', 'heading', None)
if vfr_hud_heading is None:
# try to fill it in from GLOBAL_POSITION_INT instead:
vfr_hud_heading = master.field('GLOBAL_POSITION_INT', 'hdg', None)
if vfr_hud_heading is not None:
if vfr_hud_heading == 65535: # mavlink magic "unknown" value
vfr_hud_heading = None
else:
vfr_hud_heading /= 100
gps_heading = int(msg.cog * 0.01)
if vfr_hud_heading is None:
vfr_hud_heading = '---'
else:
vfr_hud_heading = '%3u' % vfr_hud_heading
self.console.set_status('Heading', 'Hdg %s/%3u' %
(vfr_hud_heading, gps_heading))
def handle_vfr_hud(self, msg):
master = self.master
if master.mavlink10():
alt = master.field('GPS_RAW_INT', 'alt', 0) / 1.0e3
else:
alt = master.field('GPS_RAW', 'alt', 0)
home_lat = None
home_lng = None
if self.module('wp') is not None:
home = self.module('wp').get_home()
if home is not None:
home_lat = home.x
home_lng = home.y
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1.0e-7
lng = master.field('GLOBAL_POSITION_INT', 'lon', 0) * 1.0e-7
rel_alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 1.0e-3
agl_alt = None
if self.module('terrain') is not None:
elevation_model = self.module('terrain').ElevationModel
if self.settings.basealt != 0:
agl_alt = elevation_model.GetElevation(lat, lng)
if agl_alt is not None:
agl_alt = self.settings.basealt - agl_alt
else:
try:
agl_alt_home = elevation_model.GetElevation(home_lat, home_lng)
except Exception as ex:
print(ex)
agl_alt_home = None
if agl_alt_home is not None:
agl_alt = elevation_model.GetElevation(lat, lng)
if agl_alt is not None:
agl_alt = agl_alt_home - agl_alt
vehicle_agl = master.field('TERRAIN_REPORT', 'current_height', None)
if agl_alt is not None or vehicle_agl is not None or self.shown_agl:
self.shown_agl = True
if agl_alt is not None:
agl_alt += rel_alt
agl_alt = self.height_string(agl_alt)
else:
agl_alt = "---"
if vehicle_agl is None:
vehicle_agl = '---'
else:
vehicle_agl = self.height_string(vehicle_agl)
self.console.set_status('AGL', 'AGL %s/%s' % (agl_alt, vehicle_agl))
self.console.set_status('Alt', 'Alt %s' % self.height_string(rel_alt))
self.console.set_status('AirSpeed', 'AirSpeed %s' % self.speed_string(msg.airspeed))
self.console.set_status('GPSSpeed', 'GPSSpeed %s' % self.speed_string(msg.groundspeed))
self.console.set_status('Thr', 'Thr %u' % msg.throttle)
t = time.localtime(msg._timestamp)
flying = False
if self.mpstate.vehicle_type == 'copter':
flying = self.master.motors_armed()
else:
flying = msg.groundspeed > 3
if flying and not self.in_air:
self.in_air = True
self.start_time = time.mktime(t)
elif flying and self.in_air:
self.total_time = time.mktime(t) - self.start_time
self.console.set_status('FlightTime', 'FlightTime %u:%02u' % (int(self.total_time)/60, int(self.total_time)%60))
elif not flying and self.in_air:
self.in_air = False
self.total_time = time.mktime(t) - self.start_time
self.console.set_status('FlightTime', 'FlightTime %u:%02u' % (int(self.total_time)/60, int(self.total_time)%60))
def handle_attitude(self, msg):
self.console.set_status('Roll', 'Roll %u' % math.degrees(msg.roll))
self.console.set_status('Pitch', 'Pitch %u' % math.degrees(msg.pitch))
def handle_sys_status(self, msg):
master = self.master
sensors = { 'AS' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE,
'MAG' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_MAG,
'INS' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_ACCEL | mavutil.mavlink.MAV_SYS_STATUS_SENSOR_3D_GYRO,
'AHRS' : mavutil.mavlink.MAV_SYS_STATUS_AHRS,
'RC' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_RC_RECEIVER,
'TERR' : mavutil.mavlink.MAV_SYS_STATUS_TERRAIN,
'RNG' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION,
'LOG' : mavutil.mavlink.MAV_SYS_STATUS_LOGGING,
'PRX' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_PROXIMITY,
'PRE' : mavutil.mavlink.MAV_SYS_STATUS_PREARM_CHECK,
'FLO' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW,
}
hide_if_not_present = set(['PRE', 'PRX', 'FLO'])
for s in sensors.keys():
bits = sensors[s]
present = ((msg.onboard_control_sensors_present & bits) == bits)
enabled = ((msg.onboard_control_sensors_enabled & bits) == bits)
healthy = ((msg.onboard_control_sensors_health & bits) == bits)
if not present and s in hide_if_not_present:
continue
if not present:
fg = 'black'
elif not enabled:
fg = 'grey'
elif not healthy:
fg = 'red'
else:
fg = green
# for terrain show yellow if still loading
if s == 'TERR' and fg == green and master.field('TERRAIN_REPORT', 'pending', 0) != 0:
fg = 'yellow'
self.console.set_status(s, s, fg=fg)
announce_unhealthy = {
'RC': 'RC',
'PRE': 'pre-arm',
}
for s in announce_unhealthy.keys():
bits = sensors[s]
enabled = ((msg.onboard_control_sensors_enabled & bits) == bits)
healthy = ((msg.onboard_control_sensors_health & bits) == bits)
was_healthy = ((self.last_sys_status_health & bits) == bits)
if enabled and not healthy and was_healthy:
self.say("%s fail" % announce_unhealthy[s])
announce_healthy = {
'PRE': 'pre-arm',
}
for s in announce_healthy.keys():
bits = sensors[s]
enabled = ((msg.onboard_control_sensors_enabled & bits) == bits)
healthy = ((msg.onboard_control_sensors_health & bits) == bits)
was_healthy = ((self.last_sys_status_health & bits) == bits)
if enabled and healthy and not was_healthy:
self.say("%s good" % announce_healthy[s])
self.last_sys_status_health = msg.onboard_control_sensors_health
if ((msg.onboard_control_sensors_enabled & mavutil.mavlink.MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS) == 0):
self.safety_on = True
else:
self.safety_on = False
def handle_wind(self, msg):
self.console.set_status('Wind', 'Wind %u/%s' % (msg.direction, self.speed_string(msg.speed)))
def handle_ekf_status_report(self, msg):
highest = 0.0
vars = ['velocity_variance',
'pos_horiz_variance',
'pos_vert_variance',
'compass_variance',
'terrain_alt_variance']
for var in vars:
v = getattr(msg, var, 0)
highest = max(v, highest)
if highest >= 1.0:
fg = 'red'
elif highest >= 0.5:
fg = 'orange'
else:
fg = green
self.console.set_status('EKF', 'EKF', fg=fg)
def handle_power_status(self, msg):
if msg.Vcc >= 4600 and msg.Vcc <= 5300:
fg = green
else:
fg = 'red'
self.console.set_status('Vcc', 'Vcc %.2f' % (msg.Vcc * 0.001), fg=fg)
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_CHANGED:
fg = 'red'
else:
fg = green
status = 'PWR:'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_USB_CONNECTED:
status += 'U'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_BRICK_VALID:
status += 'B'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_SERVO_VALID:
status += 'S'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_PERIPH_OVERCURRENT:
status += 'O1'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_PERIPH_HIPOWER_OVERCURRENT:
status += 'O2'
self.console.set_status('PWR', status, fg=fg)
self.console.set_status('Srv', 'Srv %.2f' % (msg.Vservo*0.001), fg=green)
# this method is called on receipt of any HEARTBEAT so long as it
# comes from the device we are interested in
def handle_heartbeat(self, msg):
sysid = msg.get_srcSystem()
compid = msg.get_srcComponent()
master = self.master
fmode = master.flightmode
if self.settings.vehicle_name:
fmode = self.settings.vehicle_name + ':' + fmode
self.console.set_status('Mode', '%s' % fmode, fg='blue')
if len(self.vehicle_list) > 1:
self.console.set_status('SysID', 'Sys:%u' % sysid, fg='blue')
if self.master.motors_armed():
arm_colour = green
else:
arm_colour = 'red'
armstring = 'ARM'
# add safety switch state
if self.safety_on:
armstring += '(SAFE)'
self.console.set_status('ARM', armstring, fg=arm_colour)
if self.max_link_num != len(self.mpstate.mav_master):
for i in range(self.max_link_num):
self.console.set_status('Link%u'%(i+1), '', row=1)
self.max_link_num = len(self.mpstate.mav_master)
for m in self.mpstate.mav_master:
if self.mpstate.settings.checkdelay:
highest_msec_key = (sysid, compid)
linkdelay = (self.mpstate.status.highest_msec.get(highest_msec_key, 0) - m.highest_msec.get(highest_msec_key,0))*1.0e-3
else:
linkdelay = 0
linkline = "Link %s " % (self.link_label(m))
fg = 'dark green'
if m.linkerror:
linkline += "down"
fg = 'red'
else:
packets_rcvd_percentage = 100
if (m.mav_count+m.mav_loss) != 0: #avoid divide-by-zero
packets_rcvd_percentage = (100.0 * m.mav_count) / (m.mav_count + m.mav_loss)
linkbits = ["%u pkts" % m.mav_count,
"%u lost" % m.mav_loss,
"%.2fs delay" % linkdelay,
]
try:
if m.mav.signing.sig_count:
# other end is sending us signed packets
if not m.mav.signing.secret_key:
# we've received signed packets but
# can't verify them
fg = 'orange'
linkbits.append("!KEY")
elif not m.mav.signing.sign_outgoing:
# we've received signed packets but aren't
# signing outselves; this can lead to hairloss
fg = 'orange'
linkbits.append("!SIGNING")
if m.mav.signing.badsig_count:
fg = 'orange'
linkbits.append("%u badsigs" % m.mav.signing.badsig_count)
except AttributeError as e:
# mav.signing.sig_count probably doesn't exist
pass
linkline += "OK {rcv_pct:.1f}% ({bits})".format(
rcv_pct=packets_rcvd_percentage,
bits=", ".join(linkbits))
if linkdelay > 1 and fg == 'dark green':
fg = 'orange'
self.console.set_status('Link%u'%m.linknum, linkline, row=1, fg=fg)
def handle_mission_current(self, msg):
master = self.master
if self.module('wp') is not None:
wpmax = self.module('wp').wploader.count()
else:
wpmax = 0
if wpmax > 0:
wpmax = "/%u" % wpmax
else:
wpmax = ""
self.console.set_status('WP', 'WP %u%s' % (msg.seq, wpmax))
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1.0e-7
lng = master.field('GLOBAL_POSITION_INT', 'lon', 0) * 1.0e-7
if lat != 0 and lng != 0:
airspeed = master.field('VFR_HUD', 'airspeed', 30)
if abs(airspeed - self.speed) > 5:
self.speed = airspeed
else:
self.speed = 0.98*self.speed + 0.02*airspeed
self.speed = max(1, self.speed)
time_remaining = int(self.estimated_time_remaining(lat, lng, msg.seq, self.speed))
self.console.set_status('ETR', 'ETR %u:%02u' % (time_remaining/60, time_remaining%60))
def handle_nav_controller_output(self, msg):
self.console.set_status('WPDist', 'Distance %s' % self.dist_string(msg.wp_dist))
self.console.set_status('WPBearing', 'Bearing %u' % msg.target_bearing)
if msg.alt_error > 0:
alt_error_sign = "(L)"
else:
alt_error_sign = "(H)"
if msg.aspd_error > 0:
aspd_error_sign = "(L)"
else:
aspd_error_sign = "(H)"
if math.isnan(msg.alt_error):
alt_error = "NaN"
else:
alt_error = "%s%s" % (self.height_string(msg.alt_error), alt_error_sign)
self.console.set_status('AltError', 'AltError %s' % alt_error)
self.console.set_status('AspdError', 'AspdError %s%s' % (self.speed_string(msg.aspd_error*0.01), aspd_error_sign))
def handle_param_value(self, msg):
rec, tot = self.module('param').param_status()
self.console.set_status('Params', 'Param %u/%u' % (rec,tot))
def handle_high_latency2(self, msg):
self.console.set_status('WPDist', 'Distance %s' % self.dist_string(msg.target_distance * 10))
# The -180 here for for consistency with NAV_CONTROLLER_OUTPUT (-180->180), whereas HIGH_LATENCY2 is (0->360)
self.console.set_status('WPBearing', 'Bearing %u' % ((msg.target_heading * 2) - 180))
alt_error = "%s%s" % (self.height_string(msg.target_altitude - msg.altitude),
"(L)" if (msg.target_altitude - msg.altitude) > 0 else "(L)")
self.console.set_status('AltError', 'AltError %s' % alt_error)
self.console.set_status('AspdError', 'AspdError %s%s' % (self.speed_string((msg.airspeed_sp - msg.airspeed)/5),
"(L)" if (msg.airspeed_sp - msg.airspeed) > 0 else "(L)"))
# The -180 here for for consistency with WIND (-180->180), whereas HIGH_LATENCY2 is (0->360)
self.console.set_status('Wind', 'Wind %u/%s' % ((msg.wind_heading * 2) - 180, self.speed_string(msg.windspeed / 5)))
self.console.set_status('Alt', 'Alt %s' % self.height_string(msg.altitude - self.module('terrain').ElevationModel.GetElevation(msg.latitude / 1E7, msg.longitude / 1E7)))
self.console.set_status('AirSpeed', 'AirSpeed %s' % self.speed_string(msg.airspeed / 5))
self.console.set_status('GPSSpeed', 'GPSSpeed %s' % self.speed_string(msg.groundspeed / 5))
self.console.set_status('Thr', 'Thr %u' % msg.throttle)
self.console.set_status('Heading', 'Hdg %s/---' % (msg.heading * 2))
self.console.set_status('WP', 'WP %u/--' % (msg.wp_num))
#re-map sensors
sensors = { 'AS' : mavutil.mavlink.HL_FAILURE_FLAG_DIFFERENTIAL_PRESSURE,
'MAG' : mavutil.mavlink.HL_FAILURE_FLAG_3D_MAG,
'INS' : mavutil.mavlink.HL_FAILURE_FLAG_3D_ACCEL | mavutil.mavlink.HL_FAILURE_FLAG_3D_GYRO,
'AHRS' : mavutil.mavlink.HL_FAILURE_FLAG_ESTIMATOR,
'RC' : mavutil.mavlink.HL_FAILURE_FLAG_RC_RECEIVER,
'TERR' : mavutil.mavlink.HL_FAILURE_FLAG_TERRAIN
}
for s in sensors.keys():
bits = sensors[s]
failed = ((msg.failure_flags & bits) == bits)
if failed:
fg = 'red'
else:
fg = green
self.console.set_status(s, s, fg=fg)
# do the remaining non-standard system mappings
fence_failed = ((msg.failure_flags & mavutil.mavlink.HL_FAILURE_FLAG_GEOFENCE) == mavutil.mavlink.HL_FAILURE_FLAG_GEOFENCE)
if fence_failed:
fg = 'red'
else:
fg = green
self.console.set_status('Fence', 'FEN', fg=fg)
gps_failed = ((msg.failure_flags & mavutil.mavlink.HL_FAILURE_FLAG_GPS) == mavutil.mavlink.HL_FAILURE_FLAG_GPS)
if gps_failed:
self.console.set_status('GPS', 'GPS FAILED', fg='red')
else:
self.console.set_status('GPS', 'GPS OK', fg=green)
batt_failed = ((msg.failure_flags & mavutil.mavlink.HL_FAILURE_FLAG_GPS) == mavutil.mavlink.HL_FAILURE_FLAG_BATTERY)
if batt_failed:
self.console.set_status('PWR', 'PWR FAILED', fg='red')
else:
self.console.set_status('PWR', 'PWR OK', fg=green)
# update user-added console entries; called after a mavlink packet
# is received:
def update_user_added_keys(self, msg):
type = msg.get_type()
for id in self.user_added.keys():
if type in self.user_added[id].msg_types:
d = self.user_added[id]
try:
val = mavutil.evaluate_expression(d.expression, self.master.messages)
console_string = d.format % val
except Exception as ex:
console_string = "????"
self.console.set_status(id, console_string, row = d.row)
if self.console_settings.debug_level > 0:
exc_type, exc_value, exc_traceback = sys.exc_info()
if self.mpstate.settings.moddebug > 3:
traceback.print_exception(
exc_type,
exc_value,
exc_traceback,
file=sys.stdout
)
elif self.mpstate.settings.moddebug > 1:
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
elif self.mpstate.settings.moddebug == 1:
print(ex)
print(f"{id} failed")
self.console.set_status(id, console_string, row = d.row)
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if not isinstance(self.console, wxconsole.MessageConsole):
return
if not self.console.is_alive():
self.mpstate.console = textconsole.SimpleConsole()
return
type = msg.get_type()
if type in frozenset(['HEARTBEAT', 'HIGH_LATENCY2']):
self.handle_heartbeat_anysource(msg)
elif type == 'GIMBAL_DEVICE_INFORMATION':
self.handle_gimbal_device_information_anysource(msg)
if self.last_param_sysid_timestamp != self.module('param').new_sysid_timestamp:
'''a new component ID has appeared for parameters'''
self.last_param_sysid_timestamp = self.module('param').new_sysid_timestamp
self.update_vehicle_menu()
if type in ['RADIO', 'RADIO_STATUS']:
self.handle_radio_status(msg)
if type == 'SYS_STATUS':
self.check_critical_error(msg)
if not self.message_is_from_primary_vehicle(msg):
# don't process msgs from other than primary vehicle, other than
# updating vehicle list
return
# add some status fields
if type in [ 'GPS_RAW_INT', 'GPS2_RAW' ]:
self.handle_gps_raw(msg)
elif type == 'VFR_HUD':
self.handle_vfr_hud(msg)
elif type == 'ATTITUDE':
self.handle_attitude(msg)
elif type in ['SYS_STATUS']:
self.handle_sys_status(msg)
elif type == 'WIND':
self.handle_wind(msg)
elif type == 'EKF_STATUS_REPORT':
self.handle_ekf_status_report(msg)
elif type == 'POWER_STATUS':
self.handle_power_status(msg)
elif type in ['HEARTBEAT', 'HIGH_LATENCY2']:
self.handle_heartbeat(msg)
elif type in ['MISSION_CURRENT']:
self.handle_mission_current(msg)
elif type == 'NAV_CONTROLLER_OUTPUT':
self.handle_nav_controller_output(msg)
elif type == 'PARAM_VALUE':
self.handle_param_value(msg)
if type == 'HIGH_LATENCY2':
self.handle_high_latency2(msg)
self.update_user_added_keys(msg)
def idle_task(self):
now = time.time()
if self.last_unload_check_time + self.unload_check_interval < now:
self.last_unload_check_time = now
if not self.console.is_alive():
self.needs_unloading = True
|
class ConsoleModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_console(self, args):
pass
def add_menu(self, menu):
'''add a new menu'''
pass
def cmd_menu_add(self, args):
'''add to console menus'''
pass
def cmd_menu_add(self, args):
'''control console menus'''
pass
def cmd_set(self, args):
'''set console options'''
pass
def remove_menu(self, menu):
'''add a new menu'''
pass
def unload(self):
'''unload module'''
pass
def menu_callback(self, m):
'''called on menu selection'''
pass
def estimated_time_remaining(self, lat, lon, wpnum, speed):
'''estimate time remaining in mission in seconds'''
pass
def vehicle_type_string(self, hb):
'''return vehicle type string from a heartbeat'''
pass
def component_type_string(self, hb):
pass
def update_vehicle_menu(self):
'''update menu for new vehicles'''
pass
def add_new_vehicle(self, hb):
'''add a new vehicle'''
pass
def check_critical_error(self, msg):
'''check for any error bits being set in SYS_STATUS'''
pass
def set_component_name(self, sysid, compid, name):
pass
def handle_heartbeat_anysource(self, msg):
pass
def handle_gimbal_device_information_anysource(self, msg):
pass
def handle_radio_status(self, msg):
pass
def handle_gps_raw(self, msg):
pass
def handle_vfr_hud(self, msg):
pass
def handle_attitude(self, msg):
pass
def handle_sys_status(self, msg):
pass
def handle_wind(self, msg):
pass
def handle_ekf_status_report(self, msg):
pass
def handle_power_status(self, msg):
pass
def handle_heartbeat_anysource(self, msg):
pass
def handle_mission_current(self, msg):
pass
def handle_nav_controller_output(self, msg):
pass
def handle_param_value(self, msg):
pass
def handle_high_latency2(self, msg):
pass
def update_user_added_keys(self, msg):
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def idle_task(self):
pass
| 35 | 13 | 23 | 1 | 21 | 1 | 6 | 0.08 | 1 | 16 | 8 | 0 | 34 | 21 | 34 | 72 | 810 | 69 | 699 | 170 | 664 | 53 | 578 | 166 | 543 | 21 | 2 | 5 | 193 |
7,168 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_console.py
|
MAVProxy.modules.mavproxy_console.DisplayItem
|
class DisplayItem:
def __init__(self, fmt, expression, row):
self.expression = expression.strip('"\'')
self.format = fmt.strip('"\'')
re_caps = re.compile('[A-Z_][A-Z0-9_]+')
self.msg_types = set(re.findall(re_caps, expression))
self.row = row
|
class DisplayItem:
def __init__(self, fmt, expression, row):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 4 | 1 | 1 | 7 | 0 | 7 | 7 | 5 | 0 | 7 | 7 | 5 | 1 | 0 | 0 | 1 |
7,169 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_dataflash_logger.py
|
MAVProxy.modules.mavproxy_dataflash_logger.dataflash_logger
|
class dataflash_logger(mp_module.MPModule):
def __init__(self, mpstate):
"""Initialise module. We start poking the UAV for messages after this
is called"""
super(dataflash_logger, self).__init__(
mpstate,
"dataflash_logger",
"logging of mavlink dataflash messages"
)
self.sender = None
self.stopped = False
self.time_last_start_packet_sent = 0
self.time_last_stop_packet_sent = 0
self.dataflash_dir = self._dataflash_dir(mpstate)
self.download = 0
self.prev_download = 0
self.last_status_time = time.time()
self.last_seqno = 0
self.missing_blocks = {}
self.acking_blocks = {}
self.blocks_to_ack_and_nack = []
self.missing_found = 0
self.abandoned = 0
self.dropped = 0
self.armed = False
self.log_settings = mp_settings.MPSettings(
[('verbose', bool, False),
('rotate_on_disarm', bool, False),
('df_target_system', int, 0),
('df_target_component', int, mavutil.mavlink.MAV_COMP_ID_LOG)]
)
self.add_command('dataflash_logger',
self.cmd_dataflash_logger,
"dataflash logging control",
['status', 'start', 'stop', 'rotate', 'set (LOGSETTING)'])
self.add_completion_function('(LOGSETTING)',
self.log_settings.completion)
def usage(self):
'''show help on a command line options'''
return "Usage: dataflash_logger <status|start|stop|set>"
def cmd_dataflash_logger(self, args):
'''control behaviour of the module'''
if len(args) == 0:
print(self.usage())
elif args[0] == "status":
print(self.status())
elif args[0] == "stop":
self.sender = None
self.stopped = True
elif args[0] == "start":
self.stopped = False
elif args[0] == "set":
self.log_settings.command(args[1:])
elif args[0] == "rotate":
self.rotate_log()
else:
print(self.usage())
def _dataflash_dir(self, mpstate):
'''returns directory path to store DF logs in. May be relative'''
return mpstate.status.logdir
def new_log_filepath(self):
'''returns a filepath to a log which does not currently exist and is
suitable for DF logging'''
ll_filepath = os.path.join(self.dataflash_dir, 'LASTLOG.TXT')
if (os.path.exists(ll_filepath) and os.stat(ll_filepath).st_size != 0):
fh = open(ll_filepath, 'rb')
log_cnt = int(fh.read()) + 1
fh.close()
else:
log_cnt = 1
self.lastlog_file = open(ll_filepath, 'w+b')
if sys.version_info[0] >= 3:
self.lastlog_file.write(str.encode(log_cnt.__str__()))
else:
self.lastlog_file.write(log_cnt.__str__())
self.lastlog_file.close()
return os.path.join(self.dataflash_dir, '%u.BIN' % (log_cnt,))
def start_new_log(self):
'''open a new dataflash log, reset state'''
filename = self.new_log_filepath()
self.last_seqno = 0
self.logfile = open(filename, 'w+b')
print("DFLogger: logging started (%s)" % (filename))
self.prev_cnt = 0
self.download = 0
self.prev_download = 0
self.last_idle_status_printed_time = time.time()
self.last_status_time = time.time()
self.missing_blocks = {}
self.acking_blocks = {}
self.blocks_to_ack_and_nack = []
self.missing_found = 0
self.abandoned = 0
self.dropped = 0
def status(self):
'''returns information about module'''
if self.download is None:
return "Not started"
transferred = self.download - self.prev_download
self.prev_download = self.download
now = time.time()
interval = now - self.last_status_time
self.last_status_time = now
return("DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s "
"Block:%(block_cnt)d Missing:%(missing)d Fixed:%(fixed)d "
"Abandoned:%(abandoned)d" %
{"interval": interval,
"rate": transferred/(interval*1000),
"block_cnt": self.last_seqno,
"missing": len(self.missing_blocks),
"fixed": self.missing_found,
"abandoned": self.abandoned,
"state": "Inactive" if self.stopped else "Active"})
def idle_print_status(self):
'''print out statistics every 10 seconds from idle loop'''
now = time.time()
if (now - self.last_idle_status_printed_time) >= 10:
print(self.status())
self.last_idle_status_printed_time = now
def idle_send_acks_and_nacks(self):
'''Send packets to UAV in idle loop'''
max_blocks_to_send = 10
blocks_sent = 0
i = 0
now = time.time()
while (i < len(self.blocks_to_ack_and_nack) and
blocks_sent < max_blocks_to_send):
# print("ACKLIST: %s" %
# ([x[1] for x in self.blocks_to_ack_and_nack],))
stuff = self.blocks_to_ack_and_nack[i]
[master, block, status, first_sent, last_sent] = stuff
if status == 1:
# print("DFLogger: ACKing block (%d)" % (block,))
mavstatus = mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_ACK
(target_sys, target_comp) = self.sender
self.master.mav.remote_log_block_status_send(target_sys,
target_comp,
block,
mavstatus)
blocks_sent += 1
del self.acking_blocks[block]
del self.blocks_to_ack_and_nack[i]
continue
if block not in self.missing_blocks:
# we've received this block now
del self.blocks_to_ack_and_nack[i]
continue
# give up on packet if we have seen one with a much higher
# number (or after 60 seconds):
if (self.last_seqno - block > 200) or (now - first_sent > 60):
if self.log_settings.verbose:
print("DFLogger: Abandoning block (%d)" % (block,))
del self.blocks_to_ack_and_nack[i]
del self.missing_blocks[block]
self.abandoned += 1
continue
i += 1
# only send each nack every-so-often:
if last_sent is not None:
if now - last_sent < 0.1:
continue
if self.log_settings.verbose:
print("DFLogger: Asking for block (%d)" % (block,))
mavstatus = mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_NACK
(target_sys, target_comp) = self.sender
self.master.mav.remote_log_block_status_send(target_sys,
target_comp,
block,
mavstatus)
blocks_sent += 1
stuff[4] = now
def idle_task_started(self):
'''called in idle task only when logging is started'''
isarmed = self.master.motors_armed()
if self.armed != isarmed:
self.armed = isarmed
if not self.armed and self.log_settings.rotate_on_disarm:
self.rotate_log()
if self.log_settings.verbose:
self.idle_print_status()
self.idle_send_acks_and_nacks()
def idle_task_not_started(self):
'''called in idle task only when logging is not running'''
if not self.stopped:
self.tell_sender_to_start()
def idle_task(self):
'''called rapidly by mavproxy'''
if self.sender is not None:
self.idle_task_started()
else:
self.idle_task_not_started()
def tell_sender_to_stop(self, m):
'''send a stop packet (if we haven't sent one in the last second)'''
now = time.time()
if now - self.time_last_stop_packet_sent < 1:
return
if self.log_settings.verbose:
print("DFLogger: Sending stop packet")
self.time_last_stop_packet_sent = now
self.master.mav.remote_log_block_status_send(
m.get_srcSystem(),
m.get_srcComponent(),
mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_STOP,
1)
def tell_sender_to_start(self):
'''send a start packet (if we haven't sent one in the last second)'''
now = time.time()
if now - self.time_last_start_packet_sent < 1:
return
self.time_last_start_packet_sent = now
if self.log_settings.verbose:
print("DFLogger: Sending start packet")
target_sys = self.log_settings.df_target_system
target_comp = self.log_settings.df_target_component
self.master.mav.remote_log_block_status_send(
target_sys,
target_comp,
mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_START,
1)
def rotate_log(self):
'''send a start packet and rotate log'''
now = time.time()
self.time_last_start_packet_sent = now
if self.log_settings.verbose:
print("DFLogger: rotating")
target_sys = self.log_settings.df_target_system
target_comp = self.log_settings.df_target_component
for i in range(3):
# send 3 stop packets
self.master.mav.remote_log_block_status_send(
target_sys,
target_comp,
mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_STOP,
1)
self.master.mav.remote_log_block_status_send(
target_sys,
target_comp,
mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_START,
1)
self.start_new_log()
def packet_is_for_me(self, m):
'''returns true if this packet is appropriately addressed'''
if m.target_system != self.master.mav.srcSystem:
return False
if m.target_component != self.master.mav.srcComponent:
return False
# if have a sender we can also check the source address:
if self.sender is not None:
if (m.get_srcSystem(), m.get_srcComponent()) != self.sender:
return False
return True
def do_ack_block(self, seqno):
if seqno in self.acking_blocks:
# already acking this one; we probably sent
# multiple nacks and received this one
# multiple times
return
now = time.time()
# ACK the block we just got:
self.blocks_to_ack_and_nack.append([self.master, seqno, 1, now, None])
self.acking_blocks[seqno] = 1
# NACK any blocks we haven't seen and should have:
if(seqno - self.last_seqno > 1):
for block in range(self.last_seqno+1, seqno):
if block not in self.missing_blocks and \
block not in self.acking_blocks:
self.missing_blocks[block] = 1
if self.log_settings.verbose:
print("DFLogger: setting %d for nacking" % (block,))
self.blocks_to_ack_and_nack.append(
[self.master, block, 0, now, None]
)
# print("\nmissed blocks: ",self.missing_blocks)
def mavlink_packet(self, m):
'''handle mavlink packets'''
if m.get_type() == 'REMOTE_LOG_DATA_BLOCK':
if not self.packet_is_for_me(m):
self.dropped += 1
return
if self.sender is None and m.seqno == 0:
if self.log_settings.verbose:
print("DFLogger: Received data packet - starting new log")
self.start_new_log()
self.sender = (m.get_srcSystem(), m.get_srcComponent())
if self.sender is None:
# No connection right now, and this packet did not start one
return
if self.stopped:
# send a stop packet @1Hz until the other end gets the idea:
self.tell_sender_to_stop(m)
return
if self.sender is not None:
size = len(m.data)
data = bytearray(m.data[:size])
ofs = size*(m.seqno)
self.logfile.seek(ofs)
self.logfile.write(data)
if m.seqno in self.missing_blocks:
if self.log_settings.verbose:
print("DFLogger: Got missing block: %d" % (m.seqno,))
del self.missing_blocks[m.seqno]
self.missing_found += 1
self.blocks_to_ack_and_nack.append(
[self.master, m.seqno, 1, time.time(), None]
)
self.acking_blocks[m.seqno] = 1
# print("DFLogger: missing: %s" %
# (str(self.missing_blocks),))
else:
self.do_ack_block(m.seqno)
if self.last_seqno < m.seqno:
self.last_seqno = m.seqno
self.download += size
|
class dataflash_logger(mp_module.MPModule):
def __init__(self, mpstate):
'''Initialise module. We start poking the UAV for messages after this
is called'''
pass
def usage(self):
'''show help on a command line options'''
pass
def cmd_dataflash_logger(self, args):
'''control behaviour of the module'''
pass
def _dataflash_dir(self, mpstate):
'''returns directory path to store DF logs in. May be relative'''
pass
def new_log_filepath(self):
'''returns a filepath to a log which does not currently exist and is
suitable for DF logging'''
pass
def start_new_log(self):
'''open a new dataflash log, reset state'''
pass
def status(self):
'''returns information about module'''
pass
def idle_print_status(self):
'''print out statistics every 10 seconds from idle loop'''
pass
def idle_send_acks_and_nacks(self):
'''Send packets to UAV in idle loop'''
pass
def idle_task_started(self):
'''called in idle task only when logging is started'''
pass
def idle_task_not_started(self):
'''called in idle task only when logging is not running'''
pass
def idle_task_started(self):
'''called rapidly by mavproxy'''
pass
def tell_sender_to_stop(self, m):
'''send a stop packet (if we haven't sent one in the last second)'''
pass
def tell_sender_to_start(self):
'''send a start packet (if we haven't sent one in the last second)'''
pass
def rotate_log(self):
'''send a start packet and rotate log'''
pass
def packet_is_for_me(self, m):
'''returns true if this packet is appropriately addressed'''
pass
def do_ack_block(self, seqno):
pass
def mavlink_packet(self, m):
'''handle mavlink packets'''
pass
| 19 | 17 | 19 | 1 | 15 | 2 | 4 | 0.14 | 1 | 7 | 1 | 0 | 18 | 21 | 18 | 56 | 355 | 42 | 275 | 69 | 256 | 38 | 215 | 69 | 196 | 11 | 2 | 4 | 67 |
7,170 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_devop.py
|
MAVProxy.modules.mavproxy_devop.DeviceOpModule
|
class DeviceOpModule(mp_module.MPModule):
def __init__(self, mpstate):
super(DeviceOpModule, self).__init__(mpstate, "DeviceOp")
self.add_command('devop', self.cmd_devop, "device operations",
["<read|write> <spi|i2c>"])
self.request_id = 1
self.failure_strings = {
1: "No such bus type",
2: "No such bus/device",
3: "Sempahore-take failure",
4: "transfer failed",
}
def cmd_devop(self, args):
'''device operations'''
usage = "Usage: devop <read|write> <spi|i2c> name bus address"
if len(args) < 5:
print(usage)
return
if args[1] == 'spi':
bustype = mavutil.mavlink.DEVICE_OP_BUSTYPE_SPI
elif args[1] == 'i2c':
bustype = mavutil.mavlink.DEVICE_OP_BUSTYPE_I2C
else:
print(usage)
if args[0] == 'read':
self.devop_read(args[2:], bustype)
elif args[0] == 'write':
self.devop_write(args[2:], bustype)
else:
print(usage)
def devop_read(self, args, bustype):
'''read from device'''
if len(args) < 5:
print("Usage: devop read <spi|i2c> name bus address regstart count")
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0)
reg = int(args[3],base=0)
count = int(args[4],base=0)
if sys.version_info.major >= 3:
name = bytearray(name, 'ascii')
self.master.mav.device_op_read_send(self.target_system,
self.target_component,
self.request_id,
bustype,
bus,
address,
name,
reg,
count)
self.request_id += 1
def devop_write(self, args, bustype):
'''write to a device'''
usage = "Usage: devop write <spi|i2c> name bus address regstart count <bytes>"
if len(args) < 5:
print(usage)
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0)
reg = int(args[3],base=0)
count = int(args[4],base=0)
args = args[5:]
if len(args) < count:
print(usage)
return
bytes = [0]*128
for i in range(count):
bytes[i] = int(args[i],base=0)
if sys.version_info.major >= 3:
name = bytearray(name, 'ascii')
self.master.mav.device_op_write_send(self.target_system,
self.target_component,
self.request_id,
bustype,
bus,
address,
name,
reg,
count,
bytes)
self.request_id += 1
def read_show_reply(self, m):
# header
sys.stdout.write(" ")
for i in range(16):
sys.stdout.write("%3x" % i)
print("")
sys.stdout.write("%4x: " % (m.regstart-m.regstart%16,))
# leading no-data-read:
for i in range(m.regstart%16):
sys.stdout.write("-- ")
for i in range(m.count):
reg = i + m.regstart
sys.stdout.write("%02x " % (m.data[i]))
if (reg+1) % 16 == 0 and i != m.count-1:
print("")
sys.stdout.write("%4x: " % ((reg+1)-(reg+1)%16,))
# trailing no-data-read
if (m.regstart+m.count) % 16 != 0:
if m.count < 16 and m.regstart % 16 != 0 and (m.regstart%16+m.count) <16:
# front of line is padded
count = 16 - m.regstart%16 - m.count
else:
count = 16 - (m.regstart+m.count)%16
for i in range(0,count):
sys.stdout.write("-- ")
print("")
def mavlink_packet(self, m):
'''handle a mavlink packet'''
mtype = m.get_type()
if mtype == "DEVICE_OP_READ_REPLY":
if m.result != 0:
print("Operation %u failed: %u (%s)" %
(m.request_id,
m.result,
self.failure_strings.get(m.result, '????')))
else:
print("Operation %u OK: %u bytes" % (m.request_id, m.count))
self.read_show_reply(m)
if mtype == "DEVICE_OP_WRITE_REPLY":
if m.result != 0:
print("Operation %u failed: %u (%s)" %
(m.request_id,
m.result,
self.failure_strings.get(m.result, '????')))
else:
print("Operation %u OK" % m.request_id)
|
class DeviceOpModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_devop(self, args):
'''device operations'''
pass
def devop_read(self, args, bustype):
'''read from device'''
pass
def devop_write(self, args, bustype):
'''write to a device'''
pass
def read_show_reply(self, m):
pass
def mavlink_packet(self, m):
'''handle a mavlink packet'''
pass
| 7 | 4 | 23 | 1 | 20 | 1 | 5 | 0.07 | 1 | 4 | 0 | 0 | 6 | 2 | 6 | 44 | 142 | 13 | 121 | 28 | 114 | 8 | 85 | 28 | 78 | 8 | 2 | 2 | 28 |
7,171 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_emuecu.py
|
MAVProxy.modules.mavproxy_emuecu.EMUECUModule
|
class EMUECUModule(mp_module.MPModule):
def __init__(self, mpstate):
super(EMUECUModule, self).__init__(mpstate, "emuecu", "emuecu", public=False)
self.emuecu_settings = mp_settings.MPSettings(
[('port', int, 102)])
self.add_command('emu', self.cmd_emu, 'EMUECU control',
["<send>",
"set (EMUECUSETTING)"])
self.add_completion_function('(EMUECUSETTING)',
self.emuecu_settings.completion)
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if msg.get_type() == 'SERIAL_CONTROL':
print(msg)
def cmd_emu(self, args):
'''emu command handling'''
if len(args) <= 0:
print("Usage: emu <send|set>")
return
if args[0] == "send":
self.cmd_send(args[1:])
elif args[0] == "set":
self.emuecu_settings.command(args[1:])
def cmd_send(self, args):
'''send command'''
cmd = ' '.join(args) + '\n'
buf = [ord(x) for x in cmd]
buf.extend([0]*(70-len(buf)))
mav = self.master.mav
mav.serial_control_send(self.emuecu_settings.port,
0,
0, 0,
len(cmd), buf)
|
class EMUECUModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def cmd_emu(self, args):
'''emu command handling'''
pass
def cmd_send(self, args):
'''send command'''
pass
| 5 | 3 | 8 | 0 | 7 | 1 | 2 | 0.1 | 1 | 3 | 1 | 0 | 4 | 1 | 4 | 42 | 37 | 4 | 30 | 9 | 25 | 3 | 22 | 9 | 17 | 4 | 2 | 1 | 8 |
7,172 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Transform
|
class Transform(object):
'''Class to represent transform operations. Note that the operations
provided are isolated from each other, in the sense that the sequence of
operations is always: rotation, scale and translation. That means that an
operation add to itself and the final outcome will always be in the
following order: accumulated scale, accumulated rotation and accumulated
translation.'''
def __init__(self):
self.quaternion = Quaternion((1, 0, 0, 0))
self.translation = Vector3(0.0, 0.0, 0.0)
self.scale_factor = 1.0
def scale(self, scale):
self.scale_factor *= scale
def rotation_quaternion(self, vector, angle):
if not vector.length():
return None
c = math.cos(angle / 2.0)
v = math.sin(angle / 2.0) * vector.normalized()
q = Quaternion((c, v.x, v.y, v.z))
q.normalize()
return q
def rotate(self, vector, angle):
q = self.rotation_quaternion(vector, angle)
if not q:
return
self.quaternion = q * self.quaternion
self.quaternion.normalize()
def set_rotation(self, vector, angle):
q = self.rotation_quaternion(vector, angle)
if not q:
return
self.quaternion = q
def set_euler(self, roll, pitch, yaw):
self.quaternion = Quaternion((roll, pitch, yaw))
self.quaternion.normalize()
def translate(self, d):
self.translation += d
def mat4(self):
s = self.scale_factor
m = self.quaternion.dcm
d = self.translation
return (c_float * 16)(
s * m.a.x, s * m.b.x, s * m.c.x, 0,
s * m.a.y, s * m.b.y, s * m.c.y, 0,
s * m.a.z, s * m.b.z, s * m.c.z, 0,
d.x, d.y, d.z, 1
)
def apply(self, v):
v = self.quaternion.transform(v) * self.scale_factor
v += self.translation
return v
|
class Transform(object):
'''Class to represent transform operations. Note that the operations
provided are isolated from each other, in the sense that the sequence of
operations is always: rotation, scale and translation. That means that an
operation add to itself and the final outcome will always be in the
following order: accumulated scale, accumulated rotation and accumulated
translation.'''
def __init__(self):
pass
def scale(self, scale):
pass
def rotation_quaternion(self, vector, angle):
pass
def rotate(self, vector, angle):
pass
def set_rotation(self, vector, angle):
pass
def set_euler(self, roll, pitch, yaw):
pass
def translate(self, d):
pass
def mat4(self):
pass
def apply(self, v):
pass
| 10 | 1 | 5 | 0 | 5 | 0 | 1 | 0.13 | 1 | 0 | 0 | 0 | 9 | 3 | 9 | 9 | 59 | 8 | 45 | 21 | 35 | 6 | 40 | 21 | 30 | 2 | 1 | 1 | 12 |
7,173 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Program
|
class Program:
shader_type_names = {
GL_COMPUTE_SHADER: 'compute shader',
GL_VERTEX_SHADER: 'vertex shader',
GL_TESS_CONTROL_SHADER: 'tessellation control shader',
GL_TESS_EVALUATION_SHADER: 'tessellation evaluation shader',
GL_GEOMETRY_SHADER: 'geometry shader',
GL_FRAGMENT_SHADER: 'fragment shader',
}
default_shaders = {
GL_VERTEX_SHADER: '''
#version 330 core
layout (location = 0) in vec3 v;
layout (location = 1) in vec3 normal;
out vec3 v_normal;
out vec3 v_v;
uniform mat4 local = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
);
uniform mat4 model = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
);
uniform mat4 view = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
);
uniform mat4 proj = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
);
void main()
{
mat4 transform = model * local;
v_v = vec3(transform * vec4(v, 1.0));
v_normal = vec3(transform * vec4(normal, 1.0));
gl_Position = proj * view * vec4(v_v, 1.0);
}
''',
GL_FRAGMENT_SHADER: '''
#version 330 core
in vec3 v_normal;
in vec3 v_v;
out vec4 color;
struct Light {
vec3 pos;
vec3 ambient;
vec3 diffuse;
vec3 specular;
float att_linear;
float att_quad;
};
struct Material {
vec3 ambient;
vec3 diffuse;
vec3 specular;
float specular_exponent;
float alpha;
};
uniform Light light = Light(
vec3(1.0, 1.0, 1.0),
vec3(1.0, 1.0, 1.0),
vec3(1.0, 1.0, 1.0),
vec3(1.0, 1.0, 1.0),
0.0,
0.0
);
uniform Material material = Material(
vec3(.5, .5, .5),
vec3(.5, .5, .5),
vec3(.5, .5, .5),
32.0,
1.0
);
uniform vec3 camera_position = vec3(-1.0, 0.0, 0.0);
void main()
{
vec3 view_direction = normalize(camera_position - v_v);
vec3 light_direction = normalize(light.pos - v_v);
vec3 normal = normalize(v_normal);
/* If triangle is opposed to the camera, then color the other
* side. */
if (dot(normal, view_direction) < 0)
normal = -normal;
float cos_theta = dot(normal, light_direction);
if (cos_theta < 0) {
cos_theta = 0;
}
vec3 diffuse = cos_theta * light.diffuse * material.diffuse;
vec3 reflection = reflect(-light_direction, normal);
cos_theta = dot(reflection, view_direction);
if (cos_theta < 0) {
cos_theta = 0;
}
vec3 specular = pow(cos_theta, material.specular_exponent) *
light.specular * material.specular;
vec3 ambient = light.ambient * material.ambient;
float dist = length(light.pos - v_v);
float attenuation = 1.0 / (1.0 + light.att_linear * dist + light.att_quad * dist * dist);
color = vec4(attenuation * (diffuse + specular + ambient), material.alpha);
}
''',
}
def __init__(self):
self.shaders = dict(self.default_shaders)
self.uniforms = {k: None for k in (
'local',
'model',
'view',
'proj',
'camera_position',
'light.pos',
'light.ambient',
'light.diffuse',
'light.specular',
'light.att_linear',
'light.att_quad',
'material.ambient',
'material.diffuse',
'material.specular',
'material.specular_exponent',
'material.alpha',
)}
def shader_code(self, shader_type, code):
self.shaders[shader_type] = code
def compile_and_link(self):
self.program_id = glCreateProgram()
if not self.program_id:
raise Exception('Error on creating the OpenGL program')
shader_ids = []
try:
for shader_type, code in self.shaders.items():
shader_id = glCreateShader(shader_type)
name = self.shader_type_names[shader_type]
if not shader_id:
raise Exception("Error on creating %s" % name)
shader_ids.append(shader_id)
glShaderSource(shader_id, code)
glCompileShader(shader_id)
if glGetShaderiv(shader_id, GL_COMPILE_STATUS) != GL_TRUE:
error_string = glGetShaderInfoLog(shader_id)
raise Exception("Error on compiling %s: %s" % (name, error_string))
glAttachShader(self.program_id, shader_id)
glLinkProgram(self.program_id)
if glGetProgramiv(self.program_id, GL_LINK_STATUS) != GL_TRUE:
raise Exception('Error on linking the OpenGL program')
finally:
for i in shader_ids:
glDeleteShader(i)
for k in self.uniforms:
self.uniforms[k] = glGetUniformLocation(self.program_id, k)
if self.uniforms[k] < 0:
raise Exception("Couldn't get location for uniform %s" % k)
def use_material(self, material, enable_alpha=False):
t = Vector3_to_tuple
glUseProgram(self.program_id)
glUniform3f(self.uniforms['material.ambient'], *t(material.ambient))
glUniform3f(self.uniforms['material.diffuse'], *t(material.diffuse))
glUniform3f(self.uniforms['material.specular'], *t(material.specular))
glUniform1f(self.uniforms['material.specular_exponent'], material.specular_exponent)
alpha = material.alpha if enable_alpha else 1.0
glUniform1f(self.uniforms['material.alpha'], alpha)
def use_light(self, light):
t = Vector3_to_tuple
glUseProgram(self.program_id)
glUniform3f(self.uniforms['light.pos'], *t(light.position))
glUniform3f(self.uniforms['light.ambient'], *t(light.ambient))
glUniform3f(self.uniforms['light.diffuse'], *t(light.diffuse))
glUniform3f(self.uniforms['light.specular'], *t(light.specular))
glUniform1f(self.uniforms['light.att_linear'], light.att_linear)
glUniform1f(self.uniforms['light.att_quad'], light.att_quad)
def use_local_transform(self, transform):
glUseProgram(self.program_id)
m = transform.mat4()
glUniformMatrix4fv(self.uniforms['local'], 1, GL_FALSE, m)
def use_model_transform(self, transform):
glUseProgram(self.program_id)
m = transform.mat4()
glUniformMatrix4fv(self.uniforms['model'], 1, GL_FALSE, m)
def use_camera(self, camera):
t = Vector3_to_tuple
glUseProgram(self.program_id)
m = camera.view_mat4()
glUniform3f(self.uniforms['camera_position'], *t(camera.position))
glUniformMatrix4fv(self.uniforms['view'], 1, GL_FALSE, m)
def use_projection(self, projection):
glUseProgram(self.program_id)
m = projection.proj_mat4()
glUniformMatrix4fv(self.uniforms['proj'], 1, GL_FALSE, m)
|
class Program:
def __init__(self):
pass
def shader_code(self, shader_type, code):
pass
def compile_and_link(self):
pass
def use_material(self, material, enable_alpha=False):
pass
def use_light(self, light):
pass
def use_local_transform(self, transform):
pass
def use_model_transform(self, transform):
pass
def use_camera(self, camera):
pass
def use_projection(self, projection):
pass
| 10 | 0 | 10 | 0 | 10 | 0 | 2 | 0.01 | 0 | 2 | 0 | 0 | 9 | 3 | 9 | 9 | 234 | 36 | 196 | 30 | 186 | 2 | 71 | 30 | 61 | 9 | 0 | 3 | 18 |
7,174 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Perspective
|
class Perspective(object):
def __init__(self, near=0.01, far=100.0, top=0.24, right=0.24):
self.near = near
self.far = far
self.top = top
self.right = right
def proj_mat4(self):
n = self.near
f = self.far
t = self.top
r = self.right
return (c_float * 16)(
n / r, 0, 0, 0,
0, n / t, 0, 0,
0, 0, -(f + n) / (f - n), -1,
0, 0, -2 * f * n / (f - n), 0
)
|
class Perspective(object):
def __init__(self, near=0.01, far=100.0, top=0.24, right=0.24):
pass
def proj_mat4(self):
pass
| 3 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 4 | 2 | 2 | 18 | 1 | 17 | 11 | 14 | 0 | 12 | 11 | 9 | 1 | 1 | 0 | 2 |
7,175 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Orthographic
|
class Orthographic(object):
def __init__(self, near=0.0, far=2.0, top=1.0, right=1.0):
self.near = near
self.far = far
self.top = top
self.right = right
def proj_mat4(self):
n = self.near
f = self.far
t = self.top
r = self.right
return (c_float * 16)(
1 / r, 0, 0, 0,
0, 1 / t, 0, 0,
0, 0, -2 / (f - n), 0,
0, 0, -(f + n) / (f - n), 1
)
|
class Orthographic(object):
def __init__(self, near=0.0, far=2.0, top=1.0, right=1.0):
pass
def proj_mat4(self):
pass
| 3 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 4 | 2 | 2 | 18 | 1 | 17 | 11 | 14 | 0 | 12 | 11 | 9 | 1 | 1 | 0 | 2 |
7,176 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.Object
|
class Object(object):
def __init__(self, vertices,
normals=[],
indices=[],
material=Material(),
vertices_per_face=3,
enable_alpha=False):
self.local = Transform()
self.model = Transform()
self.num_vertices = len(vertices)
assert(self.num_vertices > 0)
for i in range(self.num_vertices):
if not isinstance(vertices[i], Vector3):
vertices[i] = Vector3(*vertices[i])
self.midpoint = Vector3(0, 0, 0)
for v in vertices:
self.midpoint += v
self.midpoint /= self.num_vertices
self.material = material
if normals:
for i in range(len(normals)):
if not isinstance(normals[i], Vector3):
normals[i] = Vector3(*normals[i])
else:
normals = self.calc_normals(vertices)
if not indices:
indices = self.calc_indices(len(vertices), vertices_per_face)
self.num_indices = len(indices)
self.centroids = None
if enable_alpha:
self.centroids = self.calc_centroids(indices, vertices)
self.vao = self.create_vao(vertices, normals, indices)
def create_vao(self, vertices, normals, indices):
vao = glGenVertexArrays(1)
glBindVertexArray(vao)
vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
vertices = [x for p in vertices for x in (p.x, p.y, p.z)]
normals = [x for p in normals for x in (p.x, p.y, p.z)]
data = vertices + normals
data = (c_float * len(data))(*data)
glBufferData(GL_ARRAY_BUFFER, data, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, c_void_p(0))
glEnableVertexAttribArray(0)
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0,
c_void_p(sizeof(c_float) * len(vertices)))
glEnableVertexAttribArray(1)
ebo = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
data = (c_int * len(indices))(*indices)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, data, GL_STATIC_DRAW);
glBindVertexArray(0)
return vao
def calc_centroids(self, indices, vertices):
num_faces = len(indices) / 3
centroids = []
for i in range(num_faces):
a = vertices[indices[i * 3]]
b = vertices[indices[i * 3 + 1]]
c = vertices[indices[i * 3 + 2]]
centroids.append((a + b + c) / 3)
return centroids
def before_draw(self, program, enable_alpha=False):
glUseProgram(program.program_id)
program.use_local_transform(self.local)
program.use_model_transform(self.model)
if self.material:
program.use_material(self.material, enable_alpha=enable_alpha)
glBindVertexArray(self.vao)
def after_draw(self, program):
glBindVertexArray(0)
def draw(self, program, faces=None, camera=None):
has_alpha = self.material and self.centroids and camera
self.before_draw(program, has_alpha)
if has_alpha:
if faces is None:
num_faces = self.num_indices / 3
faces = [i for i in range(num_faces)]
# Sort faces based on distance between centroids and camera position
dists = {}
for i in faces:
v = self.model.apply(self.local.apply(self.centroids[i]))
dists[i] = (camera.position - v).length()
faces = sorted(faces, None, lambda i: dists[i])
elif faces:
faces = sorted(faces)
if faces is None:
glDrawElements(GL_TRIANGLES, self.num_indices, GL_UNSIGNED_INT, None)
elif faces:
i0 = 0
l = len(faces)
i = 1
while i < l:
if faces[i] != faces[i - 1] + 1:
pointer = c_void_p(sizeof(c_uint) * faces[i0] * 3)
glDrawElements(GL_TRIANGLES, (i - i0) * 3, GL_UNSIGNED_INT,
pointer)
i0 = i
i += 1
pointer = c_void_p(sizeof(c_uint) * faces[i0] * 3)
glDrawElements(GL_TRIANGLES, (i - i0) * 3, GL_UNSIGNED_INT, pointer)
self.after_draw(program)
def calc_indices(self, num_vertices, vertices_per_face):
num_faces = int(num_vertices / vertices_per_face)
indices = []
for i in range(num_faces):
i0 = i * vertices_per_face
ia = i0 + 1
for _ in range(vertices_per_face - 2):
ib = ia + 1
indices.append(i0)
indices.append(ia)
indices.append(ib)
ia = ib
return indices
def calc_normals(self, vertices):
def normal(triangle):
a, b, c = triangle
v1 = b - a
v2 = c - a
n = v1 % v2
direction = (a + b + c) / 3.0 - self.midpoint
if n * direction < 0:
n = -n
return n
normals = []
for i in range(0, self.num_vertices, 3):
n = normal(vertices[i:i+3])
normals.extend([n, n, n])
return normals
|
class Object(object):
def __init__(self, vertices,
normals=[],
indices=[],
material=Material(),
vertices_per_face=3,
enable_alpha=False):
pass
def create_vao(self, vertices, normals, indices):
pass
def calc_centroids(self, indices, vertices):
pass
def before_draw(self, program, enable_alpha=False):
pass
def after_draw(self, program):
pass
def draw(self, program, faces=None, camera=None):
pass
def calc_indices(self, num_vertices, vertices_per_face):
pass
def calc_normals(self, vertices):
pass
def normal(triangle):
pass
| 10 | 0 | 18 | 3 | 15 | 0 | 3 | 0.01 | 1 | 4 | 2 | 1 | 8 | 8 | 8 | 8 | 159 | 29 | 129 | 58 | 114 | 1 | 119 | 52 | 109 | 9 | 1 | 3 | 31 |
7,177 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_chat/chat_openai.py
|
MAVProxy.modules.mavproxy_chat.chat_openai.chat_openai
|
class chat_openai():
def __init__(self, mpstate, status_cb=None, reply_cb=None, wait_for_command_ack_fn=None):
# keep reference to mpstate
self.mpstate = mpstate
# keep reference to status callback
self.status_cb = status_cb
self.reply_cb = reply_cb
# keep reference to wait_for_command_ack_fn
self.wait_for_command_ack_fn = wait_for_command_ack_fn
# lock to prevent multiple threads sending text to the assistant at the same time
self.send_lock = Lock()
# wakeup timer array
self.wakeup_schedule = []
self.thread = Thread(target=self.check_wakeup_timers)
self.thread.start()
# initialise OpenAI connection
self.client = None
self.assistant = None
self.assistant_thread = None
self.latest_run_id = None
# check connection to OpenAI assistant and connect if necessary
# returns True if connection is good, False if not
def check_connection(self):
# create connection object
if self.client is None:
try:
self.client = OpenAI()
except Exception:
print("chat: failed to connect to OpenAI")
return False
# check connection again just to be sure
if self.client is None:
print("chat: failed to connect to OpenAI")
return False
# get assistant id
if self.assistant is None:
# get list of available assistants
my_assistants = self.client.beta.assistants.list()
if my_assistants is None or my_assistants.data is None or len(my_assistants.data) == 0:
print("chat: no assistants available")
return False
# search for assistant with the expected name
for existing_assistant in my_assistants.data:
if existing_assistant.name == "ArduPilot Vehicle Control via MAVLink":
self.assistant = existing_assistant
break
# raise error if assistant not found
if self.assistant is None:
print("chat: failed to connect to OpenAI assistant")
return False
# create new thread
if self.assistant_thread is None:
self.assistant_thread = self.client.beta.threads.create()
if self.assistant_thread is None:
return "chat: failed to create assistant thread"
# if we got this far the connection must be good
return True
# set the OpenAI API key
def set_api_key(self, api_key_str):
self.client = OpenAI(api_key=api_key_str)
self.assistant = None
self.assistant_thread = None
# cancel the active run
def cancel_run(self):
# check the active thread and run id
if self.assistant_thread and self.latest_run_id is not None:
# cancel the run
self.client.beta.threads.runs.cancel(
thread_id=self.assistant_thread.id,
run_id=self.latest_run_id
)
else:
self.send_status("No active run to cancel")
# send text to assistant
def send_to_assistant(self, text):
# get lock
with self.send_lock:
# check connection
if not self.check_connection():
self.send_reply("chat: failed to connect to OpenAI")
return
# create a new message
input_message = self.client.beta.threads.messages.create(
thread_id=self.assistant_thread.id,
role="user",
content=text
)
if input_message is None:
self.send_reply("chat: failed to create input message")
return
# create event handler
event_handler = EventHandler(self)
# create a run
with self.client.beta.threads.runs.stream(
thread_id=self.assistant_thread.id,
assistant_id=self.assistant.id,
event_handler=event_handler
) as stream:
stream.until_done()
# retrieve the run and print its final status
if self.assistant_thread and self.latest_run_id:
run = self.client.beta.threads.runs.retrieve(
thread_id=self.assistant_thread.id,
run_id=self.latest_run_id
)
if run is not None:
self.send_status(run.status)
else:
self.send_status("done")
# handle function call request from assistant
def handle_function_call(self, event):
# sanity check required action (this should never happen)
if (event.event != "thread.run.requires_action"):
print("chat::handle_function_call: assistant function call empty")
return
# check format
if event.data.required_action.submit_tool_outputs is None:
print("chat::handle_function_call: submit tools outputs empty")
return
tool_outputs = []
for tool_call in event.data.required_action.submit_tool_outputs.tool_calls:
# init output to None
output = "invalid function call"
# handle supported functions
supported_funcs = ["get_current_datetime",
"get_vehicle_type",
"get_mode_mapping",
"get_vehicle_state",
"get_vehicle_location_and_yaw",
"get_location_plus_offset",
"get_location_plus_dist_at_bearing",
"send_mavlink_command_int",
"send_mavlink_set_position_target_global_int",
"get_available_mavlink_messages", "get_mavlink_message",
"get_all_parameters",
"get_parameter",
"set_parameter",
"get_parameter_description",
"set_wakeup_timer",
"get_wakeup_timers",
"delete_wakeup_timers"]
# convert function name to a callable function
func_name = tool_call.function.name
func = getattr(self, func_name, None)
if func_name in supported_funcs and func is not None:
stage_str = None
try:
# parse arguments
stage_str = "parse arguments"
arguments = json.loads(tool_call.function.arguments)
# call function
stage_str = "function call"
output = func(arguments)
# convert to json
stage_str = "convert output to json"
output = json.dumps(output)
except Exception:
error_message = str(func_name) + ": " + stage_str + " failed"
print("chat: " + error_message)
output = error_message
else:
print("chat: unrecognised function name: " + func_name)
output = "unrecognised function call: " + func_name
# append output to list of outputs
tool_outputs.append({"tool_call_id": tool_call.id, "output": output})
# send function replies to assistant
try:
stream = self.client.beta.threads.runs.submit_tool_outputs(
thread_id=event.data.thread_id,
run_id=event.data.id,
tool_outputs=tool_outputs,
stream=True)
for event in stream:
# requires_action events handled by function calls
if event.event == 'thread.run.requires_action':
self.handle_function_call(event)
# display reply text in the reply window
if (event.event == "thread.message.delta"):
stream_text = event.data.delta.content[0].text.value
self.send_reply(stream_text)
except Exception:
print("chat: error replying to function call")
print(tool_outputs)
return
# get the current date and time in the format, Saturday, June 24, 2023 6:14:14 PM
def get_current_datetime(self, arguments):
return datetime.now().strftime("%A, %B %d, %Y %I:%M:%S %p")
# get vehicle vehicle type (e.g. "Copter", "Plane", "Rover", "Boat", etc)
def get_vehicle_type(self, arguments):
# get vehicle type from latest HEARTBEAT message
hearbeat_msg = self.mpstate.master().messages.get('HEARTBEAT', None)
vehicle_type_str = "unknown"
if hearbeat_msg is not None:
if hearbeat_msg.type in [mavutil.mavlink.MAV_TYPE_FIXED_WING,
mavutil.mavlink.MAV_TYPE_VTOL_DUOROTOR,
mavutil.mavlink.MAV_TYPE_VTOL_QUADROTOR,
mavutil.mavlink.MAV_TYPE_VTOL_TILTROTOR]:
vehicle_type_str = "Plane"
if hearbeat_msg.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER:
vehicle_type_str = "Rover"
if hearbeat_msg.type == mavutil.mavlink.MAV_TYPE_SURFACE_BOAT:
vehicle_type_str = "Boat"
if hearbeat_msg.type == mavutil.mavlink.MAV_TYPE_SUBMARINE:
vehicle_type_str = "Sub"
if hearbeat_msg.type in [mavutil.mavlink.MAV_TYPE_QUADROTOR,
mavutil.mavlink.MAV_TYPE_COAXIAL,
mavutil.mavlink.MAV_TYPE_HEXAROTOR,
mavutil.mavlink.MAV_TYPE_OCTOROTOR,
mavutil.mavlink.MAV_TYPE_TRICOPTER,
mavutil.mavlink.MAV_TYPE_DODECAROTOR]:
vehicle_type_str = "Copter"
if hearbeat_msg.type == mavutil.mavlink.MAV_TYPE_HELICOPTER:
vehicle_type_str = "Heli"
if hearbeat_msg.type == mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER:
vehicle_type_str = "Tracker"
if hearbeat_msg.type == mavutil.mavlink.MAV_TYPE_AIRSHIP:
vehicle_type_str = "Blimp"
return {
"vehicle_type": vehicle_type_str
}
# get mode mapping
def get_mode_mapping(self, arguments):
# get name and/or number arguments
mode_name = arguments.get("name", None)
if mode_name is not None:
mode_name = mode_name.upper()
mode_number = arguments.get("number", None)
if mode_number is not None:
mode_number = int(mode_number)
# check mode mapping is available
if self.mpstate.master() is None or self.mpstate.master().mode_mapping() is None:
return "get_mode_mapping: failed to retrieve mode mapping"
# prepare list of modes
mode_list = []
mode_mapping = self.mpstate.master().mode_mapping()
# handle request for all modes
if mode_name is None and mode_number is None:
for mname in mode_mapping:
mnumber = mode_mapping[mname]
mode_list.append({"name": mname.upper(), "number": mnumber})
# handle request using mode name
elif mode_name is not None:
for mname in mode_mapping:
if mname.upper() == mode_name:
mode_list.append({"name": mname.upper(), "number": mode_mapping[mname]})
# handle request using mode number
elif mode_number is not None:
for mname in mode_mapping:
mnumber = mode_mapping[mname]
if mnumber == mode_number:
mode_list.append({"name": mname.upper(), "number": mnumber})
# return list of modes
return mode_list
# get vehicle state including armed, mode
def get_vehicle_state(self, arguments):
# get mode from latest HEARTBEAT message
hearbeat_msg = self.mpstate.master().messages.get('HEARTBEAT', None)
if hearbeat_msg is None:
mode_number = 0
print("chat: get_vehicle_state: vehicle mode is unknown")
else:
mode_number = hearbeat_msg.custom_mode
return {
"armed": (self.mpstate.master().motors_armed() > 0),
"mode": mode_number
}
# return the vehicle's location and yaw
def get_vehicle_location_and_yaw(self, arguments):
lat_deg = 0
lon_deg = 0
alt_amsl_m = 0
alt_rel_m = 0
yaw_deg = 0
gpi = self.mpstate.master().messages.get('GLOBAL_POSITION_INT', None)
if gpi:
lat_deg = gpi.lat * 1e-7,
lon_deg = gpi.lon * 1e-7,
alt_amsl_m = gpi.alt * 1e-3,
alt_rel_m = gpi.relative_alt * 1e-3
yaw_deg = gpi.hdg * 1e-2
location = {
"latitude": lat_deg,
"longitude": lon_deg,
"altitude_amsl": alt_amsl_m,
"altitude_above_home": alt_rel_m,
"yaw" : yaw_deg
}
return location
# Calculate the latitude and longitude given distances (in meters) North and East
def get_location_plus_offset(self, arguments):
lat = arguments.get("latitude", 0)
lon = arguments.get("longitude", 0)
dist_north = arguments.get("distance_north", 0)
dist_east = arguments.get("distance_east", 0)
lat_with_offset, lon_with_offset = self.get_latitude_longitude_given_offset(lat, lon, dist_north, dist_east)
return {
"latitude": lat_with_offset,
"longitude": lon_with_offset
}
# Calculate the latitude and longitude given a distance (in meters) and bearing (in degrees)
def get_location_plus_dist_at_bearing(self, arguments):
lat = arguments.get("latitude", 0)
lon = arguments.get("longitude", 0)
distance = arguments.get("distance", 0)
bearing_deg = arguments.get("bearing", 0)
dist_north = math.cos(math.radians(bearing_deg)) * distance
dist_east = math.sin(math.radians(bearing_deg)) * distance
lat_with_offset, lon_with_offset = self.get_latitude_longitude_given_offset(lat, lon, dist_north, dist_east)
return {
"latitude": lat_with_offset,
"longitude": lon_with_offset
}
# send a mavlink command_int message to the vehicle
def send_mavlink_command_int(self, arguments):
target_system = arguments.get("target_system", self.mpstate.settings.target_system)
target_component = arguments.get("target_component", 1)
frame = arguments.get("frame", 0)
if ("command" not in arguments):
return "command_int not sent. command field required"
command = arguments.get("command", 0)
current = arguments.get("current", 0)
autocontinue = arguments.get("autocontinue", 0)
param1 = arguments.get("param1", 0)
param2 = arguments.get("param2", 0)
param3 = arguments.get("param3", 0)
param4 = arguments.get("param4", 0)
x = arguments.get("x", 0)
y = arguments.get("y", 0)
z = arguments.get("z", 0)
# sanity check arguments
if command == mavutil.mavlink.MAV_CMD_NAV_TAKEOFF and z == 0:
return "command_int not sent. MAV_CMD_NAV_TAKEOFF requires alt in z field"
self.mpstate.master().mav.command_int_send(target_system, target_component,
frame, command, current, autocontinue,
param1, param2, param3, param4,
x, y, z)
# wait for command ack
mav_result = self.wait_for_command_ack_fn(command)
# check for timeout
if mav_result is None:
print("send_mavlink_command_int: timed out")
return "command_int timed out"
# update assistant with result
if mav_result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
return "command_int succeeded"
if mav_result == mavutil.mavlink.MAV_RESULT_FAILED:
return "command_int failed"
if mav_result == mavutil.mavlink.MAV_RESULT_DENIED:
return "command_int denied"
if mav_result == mavutil.mavlink.MAV_RESULT_UNSUPPORTED:
return "command_int unsupported"
if mav_result == mavutil.mavlink.MAV_RESULT_TEMPORARILY_REJECTED:
return "command_int temporarily rejected"
print("send_mavlink_command_int: received unexpected command ack result")
return "command_int unknown result"
# send a mavlink send_mavlink_set_position_target_global_int message to the vehicle
def send_mavlink_set_position_target_global_int(self, arguments):
if arguments is None:
return "send_mavlink_set_position_target_global_int: arguments is None"
time_boot_ms = arguments.get("time_boot_ms", 0)
target_system = arguments.get("target_system", self.mpstate.settings.target_system)
target_component = arguments.get("target_component", 1)
coordinate_frame = arguments.get("coordinate_frame", 5)
type_mask = arguments.get("type_mask", 0)
lat_int = int(arguments.get("latitude", 0) * 1e7)
lon_int = int(arguments.get("longitude", 0) * 1e7)
alt = arguments.get("alt", 0)
vx = arguments.get("vx", 0)
vy = arguments.get("vy", 0)
vz = arguments.get("vz", 0)
afx = arguments.get("afx", 0)
afy = arguments.get("afy", 0)
afz = arguments.get("afz", 0)
yaw = arguments.get("yaw", 0)
yaw_rate = arguments.get("yaw_rate", 0)
# sanity check arguments
if type_mask == 3576:
# if position is specified check lat, lon, alt are provided
if "latitude" not in arguments.keys():
return "send_mavlink_set_position_target_global_int: latitude field required"
if "longitude" not in arguments.keys():
return "send_mavlink_set_position_target_global_int: longitude field required"
if "alt" not in arguments.keys():
return "send_mavlink_set_position_target_global_int: alt field required"
self.mpstate.master().mav.set_position_target_global_int_send(time_boot_ms, target_system, target_component,
coordinate_frame, type_mask,
lat_int, lon_int, alt,
vx, vy, vz,
afx, afy, afz,
yaw, yaw_rate)
return "set_position_target_global_int sent"
# get a list of mavlink message names that can be retrieved using the get_mavlink_message function
def get_available_mavlink_messages(self, arguments):
# check if no messages available
if self.mpstate.master().messages is None or len(self.mpstate.master().messages) == 0:
return "get_available_mavlink_messages: no messages available"
# retrieve each available message's name
mav_msg_names = []
for msg in self.mpstate.master().messages:
# append all message names except MAV
if msg != "MAV":
mav_msg_names.append(msg)
# return list of message names
return mav_msg_names
# get a mavlink message including all fields and values sent by the vehicle
def get_mavlink_message(self, arguments):
if arguments is None:
return "get_mavlink_message: arguments is None"
# retrieve requested message's name
mav_msg_name = arguments.get("message", None)
if mav_msg_name is None:
return "get_mavlink_message: message not specified"
# retrieve message
mav_msg = self.mpstate.master().messages.get(mav_msg_name, None)
if mav_msg is None:
return "get_mavlink_message: message not found"
# return message
return mav_msg.to_dict()
# get all available parameters names and their values
def get_all_parameters(self, arguments):
# check if any parameters are available
if self.mpstate.mav_param is None or len(self.mpstate.mav_param) == 0:
return "get_all_parameters: no parameters are available"
param_list = {}
for param_name in sorted(self.mpstate.mav_param.keys()):
param_list[param_name] = self.mpstate.mav_param.get(param_name)
return param_list
# get a vehicle parameter's value
def get_parameter(self, arguments):
param_name = arguments.get("name", None)
if param_name is None:
print("get_parameter: name not specified")
return "get_parameter: name not specified"
# start with empty parameter list
param_list = {}
# handle param name containing regex
if self.contains_regex(param_name):
pattern = re.compile(param_name)
for existing_param_name in sorted(self.mpstate.mav_param.keys()):
if pattern.match(existing_param_name) is not None:
param_value = self.mpstate.functions.get_mav_param(existing_param_name, None)
if param_value is None:
print("chat: get_parameter unable to get " + existing_param_name)
else:
param_list[existing_param_name] = param_value
else:
# handle simple case of a single parameter name
param_value = self.mpstate.functions.get_mav_param(param_name, None)
if param_value is None:
return "get_parameter: " + param_name + " parameter not found"
param_list[param_name] = param_value
return param_list
# set a vehicle parameter's value
def set_parameter(self, arguments):
param_name = arguments.get("name", None)
if param_name is None:
return "set_parameter: parameter name not specified"
param_value = arguments.get("value", None)
if param_value is None:
return "set_parameter: value not specified"
self.mpstate.functions.param_set(param_name, param_value, retries=3)
return "set_parameter: parameter value set"
# get vehicle parameter descriptions including description, units, min and max
def get_parameter_description(self, arguments):
param_name = arguments.get("name", None)
if param_name is None:
return "get_parameter_description: name not specified"
# get parameter definitions
phelp = param_help.ParamHelp()
phelp.vehicle_name = "ArduCopter"
param_help_tree = phelp.param_help_tree(True)
# start with an empty parameter description dictionary
param_descriptions = {}
# handle param name containing regex
if self.contains_regex(param_name):
pattern = re.compile(param_name)
for existing_param_name in sorted(self.mpstate.mav_param.keys()):
if pattern.match(existing_param_name) is not None:
param_desc = self.get_single_parameter_description(param_help_tree, existing_param_name)
if param_desc is not None:
param_descriptions[existing_param_name] = param_desc
else:
# handle simple case of a single parameter name
param_desc = self.get_single_parameter_description(param_help_tree, param_name)
if param_desc is None:
return "get_parameter_description: " + param_name + " parameter description not found"
param_descriptions[param_name] = param_desc
return param_descriptions
# get a single parameter's descriptions as a dictionary
# returns None if parameter description cannot be found
def get_single_parameter_description(self, param_help_tree, param_name):
# search for parameter
param_info = None
if param_name in param_help_tree.keys():
param_info = param_help_tree[param_name]
else:
# check each possible vehicle name
for vehicle_name in ["ArduCopter", "ArduPlane", "Rover", "Sub"]:
vehicle_param_name = vehicle_name + ":" + param_name
if vehicle_param_name in param_help_tree.keys():
param_info = param_help_tree[vehicle_param_name]
break
if param_info is None:
return None
# start with empty dictionary
param_desc_dict = {}
# add name
param_desc_dict['name'] = param_name
# get description
param_desc_dict['description'] = param_info.get('documentation')
# iterate over fields to get units and range
param_fields = param_info.find('field')
if param_fields is not None:
for field in param_info.field:
field_name = field.get('name')
if field_name == 'Units':
param_desc_dict['units'] = str(field)
if field_name == 'Range':
if ' ' in str(field):
param_desc_dict['min'] = str(field).split(' ')[0]
param_desc_dict['max'] = str(field).split(' ')[1]
# iterate over values
param_values = param_info.find('values')
if param_values is not None:
param_value_dict = {}
for c in param_values.getchildren():
value_int = int(c.get('code'))
param_value_dict[value_int] = str(c)
if len(param_value_dict) > 0:
param_desc_dict['values'] = param_value_dict
# return dictionary
return param_desc_dict
# set a wakeup timer
def set_wakeup_timer(self, arguments):
# check required arguments are specified
seconds = arguments.get("seconds", -1)
if seconds < 0:
return "set_wakeup_timer: seconds not specified"
message = arguments.get("message", None)
if message is None:
return "set_wakeup_timer: message not specified"
# add timer to wakeup schedule
self.wakeup_schedule.append({"time": time.time() + seconds, "message": message})
return "set_wakeup_timer: wakeup timer set"
# get wake timers
def get_wakeup_timers(self, arguments):
# check message argument, default to None meaning all
message = arguments.get("message", None)
# prepare list of matching timers
matching_timers = []
# handle simple case of all timers
if message is None:
matching_timers = self.wakeup_schedule
# handle regex in message
elif self.contains_regex(message):
message_pattern = re.compile(message, re.IGNORECASE)
for wakeup_timer in self.wakeup_schedule:
if message_pattern.match(wakeup_timer["message"]) is not None:
matching_timers.append(wakeup_timer)
# handle case of a specific message
else:
for wakeup_timer in self.wakeup_schedule:
if wakeup_timer["message"] == message:
matching_timers.append(wakeup_timer)
# return matching timers
return matching_timers
# delete wake timers
def delete_wakeup_timers(self, arguments):
# check message argument, default to all
message = arguments.get("message", None)
# find matching timers
num_timers_deleted = 0
# handle simple case of deleting all timers
if message is None:
num_timers_deleted = len(self.wakeup_schedule)
self.wakeup_schedule.clear()
# handle regex in message
elif self.contains_regex(message):
message_pattern = re.compile(message, re.IGNORECASE)
for wakeup_timer in self.wakeup_schedule:
if message_pattern.match(wakeup_timer["message"]) is not None:
num_timers_deleted = num_timers_deleted + 1
self.wakeup_schedule.remove(wakeup_timer)
else:
# handle simple case of a single message
for wakeup_timer in self.wakeup_schedule:
if wakeup_timer["message"] == message:
num_timers_deleted = num_timers_deleted + 1
self.wakeup_schedule.remove(wakeup_timer)
# return number deleted and remaining
return "delete_wakeup_timers: deleted " + str(num_timers_deleted) + " timers, " + str(len(self.wakeup_schedule)) + " remaining" # noqa
# check if any wakeup timers have expired and send messages if they have
# this function never returns so it should be called from a new thread
def check_wakeup_timers(self):
while True:
# wait for one second
time.sleep(1)
# check if any timers are set
if len(self.wakeup_schedule) == 0:
continue
# get current time
now = time.time()
# check if any timers have expired
for wakeup_timer in self.wakeup_schedule:
if now >= wakeup_timer["time"]:
# send message to assistant
message = "WAKEUP:" + wakeup_timer["message"]
self.send_to_assistant(message)
# remove from wakeup schedule
self.wakeup_schedule.remove(wakeup_timer)
# wrap latitude to range -90 to 90
def wrap_latitude(self, latitude_deg):
if latitude_deg > 90:
return 180 - latitude_deg
if latitude_deg < -90:
return -(180 + latitude_deg)
return latitude_deg
# wrap longitude to range -180 to 180
def wrap_longitude(self, longitude_deg):
if longitude_deg > 180:
return longitude_deg - 360
if longitude_deg < -180:
return longitude_deg + 360
return longitude_deg
# calculate latitude and longitude given distances (in meters) North and East
# returns latitude and longitude in degrees
def get_latitude_longitude_given_offset(self, latitude, longitude, dist_north, dist_east):
lat_lon_to_meters_scaling = 89.8320495336892 * 1e-7
lat_diff = dist_north * lat_lon_to_meters_scaling
lon_diff = dist_east * lat_lon_to_meters_scaling / max(0.01, math.cos(math.radians((latitude+lat_diff)/2)))
return self.wrap_latitude(latitude + lat_diff), self.wrap_longitude(longitude + lon_diff)
# send status to chat window via callback
def send_status(self, status):
if self.status_cb is not None:
self.status_cb(status)
def send_reply(self, reply):
if self.reply_cb is not None:
self.reply_cb(reply)
# returns true if string contains regex characters
def contains_regex(self, string):
regex_characters = ".^$*+?{}[]\\|()"
for x in regex_characters:
if string.count(x):
return True
return False
|
class chat_openai():
def __init__(self, mpstate, status_cb=None, reply_cb=None, wait_for_command_ack_fn=None):
pass
def check_connection(self):
pass
def set_api_key(self, api_key_str):
pass
def cancel_run(self):
pass
def send_to_assistant(self, text):
pass
def handle_function_call(self, event):
pass
def get_current_datetime(self, arguments):
pass
def get_vehicle_type(self, arguments):
pass
def get_mode_mapping(self, arguments):
pass
def get_vehicle_state(self, arguments):
pass
def get_vehicle_location_and_yaw(self, arguments):
pass
def get_location_plus_offset(self, arguments):
pass
def get_location_plus_dist_at_bearing(self, arguments):
pass
def send_mavlink_command_int(self, arguments):
pass
def send_mavlink_set_position_target_global_int(self, arguments):
pass
def get_available_mavlink_messages(self, arguments):
pass
def get_mavlink_message(self, arguments):
pass
def get_all_parameters(self, arguments):
pass
def get_parameter(self, arguments):
pass
def set_parameter(self, arguments):
pass
def get_parameter_description(self, arguments):
pass
def get_single_parameter_description(self, param_help_tree, param_name):
pass
def set_wakeup_timer(self, arguments):
pass
def get_wakeup_timers(self, arguments):
pass
def delete_wakeup_timers(self, arguments):
pass
def check_wakeup_timers(self):
pass
def wrap_latitude(self, latitude_deg):
pass
def wrap_longitude(self, longitude_deg):
pass
def get_latitude_longitude_given_offset(self, latitude, longitude, dist_north, dist_east):
pass
def send_status(self, status):
pass
def send_reply(self, reply):
pass
def contains_regex(self, string):
pass
| 33 | 0 | 21 | 2 | 16 | 3 | 5 | 0.24 | 0 | 7 | 2 | 0 | 32 | 11 | 32 | 32 | 749 | 104 | 519 | 169 | 486 | 127 | 438 | 168 | 405 | 13 | 0 | 4 | 151 |
7,178 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipClearLayer
|
class SlipClearLayer:
'''remove all objects in a layer'''
def __init__(self, layer):
self.layer = str(layer)
|
class SlipClearLayer:
'''remove all objects in a layer'''
def __init__(self, layer):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 3 | 3 | 1 | 1 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
7,179 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash.py
|
MAVProxy.modules.lib.wxsaildash.SailingDashboard
|
class SailingDashboard(object):
'''
A sailing dashboard for MAVProxy
'''
def __init__(self, title="MAVProxy: Sailing Dashboard"):
self.title = title
# create a pipe for communication from the module to the GUI
self.child_pipe_recv, self.parent_pipe_send = multiproc.Pipe(duplex=False)
self.close_event = multiproc.Event()
self.close_event.clear()
# create and start the child process
self.child = multiproc.Process(target=self.child_task)
self.child.start()
# prevent the parent from using the child connection
self.child_pipe_recv.close()
def child_task(self):
'''The child process hosts the GUI elements'''
# prevent the child from using the parent connection
self.parent_pipe_send.close()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxsaildash_ui import SailingDashboardFrame
# create the wx application and pass self as the state
app = wx.App()
app.frame = SailingDashboardFrame(state=self, title=self.title, size=(800, 300))
app.frame.SetDoubleBuffered(True)
app.frame.Show()
app.MainLoop()
# trigger a close event when the main app window is closed.
# the event is monitored by the MAVProxy module which will
# flag the module for unloading
self.close_event.set()
def close(self):
'''Close the GUI'''
# trigger a close event which is monitored by the
# child gui process - it will close allowing the
# process to be joined
self.close_event.set()
if self.is_alive():
self.child.join(timeout=2.0)
def is_alive(self):
'''Check if the GUI process is alive'''
return self.child.is_alive()
|
class SailingDashboard(object):
'''
A sailing dashboard for MAVProxy
'''
def __init__(self, title="MAVProxy: Sailing Dashboard"):
pass
def child_task(self):
'''The child process hosts the GUI elements'''
pass
def close(self):
'''Close the GUI'''
pass
def is_alive(self):
'''Check if the GUI process is alive'''
pass
| 5 | 4 | 12 | 2 | 6 | 4 | 1 | 0.65 | 1 | 1 | 1 | 0 | 4 | 5 | 4 | 4 | 56 | 13 | 26 | 13 | 18 | 17 | 26 | 13 | 18 | 2 | 1 | 1 | 5 |
7,180 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipDefaultPopup
|
class SlipDefaultPopup:
'''an object to hold a default popup menu'''
def __init__(self, popup, combine=False):
self.popup = popup
self.combine = combine
|
class SlipDefaultPopup:
'''an object to hold a default popup menu'''
def __init__(self, popup, combine=False):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.25 | 0 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 5 | 0 | 4 | 4 | 2 | 1 | 4 | 4 | 2 | 1 | 0 | 0 | 1 |
7,181 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.FrameSuffixData
|
class FrameSuffixData:
def __init__(self):
self.timecode=-1
self.timecode_sub=-1
self.timestamp = -1
self.stamp_camera_mid_exposure = -1
self.stamp_data_received = -1
self.stamp_transmit = -1
self.prec_timestamp_secs = -1
self.prec_timestamp_frac_secs = -1
self.param = 0
self.is_recording = False
self.tracked_models_changed = True
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_str = ""
if not self.timestamp == -1:
out_str += "%sTimestamp : %3.3f\n"%(out_tab_str, self.timestamp)
if not self.stamp_camera_mid_exposure == -1:
out_str += "%sMid-exposure timestamp : %3.1d\n"%(out_tab_str, self.stamp_camera_mid_exposure)
if not self.stamp_data_received == -1:
out_str += "%sCamera data received timestamp : %3.1d\n"%(out_tab_str, self.stamp_data_received)
if not self.stamp_transmit == -1:
out_str += "%sTransmit timestamp : %3.1d\n"%(out_tab_str, self.stamp_transmit)
if not self.prec_timestamp_secs == -1:
#hours = int(self.prec_timestamp_secs/3600)
#minutes=int(self.prec_timestamp_secs/60)%60
#seconds=self.prec_timestamp_secs%60
#hms_string="%sPrecision timestamp (hh:mm:ss) : %2.1d:%2.2d:%2.2d\n"%(out_tab_str,hours, minutes, seconds)
#out_str += hms_string
out_str += "%sPrecision timestamp (seconds) : %3.1d\n"%(out_tab_str, self.prec_timestamp_secs)
if not self.prec_timestamp_frac_secs == -1:
out_str += "%sPrecision timestamp (fractional seconds) : %3.1d\n"%(out_tab_str, self.prec_timestamp_frac_secs)
return out_str
|
class FrameSuffixData:
def __init__(self):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 3 | 0 | 18 | 1 | 14 | 3 | 4 | 0.17 | 0 | 0 | 0 | 0 | 2 | 11 | 2 | 2 | 38 | 4 | 29 | 16 | 26 | 5 | 29 | 16 | 26 | 7 | 0 | 2 | 8 |
7,182 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.LabeledMarker
|
class LabeledMarker:
def __init__(self, new_id, pos, size=0.0, param = 0, residual=0.0):
self.id_num=new_id
self.pos = pos
self.size = size
self.param = param
self.residual = residual
self.marker_num=-1
if str(type(size)) == "<class 'tuple'>":
self.size=size[0]
def __decode_marker_id(self):
model_id = self.id_num >> 16
marker_id = self.id_num & 0x0000ffff
return model_id, marker_id
def __decode_param(self):
occluded = ( self.param & 0x01 ) != 0
point_cloud_solved = ( self.param & 0x02 ) != 0
model_solved = ( self.param & 0x04 ) != 0
return occluded,point_cloud_solved, model_solved
def get_as_string(self, tab_str, level):
out_tab_str = get_tab_str(tab_str, level)
model_id, marker_id = self.__decode_marker_id()
out_str = ""
out_str+="%sLabeled Marker"%out_tab_str
if(self.marker_num > -1):
out_str+=" %d"%self.marker_num
out_str+=":\n"
out_str += "%sID : [MarkerID: %3.1d] [ModelID: %3.1d]\n"%(out_tab_str, marker_id,model_id)
out_str += "%spos : [%3.2f, %3.2f, %3.2f]\n"%(out_tab_str, self.pos[0],self.pos[1],self.pos[2])
out_str += "%ssize : [%3.2f]\n"%(out_tab_str, self.size)
out_str += "%serr : [%3.2f]\n"%(out_tab_str, self.residual)
occluded, point_cloud_solved, model_solved = self.__decode_param()
out_str += "%soccluded : [%3.1d]\n"%(out_tab_str, occluded)
out_str += "%spoint_cloud_solved : [%3.1d]\n"%(out_tab_str, point_cloud_solved)
out_str += "%smodel_solved : [%3.1d]\n"%(out_tab_str, model_solved)
return out_str
|
class LabeledMarker:
def __init__(self, new_id, pos, size=0.0, param = 0, residual=0.0):
pass
def __decode_marker_id(self):
pass
def __decode_param(self):
pass
def get_as_string(self, tab_str, level):
pass
| 5 | 0 | 9 | 1 | 9 | 0 | 2 | 0 | 0 | 2 | 0 | 0 | 4 | 6 | 4 | 4 | 41 | 5 | 36 | 20 | 31 | 0 | 36 | 20 | 31 | 2 | 0 | 1 | 6 |
7,183 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.LabeledMarkerData
|
class LabeledMarkerData:
def __init__(self):
self.labeled_marker_list=[]
def add_labeled_marker(self, labeled_marker):
self.labeled_marker_list.append(copy.deepcopy(labeled_marker))
return len(self.labeled_marker_list)
def get_labeled_marker_count(self):
return len(self.labeled_marker_list)
def get_as_string(self, tab_str = " ", level = 0):
out_tab_str = get_tab_str(tab_str, level)
out_tab_str2 = get_tab_str(tab_str, level+1)
out_str = ""
labeled_marker_count = len(self.labeled_marker_list)
out_str += "%sLabeled Marker Count:%3.1d\n"%(out_tab_str, labeled_marker_count )
for i in range( 0, labeled_marker_count ):
labeled_marker = self.labeled_marker_list[i]
labeled_marker.marker_num=i
out_str += labeled_marker.get_as_string(tab_str, level+2)
return out_str
|
class LabeledMarkerData:
def __init__(self):
pass
def add_labeled_marker(self, labeled_marker):
pass
def get_labeled_marker_count(self):
pass
def get_as_string(self, tab_str = " ", level = 0):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 4 | 1 | 4 | 4 | 23 | 4 | 19 | 12 | 14 | 0 | 19 | 12 | 14 | 2 | 0 | 1 | 5 |
7,184 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.LegacyMarkerData
|
class LegacyMarkerData:
def __init__(self):
self.marker_pos_list=[]
def add_pos(self, pos):
self.marker_pos_list.append(copy.deepcopy(pos))
return len(self.marker_pos_list)
def get_marker_count(self):
return len(self.marker_pos_list)
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_tab_str2 = get_tab_str(tab_str, level+1)
out_str=""
marker_count = len(self.marker_pos_list)
out_str+="%sLegacy Marker Count :%3.1d\n"%(out_tab_str, marker_count)
for i in range(marker_count):
pos = self.marker_pos_list[i]
out_str+="%sMarker %3.1d pos : [x=%3.2f,y=%3.2f,z=%3.2f]\n"%(out_tab_str2,i,pos[0], pos[1], pos[2])
return out_str
|
class LegacyMarkerData:
def __init__(self):
pass
def add_pos(self, pos):
pass
def get_marker_count(self):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 4 | 1 | 4 | 4 | 21 | 3 | 18 | 12 | 13 | 0 | 18 | 12 | 13 | 2 | 0 | 1 | 5 |
7,185 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.MarkerData
|
class MarkerData:
def __init__(self):
self.model_name=""
self.marker_pos_list=[]
def set_model_name(self, model_name):
self.model_name = model_name
def add_pos(self, pos):
self.marker_pos_list.append(copy.deepcopy(pos))
return len(self.marker_pos_list)
def get_num_points(self):
return len(self.marker_pos_list)
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_tab_str2 = get_tab_str(tab_str, level+1)
out_str=""
out_str+="%sMarkerData:\n"%out_tab_str
if self.model_name != "":
out_str+="%sModel Name : %s\n"%(out_tab_str, get_as_string(self.model_name))
marker_count = len(self.marker_pos_list)
out_str+="%sMarker Count :%3.1d\n"%(out_tab_str, marker_count)
for i in range(marker_count):
pos = self.marker_pos_list[i]
out_str+="%sMarker %3.1d pos : [x=%3.2f,y=%3.2f,z=%3.2f]\n"%(out_tab_str2,i,pos[0], pos[1], pos[2])
return out_str
|
class MarkerData:
def __init__(self):
pass
def set_model_name(self, model_name):
pass
def add_pos(self, pos):
pass
def get_num_points(self):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 6 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 5 | 2 | 5 | 5 | 30 | 6 | 24 | 14 | 18 | 0 | 24 | 14 | 18 | 3 | 0 | 1 | 7 |
7,186 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.MarkerSetData
|
class MarkerSetData:
def __init__(self):
self.marker_data_list=[]
self.unlabeled_markers=MarkerData()
self.unlabeled_markers.set_model_name("")
def add_marker_data(self, marker_data):
self.marker_data_list.append(copy.deepcopy(marker_data))
return len(self.marker_data_list)
def add_unlabeled_marker(self, pos):
self.unlabeled_markers.add_pos(pos)
def get_marker_set_count(self):
return len(self.marker_data_list)
def get_unlabeled_marker_count(self):
return self.unlabeled_markers.get_num_points()
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_str=""
# Labeled markers count
marker_data_count = len(self.marker_data_list)
out_str+= "%sMarkerset Count:%3.1d\n"% (out_tab_str,marker_data_count)
for marker_data in self.marker_data_list:
out_str += marker_data.get_as_string(tab_str,level+1)
# Unlabeled markers count (4 bytes)
unlabeled_markers_count = self.unlabeled_markers.get_num_points()
out_str += "%sUnlabeled Marker Count:%3.1d\n"%(out_tab_str, unlabeled_markers_count )
out_str += self.unlabeled_markers.get_as_string(tab_str,level+1)
return out_str
|
class MarkerSetData:
def __init__(self):
pass
def add_marker_data(self, marker_data):
pass
def add_unlabeled_marker(self, pos):
pass
def get_marker_set_count(self):
pass
def get_unlabeled_marker_count(self):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 7 | 0 | 5 | 1 | 4 | 0 | 1 | 0.08 | 0 | 1 | 1 | 0 | 6 | 2 | 6 | 6 | 35 | 8 | 25 | 14 | 18 | 2 | 25 | 14 | 18 | 2 | 0 | 1 | 7 |
7,187 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.MoCapData
|
class MoCapData:
def __init__(self):
#Packet Parts
self.prefix_data = None
self.marker_set_data = None
self.legacy_other_markers = None
self.rigid_body_data = None
self.asset_data = None
self.skeleton_data = None
self.labeled_marker_data = None
self.force_plate_data = None
self.device_data = None
self.suffix_data = None
def set_prefix_data(self, new_prefix_data):
self.prefix_data = new_prefix_data
def set_marker_set_data(self, new_marker_set_data):
self.marker_set_data = new_marker_set_data
def set_legacy_other_markers(self, new_marker_set_data):
self.legacy_other_markers = new_marker_set_data
def set_rigid_body_data(self, new_rigid_body_data):
self.rigid_body_data = new_rigid_body_data
def set_skeleton_data(self, new_skeleton_data):
self.skeleton_data = new_skeleton_data
def set_asset_data(self, new_asset_data):
self.asset_data=new_asset_data
def set_labeled_marker_data(self, new_labeled_marker_data):
self.labeled_marker_data = new_labeled_marker_data
def set_force_plate_data(self, new_force_plate_data):
self.force_plate_data = new_force_plate_data
def set_device_data(self, new_device_data):
self.device_data = new_device_data
def set_suffix_data(self, new_suffix_data):
self.suffix_data = new_suffix_data
def get_as_string(self, tab_str = " ", level = 0):
out_tab_str = get_tab_str(tab_str, level)
out_str=""
out_str+= "%sMoCap Frame Begin\n%s-----------------\n"%(out_tab_str,out_tab_str)
if not self.prefix_data == None:
out_str+=self.prefix_data.get_as_string()
else:
out_str+="%sNo Prefix Data Set\n"%(out_tab_str)
if not self.marker_set_data == None:
out_str+=self.marker_set_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Markerset Data Set\n"%(out_tab_str)
if not self.rigid_body_data == None:
out_str+=self.rigid_body_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Rigid Body Data Set\n"%(out_tab_str)
if not self.skeleton_data == None:
out_str+=self.skeleton_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Skeleton Data Set\n"%(out_tab_str)
if not self.asset_data == None:
out_str+=self.asset_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Asset Data Set\n"%(out_tab_str)
if not self.labeled_marker_data == None:
out_str+=self.labeled_marker_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Labeled Marker Data Set\n"%(out_tab_str)
if not self.force_plate_data == None:
out_str+=self.force_plate_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Force Plate Data Set\n"%(out_tab_str)
if not self.device_data == None:
out_str+=self.device_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Device Data Set\n"%(out_tab_str)
if not self.suffix_data == None:
out_str+=self.suffix_data.get_as_string(tab_str, level+1)
else:
out_str+="%sNo Suffix Data Set\n"%(out_tab_str)
out_str+= "%sMoCap Frame End\n%s-----------------\n"%(out_tab_str,out_tab_str)
return out_str
|
class MoCapData:
def __init__(self):
pass
def set_prefix_data(self, new_prefix_data):
pass
def set_marker_set_data(self, new_marker_set_data):
pass
def set_legacy_other_markers(self, new_marker_set_data):
pass
def set_rigid_body_data(self, new_rigid_body_data):
pass
def set_skeleton_data(self, new_skeleton_data):
pass
def set_asset_data(self, new_asset_data):
pass
def set_labeled_marker_data(self, new_labeled_marker_data):
pass
def set_force_plate_data(self, new_force_plate_data):
pass
def set_device_data(self, new_device_data):
pass
def set_suffix_data(self, new_suffix_data):
pass
def get_as_string(self, tab_str = " ", level = 0):
pass
| 13 | 0 | 7 | 1 | 6 | 0 | 2 | 0.01 | 0 | 0 | 0 | 0 | 12 | 10 | 12 | 12 | 97 | 22 | 74 | 25 | 61 | 1 | 65 | 25 | 52 | 10 | 0 | 1 | 21 |
7,188 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.RigidBody
|
class RigidBody:
def __init__(self, new_id, pos, rot):
self.id_num = new_id
self.pos=pos
self.rot=rot
self.rb_marker_list=[]
self.tracking_valid = False
self.error = 0.0
self.marker_num = -1
def add_rigid_body_marker(self, rigid_body_marker):
self.rb_marker_list.append(copy.deepcopy(rigid_body_marker))
return len(self.rb_marker_list)
def get_as_string(self, tab_str=0, level=0):
out_tab_str = get_tab_str(tab_str, level)
out_tab_str2 = get_tab_str(tab_str, level+1)
out_str=""
# header
out_str += "%sRigid Body :"% (out_tab_str)
if ( self.marker_num > -1 ):
out_str += " %3.1d"% (self.marker_num)
out_str += "\n"
out_str += "%s ID : %3.1d\n"% (out_tab_str, self.id_num)
# Position and orientation
out_str += "%s Position : [%3.2f, %3.2f, %3.2f]\n"% (out_tab_str, self.pos[0], self.pos[1], self.pos[2] )
out_str += "%s Orientation : [%3.2f, %3.2f, %3.2f, %3.2f]\n"% (out_tab_str, self.rot[0], self.rot[1], self.rot[2], self.rot[3] )
marker_count = len(self.rb_marker_list)
marker_count_range = range( 0, marker_count )
# Marker Data
if marker_count > 0:
out_str += "%s Marker Count : %3.1d\n"%(out_tab_str, marker_count )
for i in marker_count_range:
rbmarker = self.rb_marker_list[i]
rbmarker.marker_num=i
out_str += rbmarker.get_as_string(tab_str, level+2)
out_str += "%s Marker Error : %3.2f\n"% (out_tab_str, self.error)
# Valid Tracking
tf_string = 'False'
if self.tracking_valid:
tf_string = 'True'
out_str += "%sTracking Valid: %s\n"%(out_tab_str, tf_string)
return out_str
|
class RigidBody:
def __init__(self, new_id, pos, rot):
pass
def add_rigid_body_marker(self, rigid_body_marker):
pass
def get_as_string(self, tab_str=0, level=0):
pass
| 4 | 0 | 16 | 2 | 12 | 1 | 2 | 0.11 | 0 | 1 | 0 | 0 | 3 | 7 | 3 | 3 | 51 | 10 | 37 | 19 | 33 | 4 | 37 | 19 | 33 | 5 | 0 | 2 | 7 |
7,189 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.RigidBodyData
|
class RigidBodyData:
def __init__(self):
self.rigid_body_list=[]
def add_rigid_body(self, rigid_body):
self.rigid_body_list.append(copy.deepcopy(rigid_body))
return len(self.rigid_body_list)
def get_rigid_body_count(self):
return len(self.rigid_body_list)
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_str=""
rigid_body_count=len(self.rigid_body_list)
out_str += "%sRigid Body Count: %3.1d\n"%(out_tab_str, rigid_body_count)
rb_num=0
for rigid_body in self.rigid_body_list:
rigid_body.marker_num=rb_num
out_str += rigid_body.get_as_string(tab_str, level+1)
rb_num+=1
return out_str
|
class RigidBodyData:
def __init__(self):
pass
def add_rigid_body(self, rigid_body):
pass
def get_rigid_body_count(self):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 4 | 4 | 25 | 6 | 19 | 11 | 14 | 0 | 19 | 11 | 14 | 2 | 0 | 1 | 5 |
7,190 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.RigidBodyMarker
|
class RigidBodyMarker:
def __init__(self):
self.pos = [0.0,0.0,0.0]
self.id_num = 0
self.size = 0
self.error = 0
self.marker_num = -1;
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_str = ""
out_str += "%sRBMarker:"%( out_tab_str)
if ( self.marker_num > -1 ):
out_str += " %3.1d"%( self.marker_num )
out_str += "\n"
out_str += "%sPosition: [%3.2f %3.2f %3.2f]\n"%( out_tab_str, self.pos[0], self.pos[1], self.pos[2] )
out_str += "%sID : %3.1d\n"%(out_tab_str, self.id_num)
out_str += "%sSize : %3.1d\n"%(out_tab_str, self.size)
return out_str
|
class RigidBodyMarker:
def __init__(self):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 3 | 0 | 9 | 1 | 9 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2 | 5 | 2 | 2 | 20 | 2 | 18 | 10 | 15 | 0 | 18 | 10 | 15 | 2 | 0 | 1 | 3 |
7,191 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.Skeleton
|
class Skeleton:
def __init__(self, new_id=0):
self.id_num=new_id
self.rigid_body_list=[]
def add_rigid_body(self, rigid_body):
self.rigid_body_list.append(copy.deepcopy(rigid_body))
return len(self.rigid_body_list)
def get_as_string(self, tab_str=" ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_tab_str2 = get_tab_str(tab_str, level+1)
out_str=""
out_str+="%sID: %3.1d\n"%(out_tab_str, self.id_num)
rigid_body_count=len(self.rigid_body_list)
out_str += "%sRigid Body Count: %3.1d\n"%(out_tab_str, rigid_body_count)
for rb_num in range(rigid_body_count):
self.rigid_body_list[rb_num].marker_num = rb_num
out_str += self.rigid_body_list[rb_num].get_as_string(tab_str, level+2)
return out_str
|
class Skeleton:
def __init__(self, new_id=0):
pass
def add_rigid_body(self, rigid_body):
pass
def get_as_string(self, tab_str=" ", level=0):
pass
| 4 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 3 | 2 | 3 | 3 | 22 | 4 | 18 | 11 | 14 | 0 | 18 | 11 | 14 | 2 | 0 | 1 | 4 |
7,192 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.SkeletonData
|
class SkeletonData:
def __init__(self):
self.skeleton_list=[]
def add_skeleton(self, new_skeleton):
self.skeleton_list.append(copy.deepcopy(new_skeleton))
def get_skeleton_count(self):
return len(self.skeleton_list)
def get_as_string(self, tab_str = " ", level=0):
out_tab_str = get_tab_str(tab_str, level)
out_tab_str2 = get_tab_str(tab_str, level+1)
out_str = ""
skeleton_count = len(self.skeleton_list)
out_str += "%sSkeleton Count: %3.1d\n"%(out_tab_str, skeleton_count)
for skeleton_num in range(skeleton_count):
out_str += "%sSkeleton %3.1d\n"%(out_tab_str2, skeleton_num)
out_str += self.skeleton_list[skeleton_num].get_as_string(tab_str, level+2)
return out_str
|
class SkeletonData:
def __init__(self):
pass
def add_skeleton(self, new_skeleton):
pass
def get_skeleton_count(self):
pass
def get_as_string(self, tab_str = " ", level=0):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 4 | 1 | 4 | 4 | 24 | 7 | 17 | 11 | 12 | 0 | 17 | 11 | 12 | 2 | 0 | 1 | 5 |
7,193 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/__init__.py
|
MAVProxy.modules.mavproxy_optitrack.optitrack
|
class optitrack(mp_module.MPModule):
def __init__(self, mpstate):
"""Initialise module"""
super(optitrack, self).__init__(mpstate, "optitrack", "optitrack")
self.optitrack_settings = mp_settings.MPSettings(
[('server', str, '127.0.0.1'),
('client', str, '127.0.0.1'),
('msg_intvl_ms', int, 75),
('obj_id', int, 1),
('print_lv', int, 0),
('multicast', bool, True)]
)
self.add_command('optitrack', self.cmd_optitrack, "optitrack control", ['<start>', '<stop>', 'set (OPTITRACKSETTING)'])
self.streaming_client = NatNetClient.NatNetClient()
# Configure the streaming client to call our rigid body handler on the emulator to send data out.
self.streaming_client.rigid_body_listener = self.receive_rigid_body_frame
self.last_msg_time = 0
self.started = False
# This is a callback function that gets connected to the NatNet client. It is called once per rigid body per frame
def receive_rigid_body_frame(self, new_id, position, rotation):
if (new_id == self.optitrack_settings.obj_id):
now = time.time()
if (now - self.last_msg_time) > (self.optitrack_settings.msg_intvl_ms * 0.001):
time_us = int(now * 1.0e6)
self.master.mav.att_pos_mocap_send(time_us, (rotation[3], rotation[0], rotation[2], -rotation[1]), position[0], position[2], -position[1])
self.last_msg_time = now
def usage(self):
'''show help on command line options'''
return "Usage: optitrack <start|stop|set>"
def cmd_start(self):
self.streaming_client.set_client_address(self.optitrack_settings.client)
self.streaming_client.set_server_address(self.optitrack_settings.server)
self.streaming_client.set_print_level(self.optitrack_settings.print_lv)
self.streaming_client.set_use_multicast(self.optitrack_settings.multicast)
self.streaming_client.run()
self.started = True
def cmd_optitrack(self, args):
'''control behaviour of the module'''
if len(args) == 0:
print(self.usage())
elif args[0] == "start":
self.cmd_start()
elif args[0] == "stop":
if self.started:
self.started = False
self.streaming_client.shutdown()
elif args[0] == "set":
self.optitrack_settings.command(args[1:])
else:
print(self.usage())
|
class optitrack(mp_module.MPModule):
def __init__(self, mpstate):
'''Initialise module'''
pass
def receive_rigid_body_frame(self, new_id, position, rotation):
pass
def usage(self):
'''show help on command line options'''
pass
def cmd_start(self):
pass
def cmd_optitrack(self, args):
'''control behaviour of the module'''
pass
| 6 | 3 | 10 | 0 | 9 | 1 | 2 | 0.11 | 1 | 6 | 2 | 0 | 5 | 4 | 5 | 43 | 54 | 4 | 45 | 12 | 39 | 5 | 34 | 12 | 28 | 6 | 2 | 2 | 12 |
7,194 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_optitrack/MoCapData.py
|
MAVProxy.modules.mavproxy_optitrack.MoCapData.FramePrefixData
|
class FramePrefixData:
def __init__(self, frame_number):
self.frame_number=frame_number
def get_as_string(self,tab_str=" ", level = 0):
out_tab_str = get_tab_str(tab_str, level)
out_str = "%sFrame #: %3.1d\n"%(out_tab_str,self.frame_number)
return out_str
|
class FramePrefixData:
def __init__(self, frame_number):
pass
def get_as_string(self,tab_str=" ", level = 0):
pass
| 3 | 0 | 3 | 0 | 3 | 1 | 1 | 0.14 | 0 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 8 | 1 | 7 | 6 | 4 | 1 | 7 | 6 | 4 | 1 | 0 | 0 | 2 |
7,195 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_osd.py
|
MAVProxy.modules.mavproxy_osd.osd
|
class osd(mp_module.MPModule):
def __init__(self, mpstate):
"""Initialise OSD module"""
super(osd, self).__init__(mpstate, "osd", "")
self.request_id = 1
self.add_command('osd', self.cmd_osd, "OSD module",
['param-set <5|6> <1|2|3|4|5|6|7|8|9> (PARAMETER) (TYPES)',
'param-show <5|6> <1|2|3|4|5|6|7|8|9>'
])
self.add_completion_function('(TYPES)', self.param_type_completion)
self.type_map = {
mavutil.mavlink.OSD_PARAM_NONE : "NONE",
mavutil.mavlink.OSD_PARAM_SERIAL_PROTOCOL : "SERIAL_PROTOCOL",
mavutil.mavlink.OSD_PARAM_SERVO_FUNCTION : "SERVO_FUNCTION",
mavutil.mavlink.OSD_PARAM_AUX_FUNCTION : "AUX_FUNCTION",
mavutil.mavlink.OSD_PARAM_FLIGHT_MODE : "FLIGHT_MODE",
mavutil.mavlink.OSD_PARAM_FAILSAFE_ACTION : "FAILSAFE_ACTION",
mavutil.mavlink.OSD_PARAM_FAILSAFE_ACTION_1 : "FAILSAFE_ACTION_1",
mavutil.mavlink.OSD_PARAM_FAILSAFE_ACTION_2 : "FAILSAFE_ACTION_2" }
self.invtype_map = { v : k for k, v in self.type_map.items()}
self.param_list = {}
def usage(self):
'''show help on command line options'''
return "Usage: osd <param-set|param-show|set>"
def cmd_osd(self, args):
'''control behaviour of the OSD module'''
if len(args) == 0:
print(self.usage())
elif args[0] == "param-set":
self.param_set(args[1:])
elif args[0] == "param-show":
self.param_show(args[1:])
else:
print(self.usage())
def param_set(self, args):
'''sets an OSD parameter'''
if len(args) < 3 or len(args) > 6:
print("param-set <screen> <index> <name> (<type> | <min> <max> <increment>)")
return
screen = int(args[0], 0)
index = int(args[1], 0)
name = args[2]
type = mavutil.mavlink.OSD_PARAM_NONE
min_value = 0.
max_value = 0.
increment = 0.
# config type implies the ranges are pre-defined
if len(args) > 3:
type = self.string_to_config_type(args[3])
# can't have config type and ranges
if type is not None and len(args) > 4:
print("param-set <screen> <index> <name> (<type> | <min> <max> <increment>)")
return
if len(args) > 3 and type is None:
type = mavutil.mavlink.OSD_PARAM_NONE
min_value = float(args[3])
if len(args) > 4:
max_value = float(args[4])
if len(args) > 5:
increment = float(args[5])
if sys.version_info.major >= 3:
name = bytearray(name, 'ascii')
self.master.mav.osd_param_config_send(self.target_system,
self.target_component,
self.request_id,
screen,
index,
name,
type,
min_value,
max_value,
increment)
self.request_id += 1
def param_show(self, args):
'''show an OSD parameter or list of parameters'''
if len(args) == 0:
for screen in range(5, 7):
for index in range(1, 10):
self.master.mav.osd_param_show_config_send(self.target_system,
self.target_component,
self.request_id,
screen,
index)
self.request_id += 1
return
elif len(args) == 1:
screen = int(args[0], 0)
for index in range(1, 10):
self.master.mav.osd_param_show_config_send(self.target_system,
self.target_component,
self.request_id,
screen,
index)
self.request_id += 1
return
elif len(args) != 2:
print("param-show <screen> <index>")
return
screen = int(args[0], 0)
index = int(args[1], 0)
self.master.mav.osd_param_show_config_send(self.target_system,
self.target_component,
self.request_id,
screen,
index)
self.request_id += 1
def mavlink_packet(self, m):
'''handle mavlink packets'''
mtype = m.get_type()
if mtype == "OSD_PARAM_CONFIG_REPLY" or mtype == "OSD_PARAM_SHOW_CONFIG_REPLY":
if m.result == mavutil.mavlink.OSD_PARAM_INVALID_PARAMETER:
print("OSD request %u failed: invalid parameter" % (m.request_id))
elif m.result != 0:
print("OSD request %u failed: %u" % (m.request_id, m.result))
else:
if mtype == "OSD_PARAM_CONFIG_REPLY":
print("OSD parameter set")
else:
print("%s %f %f %f %s" % (m.param_id, m.min_value, m.max_value, m.increment,
self.config_type_to_string(m.config_type)))
def config_type_to_string(self, config_type):
'''convert config type to a string'''
if config_type in self.type_map:
return self.type_map[config_type]
return None
def string_to_config_type(self, config_str):
'''convert a string to a config type'''
if config_str in self.invtype_map:
return self.invtype_map[config_str]
return None
def param_type_completion(self, text):
'''return list of param-set type completions'''
return self.invtype_map.keys()
|
class osd(mp_module.MPModule):
def __init__(self, mpstate):
'''Initialise OSD module'''
pass
def usage(self):
'''show help on command line options'''
pass
def cmd_osd(self, args):
'''control behaviour of the OSD module'''
pass
def param_set(self, args):
'''sets an OSD parameter'''
pass
def param_show(self, args):
'''show an OSD parameter or list of parameters'''
pass
def mavlink_packet(self, m):
'''handle mavlink packets'''
pass
def config_type_to_string(self, config_type):
'''convert config type to a string'''
pass
def string_to_config_type(self, config_str):
'''convert a string to a config type'''
pass
def param_type_completion(self, text):
'''return list of param-set type completions'''
pass
| 10 | 9 | 15 | 1 | 13 | 1 | 3 | 0.09 | 1 | 5 | 0 | 0 | 9 | 4 | 9 | 47 | 148 | 15 | 122 | 24 | 112 | 11 | 81 | 24 | 71 | 8 | 2 | 3 | 31 |
7,196 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_param.py
|
MAVProxy.modules.mavproxy_param.ParamModule
|
class ParamModule(mp_module.MPModule):
def __init__(self, mpstate, **kwargs):
super(ParamModule, self).__init__(mpstate, "param", "parameter handling", public=True, multi_vehicle=True)
self.xml_filepath = kwargs.get("xml-filepath", None)
self.pstate = {}
self.check_new_target_system()
self.menu_added_console = False
bitmask_indexes = "|".join(str(x) for x in range(32))
self.add_command(
'param', self.cmd_param, "parameter handling", [
"<download|status>",
"<set|show|fetch|ftp|help|apropos|revert> (PARAMETER)",
"<load|save|savechanged|diff|forceload|ftpload> (FILENAME)",
"<set_xml_filepath> (FILEPATH)",
f"<bitmask> <toggle|set|clear> (PARAMETER) <{bitmask_indexes}>"
],
)
if mp_util.has_wxpython:
self.menu = MPMenuSubMenu(
'Parameter',
items=[
MPMenuItem('Editor', 'Editor', '# module load paramedit'),
MPMenuItem('Fetch', 'Fetch', '# param fetch'),
MPMenuItem('Load', 'Load', '# param load ',
handler=MPMenuCallFileDialog(
flags=('open',),
title='Param Load',
wildcard='ParmFiles(*.parm,*.param)|*.parm;*.param')),
MPMenuItem('Save', 'Save', '# param save ',
handler=MPMenuCallFileDialog(
flags=('save', 'overwrite_prompt'),
title='Param Save',
wildcard='ParmFiles(*.parm,*.param)|*.parm;*.param')),
MPMenuItem('FTP', 'FTP', '# param ftp'),
MPMenuItem('Update Metadata', 'Update Metadata', '# param download'),
],
)
def get_component_id_list(self, system_id):
'''get list of component IDs with parameters for a given system ID'''
ret = []
for (s, c) in self.mpstate.mav_param_by_sysid.keys():
if s == system_id:
ret.append(c)
return ret
def add_new_target_system(self, sysid):
'''handle a new target_system'''
if sysid in self.pstate:
return
if sysid not in self.mpstate.mav_param_by_sysid:
self.mpstate.mav_param_by_sysid[sysid] = mavparm.MAVParmDict()
self.new_sysid_timestamp = time.time()
fname = 'mav.parm'
if sysid not in [(0, 0), (1, 1), (1, 0)]:
fname = 'mav_%u_%u.parm' % (sysid[0], sysid[1])
self.pstate[sysid] = ParamState(
self.mpstate.mav_param_by_sysid[sysid],
self.logdir,
self.vehicle_name,
fname,
self.mpstate,
sysid,
)
if self.continue_mode and self.logdir is not None:
parmfile = os.path.join(self.logdir, fname)
if os.path.exists(parmfile):
self.mpstate.mav_param.load(parmfile)
self.pstate[sysid].mav_param_set = set(self.mav_param.keys())
self.pstate[sysid].param_help.xml_filepath = self.xml_filepath
def get_sysid(self):
'''get sysid tuple to use for parameters'''
component = self.target_component
if component == 0:
component = 1
return (self.target_system, component)
def check_new_target_system(self):
'''handle a new target_system'''
sysid = self.get_sysid()
if sysid in self.pstate:
return
self.add_new_target_system(sysid)
def param_status(self):
sysid = self.get_sysid()
pset, pcount = self.pstate[sysid].status(self.master, self.mpstate)
return (pset, pcount)
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
sysid = (m.get_srcSystem(), m.get_srcComponent())
self.add_new_target_system(sysid)
self.pstate[sysid].handle_mavlink_packet(self.master, m)
def idle_task(self):
'''handle missing parameters'''
self.check_new_target_system()
sysid = self.get_sysid()
self.pstate[sysid].vehicle_name = self.vehicle_name
self.pstate[sysid].param_help.vehicle_name = self.vehicle_name
self.pstate[sysid].fetch_check(self.master)
if self.module('console') is not None:
if not self.menu_added_console:
self.menu_added_console = True
self.module('console').add_menu(self.menu)
else:
self.menu_added_console = False
self.run_parameter_set_queues()
def run_parameter_set_queues(self):
for pstate in self.pstate.values():
pstate.run_parameter_set_queue()
def cmd_param(self, args):
'''control parameters'''
self.check_new_target_system()
sysid = self.get_sysid()
self.pstate[sysid].handle_command(self.master, self.mpstate, args)
def fetch_all(self):
'''force fetch of all parameters'''
self.check_new_target_system()
sysid = self.get_sysid()
self.pstate[sysid].fetch_all(self.master)
|
class ParamModule(mp_module.MPModule):
def __init__(self, mpstate, **kwargs):
pass
def get_component_id_list(self, system_id):
'''get list of component IDs with parameters for a given system ID'''
pass
def add_new_target_system(self, sysid):
'''handle a new target_system'''
pass
def get_sysid(self):
'''get sysid tuple to use for parameters'''
pass
def check_new_target_system(self):
'''handle a new target_system'''
pass
def param_status(self):
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def idle_task(self):
'''handle missing parameters'''
pass
def run_parameter_set_queues(self):
pass
def cmd_param(self, args):
'''control parameters'''
pass
def fetch_all(self):
'''force fetch of all parameters'''
pass
| 12 | 8 | 11 | 0 | 10 | 1 | 2 | 0.13 | 1 | 8 | 4 | 0 | 11 | 5 | 11 | 49 | 128 | 12 | 108 | 31 | 96 | 14 | 74 | 31 | 62 | 6 | 2 | 2 | 24 |
7,197 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_param.py
|
MAVProxy.modules.mavproxy_param.ParamState
|
class ParamState:
'''this class is separated to make it possible to use the parameter
functions on a secondary connection'''
def __init__(self, mav_param, logdir, vehicle_name, parm_file, mpstate, sysid):
self.mav_param_set = set()
self.mav_param_count = 0
self.param_period = mavutil.periodic_event(1)
self.fetch_one = dict()
self.mav_param = mav_param
self.logdir = logdir
self.vehicle_name = vehicle_name
self.parm_file = parm_file
self.fetch_set = None
self.new_sysid_timestamp = time.time()
self.autopilot_type_by_sysid = {}
self.param_types = {}
self.ftp_failed = False
self.ftp_started = False
self.ftp_count = None
self.ftp_send_param = None
self.mpstate = mpstate
self.sysid = sysid
self.param_help = param_help.ParamHelp()
self.param_help.vehicle_name = vehicle_name
self.default_params = None
self.watch_patterns = set()
# dictionary of ParamSet objects we are processing:
self.parameters_to_set = {}
# a Queue which onto which ParamSet objects can be pushed in a
# thread-safe manner:
self.parameters_to_set_input_queue = Queue.Queue()
class ParamSet():
'''class to hold information about a parameter set being attempted'''
def __init__(self, master, name, value, param_type=None, attempts=None):
self.master = master
self.name = name
self.value = value
self.param_type = param_type
self.attempts_remaining = attempts
self.retry_interval = 1 # seconds
self.last_value_received = None
if self.attempts_remaining is None:
self.attempts_remaining = 3
self.request_sent = 0 # this is a timestamp
def normalize_parameter_for_param_set_send(self, name, value, param_type):
'''uses param_type to convert value into a value suitable for passing
into the mavlink param_set_send binding. Note that this
is a copy of a method in pymavlink, in case the user has
an older version of that library.
'''
if param_type is not None and param_type != mavutil.mavlink.MAV_PARAM_TYPE_REAL32:
# need to encode as a float for sending
if param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT8:
vstr = struct.pack(">xxxB", int(value))
elif param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT8:
vstr = struct.pack(">xxxb", int(value))
elif param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT16:
vstr = struct.pack(">xxH", int(value))
elif param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT16:
vstr = struct.pack(">xxh", int(value))
elif param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT32:
vstr = struct.pack(">I", int(value))
elif param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT32:
vstr = struct.pack(">i", int(value))
else:
print("can't send %s of type %u" % (name, param_type))
return None
numeric_value, = struct.unpack(">f", vstr)
else:
if isinstance(value, str) and value.lower().startswith('0x'):
numeric_value = int(value[2:], 16)
else:
try:
numeric_value = float(value)
except ValueError:
print(f"can't convert {name} ({value}, {type(value)}) to float")
return None
return numeric_value
def send_set(self):
numeric_value = self.normalize_parameter_for_param_set_send(self.name, self.value, self.param_type)
if numeric_value is None:
print(f"can't send {self.name} of type {self.param_type}")
self.attempts_remaining = 0
return
# print(f"Sending set attempts-remaining={self.attempts_remaining}")
self.master.param_set_send(
self.name.upper(),
numeric_value,
parm_type=self.param_type,
)
self.request_sent = time.time()
self.attempts_remaining -= 1
def expired(self):
if self.attempts_remaining > 0:
return False
return time.time() - self.request_sent > self.retry_interval
def due_for_retry(self):
if self.attempts_remaining <= 0:
return False
return time.time() - self.request_sent > self.retry_interval
def handle_PARAM_VALUE(self, m, value):
'''handle PARAM_VALUE packet m which has already been checked for a
match against self.name. Returns true if this Set is now
satisfied. value is the value extracted and potentially
manipulated from the packet
'''
self.last_value_received = value
if abs(value - float(self.value)) > 0.00001:
return False
return True
def print_expired_message(self):
reason = ""
if self.last_value_received is None:
reason = " (no PARAM_VALUE received)"
else:
reason = f" (invalid returned value {self.last_value_received})"
print(f"Failed to set {self.name} to {self.value}{reason}")
def run_parameter_set_queue(self):
# firstly move anything from the input queue into our
# collection of things to send:
try:
while True:
new_parameter_to_set = self.parameters_to_set_input_queue.get(block=False)
self.parameters_to_set[new_parameter_to_set.name] = new_parameter_to_set
except Empty:
pass
# now send any parameter-sets which are due to be sent out,
# either because they are new or because we need to retry:
count = 0
keys_to_remove = [] # remove entries after iterating the dict
for (key, parameter_to_set) in self.parameters_to_set.items():
if parameter_to_set.expired():
parameter_to_set.print_expired_message()
keys_to_remove.append(key)
continue
if not parameter_to_set.due_for_retry():
continue
# send parameter set:
parameter_to_set.send_set()
# rate-limit to 10 items per call:
count += 1
if count > 10:
break
# complete purging of expired parameter-sets:
for key in keys_to_remove:
del self.parameters_to_set[key]
def use_ftp(self):
'''return true if we should try ftp for download'''
if self.ftp_failed:
return False
return self.mpstate.settings.param_ftp
def handle_px4_param_value(self, m):
'''special handling for the px4 style of PARAM_VALUE'''
if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_REAL32:
# already right type
return m.param_value
is_px4_params = False
if m.get_srcComponent() in [mavutil.mavlink.MAV_COMP_ID_UDP_BRIDGE]:
# ESP8266 uses PX4 style parameters
is_px4_params = True
sysid = m.get_srcSystem()
if self.autopilot_type_by_sysid.get(sysid, -1) in [mavutil.mavlink.MAV_AUTOPILOT_PX4]:
is_px4_params = True
if not is_px4_params:
return m.param_value
# try to extract px4 param value
value = m.param_value
try:
v = struct.pack(">f", value)
except Exception:
return value
if m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT8:
value, = struct.unpack(">B", v[3:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT8:
value, = struct.unpack(">b", v[3:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT16:
value, = struct.unpack(">H", v[2:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT16:
value, = struct.unpack(">h", v[2:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_UINT32:
value, = struct.unpack(">I", v[0:])
elif m.param_type == mavutil.mavlink.MAV_PARAM_TYPE_INT32:
value, = struct.unpack(">i", v[0:])
# can't pack other types
# remember type for param set
self.param_types[m.param_id.upper()] = m.param_type
return value
def handle_mavlink_packet(self, master, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'PARAM_VALUE':
self.handle_mavlink_watch_param_value(master, m)
value = self.handle_px4_param_value(m)
param_id = "%.16s" % m.param_id
# Note: the xml specifies param_index is a uint16, so -1 in that field will show as 65535
# We accept both -1 and 65535 as 'unknown index' to future proof us against someday having that
# xml fixed.
if self.fetch_set is not None:
self.fetch_set.discard(m.param_index)
if m.param_index != -1 and m.param_index != 65535 and m.param_index not in self.mav_param_set:
added_new_parameter = True
self.mav_param_set.add(m.param_index)
else:
added_new_parameter = False
if m.param_count != -1:
self.mav_param_count = m.param_count
self.mav_param[str(param_id)] = value
if param_id in self.fetch_one and self.fetch_one[param_id] > 0:
self.fetch_one[param_id] -= 1
if isinstance(value, float):
print("%s = %.7f" % (param_id, value))
else:
print("%s = %s" % (param_id, str(value)))
if added_new_parameter and len(self.mav_param_set) == m.param_count:
print("Received %u parameters" % m.param_count)
if self.logdir is not None:
self.mav_param.save(os.path.join(self.logdir, self.parm_file), '*', verbose=True)
self.fetch_set = None
if self.fetch_set is not None and len(self.fetch_set) == 0:
self.fetch_check(master, force=True)
# if we were setting this parameter then check it's the
# value we want and, if so, stop setting the parameter
try:
if self.parameters_to_set[param_id].handle_PARAM_VALUE(m, value):
# print(f"removing set of param_id ({self.parameters_to_set[param_id].value} vs {value})")
del self.parameters_to_set[param_id]
except KeyError:
pass
elif m.get_type() == 'HEARTBEAT':
if m.get_srcComponent() == 1:
# remember autopilot types so we can handle PX4 parameters
self.autopilot_type_by_sysid[m.get_srcSystem()] = m.autopilot
def fetch_check(self, master, force=False):
'''check for missing parameters periodically'''
if self.param_period.trigger() or force:
if master is None:
return
if len(self.mav_param_set) == 0 and not self.ftp_started:
if not self.use_ftp():
master.param_fetch_all()
else:
self.ftp_start()
elif not self.ftp_started and self.mav_param_count != 0 and len(self.mav_param_set) != self.mav_param_count:
if master.time_since('PARAM_VALUE') >= 1 or force:
diff = set(range(self.mav_param_count)).difference(self.mav_param_set)
count = 0
while len(diff) > 0 and count < 10:
idx = diff.pop()
master.param_fetch_one(idx)
if self.fetch_set is None:
self.fetch_set = set()
self.fetch_set.add(idx)
count += 1
def param_use_xml_filepath(self, filepath):
self.param_help.xml_filepath = filepath
def param_set_xml_filepath(self, args):
self.param_use_xml_filepath(args[0])
def status(self, master, mpstate):
return (len(self.mav_param_set), self.mav_param_count)
def ftp_start(self):
'''start a ftp download of parameters'''
ftp = self.mpstate.module('ftp')
if ftp is None:
self.ftp_failed = True
self.ftp_started = False
return
self.ftp_started = True
self.ftp_count = None
ftp.cmd_get([
"@PARAM/param.pck?withdefaults=1",
],
callback=self.ftp_callback,
callback_progress=self.ftp_callback_progress,
)
def log_params(self, params):
'''log PARAM_VALUE messages so that we can extract parameters from a tlog when using ftp download'''
if not self.mpstate.logqueue:
return
usec = int(time.time() * 1.0e6)
idx = 0
mav = self.mpstate.master().mav
editor = self.mpstate.module('paramedit')
for (name, v, ptype) in params:
p = mavutil.mavlink.MAVLink_param_value_message(name,
float(v),
mavutil.mavlink.MAV_PARAM_TYPE_REAL32,
len(params),
idx)
idx += 1
# log PARAM_VALUE using the source vehicles sysid but MAV_COMP_ID_MISSIONPLANNER, to allow
# us to tell that it came from the GCS, but to not corrupt the sequence numbers
id_saved = (mav.srcSystem, mav.srcComponent)
mav.srcSystem = self.sysid[0]
mav.srcComponent = mavutil.mavlink.MAV_COMP_ID_MISSIONPLANNER
try:
buf = p.pack(mav)
self.mpstate.logqueue.put(bytearray(struct.pack('>Q', usec) + buf))
# also give to param editor so it can update for changes
if editor:
editor.mavlink_packet(p)
except Exception:
pass
(mav.srcSystem, mav.srcComponent) = id_saved
def ftp_callback_progress(self, fh, total_size):
'''callback as read progresses'''
if self.ftp_count is None and total_size >= 6:
ofs = fh.tell()
fh.seek(0)
buf = fh.read(6)
fh.seek(ofs)
magic2, num_params, total_params = struct.unpack("<HHH", buf)
if magic2 == 0x671b or magic2 == 0x671c:
self.ftp_count = total_params
# approximate count
if self.ftp_count is not None:
# each entry takes 11 bytes on average
per_entry_size = 11
done = min(int(total_size / per_entry_size), self.ftp_count-1)
self.mpstate.console.set_status('Params', 'Param %u/%u' % (done, self.ftp_count))
def ftp_callback(self, fh):
'''callback from ftp fetch of parameters'''
self.ftp_started = False
if fh is None:
# the fetch failed
self.ftp_failed = True
return
# magic = 0x671b
# magic_defaults = 0x671c
data = fh.read()
pdata = param_ftp.ftp_param_decode(data)
if pdata is None or len(pdata.params) == 0:
return
with_defaults = pdata.defaults is not None
self.param_types = {}
self.mav_param_set = set()
self.fetch_one = dict()
self.fetch_set = None
self.mav_param.clear()
total_params = len(pdata.params)
self.mav_param_count = total_params
idx = 0
for (name, v, ptype) in pdata.params:
# we need to set it to REAL32 to ensure we use write value for param_set
name = str(name.decode('utf-8'))
self.param_types[name] = mavutil.mavlink.MAV_PARAM_TYPE_REAL32
self.mav_param_set.add(idx)
self.mav_param[name] = v
idx += 1
self.ftp_failed = False
self.mpstate.console.set_status('Params', 'Param %u/%u' % (total_params, total_params))
print("Received %u parameters (ftp)" % total_params)
if self.logdir is not None:
self.mav_param.save(os.path.join(self.logdir, self.parm_file), '*', verbose=True)
self.log_params(pdata.params)
if with_defaults:
self.default_params = mavparm.MAVParmDict()
for (name, v, ptype) in pdata.defaults:
name = str(name.decode('utf-8'))
self.default_params[name] = v
if self.logdir:
defaults_path = os.path.join(self.logdir, "defaults.parm")
self.default_params.save(defaults_path, '*', verbose=False)
print("Saved %u defaults to %s" % (len(pdata.defaults), defaults_path))
def fetch_all(self, master):
'''force refetch of parameters'''
if not self.use_ftp():
master.param_fetch_all()
self.mav_param_set = set()
else:
self.ftp_start()
def param_diff(self, args):
'''handle param diff'''
wildcard = '*'
if len(args) < 1 or args[0].find('*') != -1:
defaults = self.default_params
if defaults is None and self.vehicle_name is not None:
filename = mp_util.dot_mavproxy("%s-defaults.parm" % self.vehicle_name)
if not os.path.exists(filename):
print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name)
return
defaults = mavparm.MAVParmDict()
defaults.load(filename)
if len(args) >= 1:
wildcard = args[0]
else:
filename = args[0]
if not os.path.exists(filename):
print("Can't find defaults file %s" % filename)
return
defaults = mavparm.MAVParmDict()
defaults.load(filename)
if len(args) == 2:
wildcard = args[1]
print("\nParameter Current Default")
for p in self.mav_param:
p = str(p).upper()
if p not in defaults:
continue
if self.mav_param[p] == defaults[p]:
continue
if fnmatch.fnmatch(p, wildcard.upper()):
s1 = "%f" % self.mav_param[p]
s2 = "%f" % defaults[p]
if s1 == s2:
continue
s = "%-16.16s %s %s" % (str(p), s1, s2)
if self.mpstate.settings.param_docs and self.vehicle_name is not None:
info = self.param_help.param_info(p, self.mav_param[p])
if info is not None:
s += " # %s" % info
info_default = self.param_help.param_info(p, defaults[p])
if info_default is not None:
s += " (DEFAULT: %s)" % info_default
print(s)
def param_savechanged(self, args):
'''handle param savechanged'''
if len(args) < 1:
filename = "changed.parm"
else:
filename = args[0]
defaults = self.default_params
if defaults is None:
print("No defaults available")
return
f = open(filename, "w")
count = 0
for p in self.mav_param:
p = str(p).upper()
if p not in defaults:
continue
if self.mav_param[p] == defaults[p]:
continue
s1 = "%f" % self.mav_param[p]
s2 = "%f" % defaults[p]
if s1 == s2:
continue
s = "%-16.16s %s" % (str(p), s1)
f.write("%s\n" % s)
count += 1
f.close()
print("Saved %u parameters to %s" % (count, filename))
def handle_mavlink_watch_param_value(self, master, m):
param_id = "%.16s" % m.param_id
for pattern in self.watch_patterns:
if fnmatch.fnmatch(param_id, pattern):
self.mpstate.console.writeln("> %s=%f" % (param_id, m.param_value))
def param_watch(self, master, args):
'''command to allow addition of watches for parameter changes'''
for pattern in args:
self.watch_patterns.add(pattern)
def param_unwatch(self, master, args):
'''command to allow removal of watches for parameter changes'''
for pattern in args:
self.watch_patterns.discard(pattern)
def param_watchlist(self, master, args):
'''command to show watch patterns for parameter changes'''
for pattern in self.watch_patterns:
self.mpstate.console.writeln("> %s" % (pattern))
def param_bitmask_modify(self, master, args):
'''command for performing bitmask actions on a parameter'''
BITMASK_ACTIONS = ['toggle', 'set', 'clear']
NUM_BITS_MAX = 32
# Ensure we have at least an action and a parameter
if len(args) < 2:
print("Not enough arguments")
print(f"param bitmask <{'/'.join(BITMASK_ACTIONS)}> <parameter> [bit-index]")
return
action = args[0]
if action not in BITMASK_ACTIONS:
print(f"action must be one of: {', '.join(BITMASK_ACTIONS)}")
return
# Grab the parameter argument, and check it exists
param = args[1]
if not param.upper() in self.mav_param:
print(f"Unable to find parameter {param.upper()}")
return
uname = param.upper()
htree = self.param_help.param_help_tree()
if htree is None:
# No help tree is available
print("Download parameters first")
return
# Take the help tree and check if parameter is a bitmask
phelp = htree[uname]
bitmask_values = self.param_help.get_bitmask_from_help(phelp)
if bitmask_values is None:
print(f"Parameter {uname} is not a bitmask")
return
# Find the type of the parameter
ptype = None
if uname in self.param_types:
# Get the type of the parameter
ptype = self.param_types[uname]
# Now grab the value for the parameter
value = int(self.mav_param.get(uname))
if value is None:
print(f"Could not get a value for parameter {uname}")
return
# The next argument is the bit_index - if it exists, handle it
bit_index = None
if len(args) >= 3:
try:
# If the bit index is available lets grab it
arg_bit_index = args[2]
# Try to convert it to int
bit_index = int(arg_bit_index)
except ValueError:
print(f"Invalid bit index: {arg_bit_index}\n")
if bit_index is None:
# No bit index was specified, but the parameter and action was.
# Print the available bitmask information.
print("%s: %s" % (uname, phelp.get('humanName')))
s = "%-16.16s %s" % (uname, value)
print(s)
# Generate the bitmask enabled list
remaining_bits = value
out_v = []
if bitmask_values is not None and len(bitmask_values):
for (n, v) in bitmask_values.items():
if bit_index is None or bit_index == int(n):
out_v.append(f"\t{int(n):3d} [{'x' if value & (1<<int(n)) else ' '}] : {v}")
remaining_bits &= ~(1 << int(n))
# Loop bits 0 to 31, checking if they are remaining, and append
for i in range(32):
if (remaining_bits & (1 << i)) and ((bit_index is None) or (bit_index == i)):
out_v.append(f"\t{i:3d} [{'x' if value & (1 << i) else ' '}] : Unknownbit{i}")
if out_v is not None and len(out_v) > 0:
print("\nBitmask: ")
print("\n".join(out_v))
# Finally, inform user of the error we experienced
if bit_index is None:
print("bit index is not specified")
# We don't have enough information to modify the bitmask, so bail
return
# Sanity check the bit index
if bit_index >= NUM_BITS_MAX:
print(f"Cannot perform bitmask action '{action}' on bit index {bit_index}.")
return
# We have enough information to try perform an action
if action == "toggle":
value = value ^ (1 << bit_index)
elif action == "set":
value = value | (1 << bit_index)
elif action == "clear":
value = value & ~(1 << bit_index)
else:
# We cannot toggle, set or clear
print("Invalid bitmask action")
return
# Update the parameter
self.set_parameter(master, uname, value, attempts=3, param_type=ptype)
def set_parameter(self, master, name, value, attempts=None, param_type=None):
'''convenient intermediate method which determines parameter type for
lazy callers'''
if param_type is None:
param_type = self.param_types.get(name, None)
self.parameters_to_set_input_queue.put(ParamState.ParamSet(
master,
name,
value,
attempts=attempts,
param_type=param_type,
))
def param_revert(self, master, args):
'''handle param revert'''
defaults = self.default_params
if defaults is None:
print("No defaults available")
return
if len(args) == 0:
print("Usage: param revert PATTERN")
return
wildcard = args[0].upper()
count = 0
for p in self.mav_param:
p = str(p).upper()
if not fnmatch.fnmatch(p, wildcard):
continue
if p not in defaults:
continue
if self.mav_param[p] == defaults[p]:
continue
s1 = "%f" % self.mav_param[p]
s2 = "%f" % defaults[p]
if s1 == s2:
continue
print("Reverting %-16.16s %s -> %s" % (p, s1, s2))
self.set_parameter(master, p, defaults[p], attempts=3)
count += 1
print("Reverted %u parameters" % count)
def handle_command(self, master, mpstate, args):
'''handle parameter commands'''
param_wildcard = "*"
usage="Usage: param <fetch|ftp|save|savechanged|revert|set|show|load|preload|forceload|ftpload|diff|download|check|help|watch|unwatch|watchlist|bitmask>" # noqa
if len(args) < 1:
print(usage)
return
if args[0] == "fetch":
if len(args) == 1:
self.fetch_all(master)
if self.ftp_started:
print("Requested parameter list (ftp)")
else:
print("Requested parameter list")
else:
found = False
pname = args[1].upper()
for p in self.mav_param.keys():
if fnmatch.fnmatch(p, pname):
master.param_fetch_one(p)
if p not in self.fetch_one:
self.fetch_one[p] = 0
self.fetch_one[p] += 1
found = True
print("Requested parameter %s" % p)
if not found and args[1].find('*') == -1:
master.param_fetch_one(pname)
if pname not in self.fetch_one:
self.fetch_one[pname] = 0
self.fetch_one[pname] += 1
print("Requested parameter %s" % pname)
elif args[0] == "ftp":
self.ftp_start()
elif args[0] == "save":
if len(args) < 2:
print("usage: param save <filename> [wildcard]")
return
if len(args) > 2:
param_wildcard = args[2]
else:
param_wildcard = "*"
self.mav_param.save(args[1].strip('"'), param_wildcard, verbose=True)
elif args[0] == "diff":
self.param_diff(args[1:])
elif args[0] == "savechanged":
self.param_savechanged(args[1:])
elif args[0] == "revert":
self.param_revert(master, args[1:])
elif args[0] == "watch":
self.param_watch(master, args[1:])
elif args[0] == "unwatch":
self.param_unwatch(master, args[1:])
elif args[0] == "watchlist":
self.param_watchlist(master, args[1:])
elif args[0] == "set":
if len(args) < 2:
print("Usage: param set PARMNAME VALUE")
return
if len(args) == 2:
self.param_show(args[1], self.mpstate.settings.param_docs)
return
param = args[1]
value = args[2]
if value.startswith('0x'):
value = int(value, base=16)
if not param.upper() in self.mav_param:
print("Unable to find parameter '%s'" % param)
return
uname = param.upper()
self.set_parameter(master, uname, value, attempts=3)
if (param.upper() == "WP_LOITER_RAD" or param.upper() == "LAND_BREAK_PATH"):
# need to redraw rally points
# mpstate.module('rally').set_last_change(time.time())
# need to redraw loiter points
mpstate.module('wp').wploader.last_change = time.time()
elif args[0] == "bitmask":
self.param_bitmask_modify(master, args[1:])
elif args[0] == "load":
if len(args) < 2:
print("Usage: param load <filename> [wildcard]")
return
if len(args) > 2:
param_wildcard = args[2]
else:
param_wildcard = "*"
self.mav_param.load(args[1].strip('"'), param_wildcard, master)
elif args[0] == "preload":
if len(args) < 2:
print("Usage: param preload <filename>")
return
self.mav_param.load(args[1].strip('"'))
elif args[0] == "forceload":
if len(args) < 2:
print("Usage: param forceload <filename> [wildcard]")
return
if len(args) > 2:
param_wildcard = args[2]
else:
param_wildcard = "*"
self.mav_param.load(args[1].strip('"'), param_wildcard, master, check=False)
elif args[0] == "ftpload":
if len(args) < 2:
print("Usage: param ftpload <filename> [wildcard]")
return
if len(args) > 2:
param_wildcard = args[2]
else:
param_wildcard = "*"
self.ftp_load(args[1].strip('"'), param_wildcard, master)
elif args[0] == "download":
self.param_help.param_help_download()
elif args[0] == "apropos":
self.param_help.param_apropos(args[1:])
elif args[0] == "check":
self.param_help.param_check(self.mav_param, args[1:])
elif args[0] == "help":
if len(args) < 2:
print(usage)
return
self.param_help.param_help(args[1:])
elif args[0] == "set_xml_filepath":
self.param_set_xml_filepath(args[1:])
elif args[0] == "show":
verbose = self.mpstate.settings.param_docs
if len(args) > 1:
pattern = args[1]
if len(args) > 2 and args[2] == '-v':
verbose = True
else:
pattern = "*"
self.param_show(pattern, verbose)
elif args[0] == "status":
print("Have %u/%u params" % (len(self.mav_param_set), self.mav_param_count))
else:
print(usage)
def param_show(self, pattern, verbose):
'''show parameters'''
k = sorted(self.mav_param.keys())
for p in k:
name = str(p).upper()
if fnmatch.fnmatch(name, pattern.upper()):
value = self.mav_param.get(name)
s = "%-16.16s %s" % (name, value)
if verbose:
info = self.param_help.param_info(name, value)
if info is not None:
s = "%-28.28s # %s" % (s, info)
print(s)
def ftp_upload_callback(self, dlen):
'''callback on ftp put completion'''
if dlen is None:
print("Failed to send parameters")
else:
if self.ftp_send_param is not None:
for k in sorted(self.ftp_send_param.keys()):
v = self.ftp_send_param.get(k)
self.mav_param[k] = v
self.ftp_send_param = None
print("Parameter upload done")
def ftp_upload_progress(self, proportion):
'''callback from ftp put of parameters'''
if proportion is None:
self.mpstate.console.set_status('Params', 'Params ERR')
else:
self.mpstate.console.set_status('Params', 'Param %.1f%%' % (100.0*proportion))
def best_type(self, v):
'''work out best type for a variable'''
if not v.is_integer():
# treat as float
return 4
if v >= -128 and v <= 127:
return 1
if v >= -32768 and v <= 32767:
return 2
return 3
def str_common_len(self, s1, s2):
'''return common length between two strings'''
c = min(len(s1), len(s2))
for i in range(c):
if s1[i] != s2[i]:
return i
return c
def ftp_load(self, filename, param_wildcard, master):
'''load parameters with ftp'''
ftp = self.mpstate.module('ftp')
if ftp is None:
print("Need ftp module")
return
newparm = mavparm.MAVParmDict()
newparm.load(filename, param_wildcard, check=False)
fh = SIO()
for k in sorted(newparm.keys()):
v = newparm.get(k)
oldv = self.mav_param.get(k, None)
if oldv is not None and abs(oldv - v) <= newparm.mindelta:
# not changed
newparm.pop(k)
count = len(newparm.keys())
if count == 0:
print("No parameter changes")
return
fh.write(struct.pack("<HHH", 0x671b, count, count))
last_param = ""
for k in sorted(newparm.keys()):
v = newparm.get(k)
vtype = self.best_type(v)
common_len = self.str_common_len(last_param, k)
b1 = vtype
b2 = common_len | ((len(k) - (common_len + 1)) << 4)
fh.write(struct.pack("<BB", b1, b2))
fh.write(k[common_len:].encode("UTF-8"))
if vtype == 1: # int8
fh.write(struct.pack("<b", int(v)))
if vtype == 2: # int16
fh.write(struct.pack("<h", int(v)))
if vtype == 3: # int32
fh.write(struct.pack("<i", int(v)))
if vtype == 4: # float
fh.write(struct.pack("<f", v))
last_param = k
# re-pack with full file length in total_params
file_len = fh.tell()
fh.seek(0)
fh.write(struct.pack("<HHH", 0x671b, count, file_len))
fh.seek(0)
self.ftp_send_param = newparm
print("Sending %u params" % count)
ftp.cmd_put(["-", "@PARAM/param.pck"],
fh=fh, callback=self.ftp_upload_callback, progress_callback=self.ftp_upload_progress)
|
class ParamState:
'''this class is separated to make it possible to use the parameter
functions on a secondary connection'''
def __init__(self, mav_param, logdir, vehicle_name, parm_file, mpstate, sysid):
pass
class ParamSet():
'''class to hold information about a parameter set being attempted'''
def __init__(self, mav_param, logdir, vehicle_name, parm_file, mpstate, sysid):
pass
def normalize_parameter_for_param_set_send(self, name, value, param_type):
'''uses param_type to convert value into a value suitable for passing
into the mavlink param_set_send binding. Note that this
is a copy of a method in pymavlink, in case the user has
an older version of that library.
'''
pass
def send_set(self):
pass
def expired(self):
pass
def due_for_retry(self):
pass
def handle_PARAM_VALUE(self, m, value):
'''handle PARAM_VALUE packet m which has already been checked for a
match against self.name. Returns true if this Set is now
satisfied. value is the value extracted and potentially
manipulated from the packet
'''
pass
def print_expired_message(self):
pass
def run_parameter_set_queue(self):
pass
def use_ftp(self):
'''return true if we should try ftp for download'''
pass
def handle_px4_param_value(self, m):
'''special handling for the px4 style of PARAM_VALUE'''
pass
def handle_mavlink_packet(self, master, m):
'''handle an incoming mavlink packet'''
pass
def fetch_check(self, master, force=False):
'''check for missing parameters periodically'''
pass
def param_use_xml_filepath(self, filepath):
pass
def param_set_xml_filepath(self, args):
pass
def status(self, master, mpstate):
pass
def ftp_start(self):
'''start a ftp download of parameters'''
pass
def log_params(self, params):
'''log PARAM_VALUE messages so that we can extract parameters from a tlog when using ftp download'''
pass
def ftp_callback_progress(self, fh, total_size):
'''callback as read progresses'''
pass
def ftp_callback_progress(self, fh, total_size):
'''callback from ftp fetch of parameters'''
pass
def fetch_all(self, master):
'''force refetch of parameters'''
pass
def param_diff(self, args):
'''handle param diff'''
pass
def param_savechanged(self, args):
'''handle param savechanged'''
pass
def handle_mavlink_watch_param_value(self, master, m):
pass
def param_watch(self, master, args):
'''command to allow addition of watches for parameter changes'''
pass
def param_unwatch(self, master, args):
'''command to allow removal of watches for parameter changes'''
pass
def param_watchlist(self, master, args):
'''command to show watch patterns for parameter changes'''
pass
def param_bitmask_modify(self, master, args):
'''command for performing bitmask actions on a parameter'''
pass
def set_parameter(self, master, name, value, attempts=None, param_type=None):
'''convenient intermediate method which determines parameter type for
lazy callers'''
pass
def param_revert(self, master, args):
'''handle param revert'''
pass
def handle_command(self, master, mpstate, args):
'''handle parameter commands'''
pass
def param_show(self, pattern, verbose):
'''show parameters'''
pass
def ftp_upload_callback(self, dlen):
'''callback on ftp put completion'''
pass
def ftp_upload_progress(self, proportion):
'''callback from ftp put of parameters'''
pass
def best_type(self, v):
'''work out best type for a variable'''
pass
def str_common_len(self, s1, s2):
'''return common length between two strings'''
pass
def ftp_load(self, filename, param_wildcard, master):
'''load parameters with ftp'''
pass
| 39 | 28 | 23 | 1 | 19 | 3 | 6 | 0.15 | 0 | 12 | 1 | 0 | 30 | 23 | 30 | 30 | 892 | 74 | 721 | 187 | 682 | 107 | 645 | 187 | 606 | 48 | 0 | 5 | 233 |
7,198 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_paramedit/__init__.py
|
MAVProxy.modules.mavproxy_paramedit.ParamEditorModule
|
class ParamEditorModule(mp_module.MPModule):
'''
A Graphical parameter editor for use with MAVProxy
'''
def __init__(self, mpstate):
super(ParamEditorModule, self).__init__(mpstate,
"paramedit", "param edit",
public=True)
# to work around an issue on MacOS this module is a thin wrapper
# around a separate ParamEditorMain object
self.pe_main = None
self.mpstate = mpstate
def unload(self):
'''unload module'''
if self.pe_main:
self.pe_main.unload()
def idle_task(self):
if not self.pe_main:
# wait for parameter module to load
if self.module('param') is None:
return
from MAVProxy.modules.mavproxy_paramedit import param_editor
self.pe_main = param_editor.ParamEditorMain(self.mpstate)
if self.pe_main:
if self.pe_main.needs_unloading:
self.needs_unloading = True
self.pe_main.idle_task()
def mavlink_packet(self, m):
if self.pe_main:
self.pe_main.mavlink_packet(m)
|
class ParamEditorModule(mp_module.MPModule):
'''
A Graphical parameter editor for use with MAVProxy
'''
def __init__(self, mpstate):
pass
def unload(self):
'''unload module'''
pass
def idle_task(self):
pass
def mavlink_packet(self, m):
pass
| 5 | 2 | 7 | 0 | 6 | 1 | 3 | 0.3 | 1 | 2 | 1 | 0 | 4 | 3 | 4 | 42 | 34 | 4 | 23 | 9 | 17 | 7 | 21 | 9 | 15 | 5 | 2 | 2 | 10 |
7,199 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_paramedit/checklisteditor.py
|
MAVProxy.modules.mavproxy_paramedit.checklisteditor.GridCheckListEditor
|
class GridCheckListEditor(gridlib.PyGridCellEditor):
"""
This is a custom CheckListBox editor for setting of Bitmasks
"""
def __init__(self, choice, pvalcol, start):
# ensure the choices list has no gaps
bvalue = 0
self.choices = []
for c in choice:
bopt = c.split(":")
if len(bopt) != 2:
continue
bval = int(bopt[0])
while bvalue < bval:
self.choices.append("%u:INVALID" % bvalue)
bvalue += 1
self.choices.append(c)
bvalue += 1
binary = bin(int(start))[2:]
self.startValue = [(len(binary)-ones-1) for ones in range(len(binary)) if binary[ones] == '1']
self.pvalcol = pvalcol
gridlib.PyGridCellEditor.__init__(self)
def set_checked(self, selected):
if int(selected) < int(math.pow(2, len(self.choices))):
binary = bin(int(selected))[2:]
self.startValue = [(len(binary)-ones-1) for ones in range(len(binary)) if binary[ones] == '1']
try:
self._tc.SetChecked(self.startValue)
except Exception as e:
print (e)
def get_checked(self):
return self._tc.GetChecked()
def Create(self, parent, id, evtHandler):
self._tc = wx.CheckListBox(parent, id, choices=self.choices)
self._tc.SetChecked(self.startValue)
self.SetControl(self._tc)
if evtHandler:
self._tc.PushEventHandler(evtHandler)
def SetSize(self, rect):
self._tc.SetDimensions(rect.x, rect.y, rect.width+2, 30*len(self.choices),
wx.SIZE_ALLOW_MINUS_ONE)
def Show(self, show, attr):
super(GridCheckListEditor, self).Show(show, attr)
def BeginEdit(self, row, col, grid):
self._tc.SetChecked(self.startValue)
def EndEdit(self, row, col, grid, oldVal):
val = self._tc.GetChecked()
self.startValue = val
if val != oldVal:
return self._tc.GetChecked()
else:
return None
def get_pvalue(self):
s = 0
for i in self._tc.GetChecked():
s = s + int(math.pow(2, i))
return str(s)
def ApplyEdit(self, row, col, grid):
val = ""
for i in self._tc.GetChecked():
val = val + str(self.choices[i]) + "\n"
grid.GetTable().SetValue(row, col, str(val))
grid.GetTable().SetValue(row, self.pvalcol, self.get_pvalue())
def Reset(self):
self._tc.SetChecked(None)
def StartingKey(self, evt):
evt.Skip()
def Destroy(self):
super(GridCheckListEditor, self).Destroy()
def Clone(self):
return GridCheckListEditor(self.choices, self.pvalcol, self.startValue)
|
class GridCheckListEditor(gridlib.PyGridCellEditor):
'''
This is a custom CheckListBox editor for setting of Bitmasks
'''
def __init__(self, choice, pvalcol, start):
pass
def set_checked(self, selected):
pass
def get_checked(self):
pass
def Create(self, parent, id, evtHandler):
pass
def SetSize(self, rect):
pass
def Show(self, show, attr):
pass
def BeginEdit(self, row, col, grid):
pass
def EndEdit(self, row, col, grid, oldVal):
pass
def get_pvalue(self):
pass
def ApplyEdit(self, row, col, grid):
pass
def Reset(self):
pass
def StartingKey(self, evt):
pass
def Destroy(self):
pass
def Clone(self):
pass
| 15 | 1 | 5 | 0 | 5 | 0 | 2 | 0.06 | 1 | 5 | 0 | 0 | 14 | 4 | 14 | 14 | 84 | 13 | 67 | 31 | 52 | 4 | 65 | 30 | 50 | 4 | 1 | 2 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.