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,000 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/wxgeodesicgrid.py
|
MAVProxy.modules.mavproxy_magical.wxgeodesicgrid.Renderer
|
class Renderer(glrenderer.Renderer):
def __init__(self, background):
super(Renderer, self).__init__(background)
glEnable(GL_DEPTH_TEST)
glEnable(GL_MULTISAMPLE)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
self.visible = [False for _ in range(len(geodesic_grid.sections))]
self.common_model_transform = opengl.Transform()
self.last_render_quaternion = quaternion.Quaternion(
self.common_model_transform.quaternion)
vertices = [(p.x, p.y, p.z) for t in geodesic_grid.sections for p in t]
self.sphere = opengl.Object(vertices, enable_alpha=True)
self.sphere.local.scale(0.46)
self.sphere.model = self.common_model_transform
self.base_color = Vector3(0.08, 0.68, 0.706667)
self.vehicle = None
path = os.path.join(magical.datapath, 'arrow.obj')
obj = wv.ObjParser(filename=path).parse()
self.mag = opengl.WavefrontObject(obj)
self.mag.local.scale(.88)
def get_load_progress(self):
return self.vehicle_loader.get_progress()
def rotate(self, vector, angle, rotate_mag=False):
self.common_model_transform.rotate(vector, angle)
if rotate_mag and self.mag:
self.mag.model.rotate(vector, angle)
def set_attitude(self, roll, pitch, yaw):
self.common_model_transform.set_euler(roll, pitch, yaw)
def set_mag(self, mag):
if not mag.length():
return
m = self.common_model_transform.apply(mag).normalized()
axis = Vector3(0, 0, 1) % m
angle = math.acos(Vector3(0, 0, 1) * m)
self.mag.model.set_rotation(axis, angle)
def render(self):
super(Renderer, self).render()
if self.vehicle:
self.vehicle.draw(self.program)
self.sphere.material.set_color(1.2 * self.base_color)
self.sphere.material.specular_exponent = 4
self.sphere.material.alpha = 1.0
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
self.sphere.draw(self.program)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
self.mag.draw(self.program)
self.sphere.material.set_color(self.base_color)
self.sphere.material.alpha = .4
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
faces = [i for i in range(80) if self.visible[i]]
self.sphere.draw(self.program, faces=faces, camera=self.camera)
self.last_render_quaternion = quaternion.Quaternion(
self.common_model_transform.quaternion)
def set_section_visible(self, section, visible=True):
self.visible[section] = visible
def clear_sections(self):
for i in range(len(self.visible)):
self.visible[i] = False
def set_vehicle_wavefront(self, vehicle):
self.vehicle = opengl.WavefrontObject(vehicle)
# FIXME: this class shouldn't need to be aware of the proper scaling
self.vehicle.local.scale(3.5)
self.vehicle.model = self.common_model_transform
|
class Renderer(glrenderer.Renderer):
def __init__(self, background):
pass
def get_load_progress(self):
pass
def rotate(self, vector, angle, rotate_mag=False):
pass
def set_attitude(self, roll, pitch, yaw):
pass
def set_mag(self, mag):
pass
def render(self):
pass
def set_section_visible(self, section, visible=True):
pass
def clear_sections(self):
pass
def set_vehicle_wavefront(self, vehicle):
pass
| 10 | 0 | 8 | 1 | 7 | 0 | 1 | 0.02 | 1 | 6 | 4 | 0 | 9 | 8 | 9 | 12 | 85 | 21 | 63 | 26 | 53 | 1 | 61 | 25 | 51 | 2 | 2 | 1 | 13 |
7,001 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/wxvehicle.py
|
MAVProxy.modules.mavproxy_magical.wxvehicle.Renderer
|
class Renderer(glrenderer.Renderer):
def __init__(self, background):
super(Renderer, self).__init__(background)
glEnable(GL_DEPTH_TEST)
glEnable(GL_MULTISAMPLE)
self.vehicle = None
def render(self):
super(Renderer, self).render()
if self.vehicle:
self.vehicle.draw(self.program)
def set_vehicle_wavefront(self, vehicle):
self.vehicle = opengl.WavefrontObject(vehicle)
# FIXME: this class shouldn't need to be aware of the proper scaling
self.vehicle.local.scale(4.4)
|
class Renderer(glrenderer.Renderer):
def __init__(self, background):
pass
def render(self):
pass
def set_vehicle_wavefront(self, vehicle):
pass
| 4 | 0 | 5 | 1 | 4 | 0 | 1 | 0.08 | 1 | 2 | 1 | 0 | 3 | 1 | 3 | 6 | 19 | 5 | 13 | 5 | 9 | 1 | 13 | 5 | 9 | 2 | 2 | 1 | 4 |
7,002 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/wxvehicle.py
|
MAVProxy.modules.mavproxy_magical.wxvehicle.Vehicle
|
class Vehicle(glrenderer.GLCanvas):
script_available_methods = (
'SetAngvel',
'SetEuler',
)
def __init__(self, *k, **kw):
kw['attribList'] = (glcanvas.WX_GL_SAMPLES, 4)
super(Vehicle, self).__init__(*k, **kw)
self.context = glcanvas.GLContext(self)
self.vehicle_wavefront = None
self.script = None
self.script_command = 0
self.script_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnScriptTimer, self.script_timer)
self.angvel = None
self.desired_quaternion = None
self.attitude_callback = None
self.actuation_state = None
self.actuation_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnActuationTimer, self.actuation_timer)
def CreateRenderer(self):
r, g, b = self.GetParent().GetBackgroundColour()
self.renderer = Renderer(
background=(r / 255.0, g / 255.0, b / 255.0, 1),
)
if self.vehicle_wavefront:
self.renderer.set_vehicle_wavefront(self.vehicle_wavefront)
self.vehicle_wavefront = None
def SetVehicleWavefront(self, vehicle):
if self.renderer:
self.SetCurrent(self.context)
self.renderer.set_vehicle_wavefront(vehicle)
self.Refresh()
return
self.vehicle_wavefront = vehicle
def SetEuler(self, roll, pitch, yaw, callback=None):
self.desired_quaternion = Quaternion((roll, pitch, yaw))
self.attitude_callback = callback
self.actuation_state = 'attitude'
self.angvel = Vector3(1, 0, 0), 0
self.StartActuation()
def SetAngvel(self, axis, speed):
if not isinstance(axis, Vector3):
axis = Vector3(*axis)
axis = self.renderer.vehicle.model.apply(axis)
self.angvel = axis, speed
self.actuation_state = 'angvel'
self.StartActuation()
def StartActuation(self):
if not self.actuation_timer.IsRunning():
self.actuation_timer.Start(40)
def StopActuation(self):
self.actuation_timer.Stop()
def OnActuationTimer(self, evt):
if not self.renderer.vehicle:
return
dt = evt.GetInterval() * .001
axis, speed = self.angvel
angle = speed * dt
self.renderer.vehicle.model.rotate(axis, angle)
if self.actuation_state == 'attitude':
diff = self.desired_quaternion / self.renderer.vehicle.model.quaternion
diff = quaternion_to_axis_angle(diff)
angle = diff.length()
if abs(angle) <= 0.001:
self.renderer.vehicle.model.quaternion = self.desired_quaternion
self.StopActuation()
if self.attitude_callback:
self.attitude_callback()
self.attitude_callback = None
else:
speed = angle / dt
self.angvel = Vector3(diff.x, diff.y, diff.z), speed * .3
self.Refresh()
def RunScript(self, script):
'''
Actuate on the vehicle through a script. The script is a sequence of
commands. Each command is a sequence with the first element as the
command name and the remaining values as parameters.
The script is executed asynchronously by a timer with a period of 0.1
seconds. At each timer tick, the next command is executed if it's ready
for execution.
If a command name starts with '.', then the remaining characters are a
method name and the arguments are passed to the method call. For
example, the command ('.SetEuler', 0, math.pi / 2, 0) sets the vehicle
nose up. The methods available for that type of command are in the
class property script_available_methods.
The other possible commands are:
- wait(sec): wait for sec seconds. Because of the timer period, some
inaccuracy is expected depending on the value of sec.
- restart: go back to the first command.
Example::
vehicle.RunScript((
('.SetEuler', 0, 0, 0), # Set vehicle level
('wait', 2), # Wait for 2 seconds
# Rotate continuously on the x-axis at a rate of 90 degrees per
# second
('.SetAngvel', (1, 0, 0), math.pi / 2),
('wait', 5), # Let the vehicle rotating for 5 seconds
('restart',), # Restart the script
))
'''
self.script = script
self.script_command = 0
self.script_command_start_time = 0
self.script_command_state = 'ready'
self.script_timer.Start(100)
self.script_wait_time = 0
def OnScriptTimer(self, evt):
if not self.script or self.script_command >= len(self.script):
self.StopScript()
return
cmd = self.script[self.script_command]
name = cmd[0]
args = cmd[1:]
if self.script_command_state == 'ready':
if name.startswith('.'):
name = name[1:]
if name not in self.script_available_methods:
raise Exception("Vehicle: script: invalid method name \"%s\"" % name)
if name == 'SetEuler':
self.script_command_state = 'running'
def callback():
self.script_command += 1
self.script_command_state = 'ready'
args = tuple(args[:3]) + (callback,)
else:
self.script_command += 1
getattr(self, name)(*args)
elif name == 'wait':
self.script_wait_time = float(args[0]) if args else 1
self.script_command_state = 'running'
elif name == 'restart':
self.script_command = 0
else:
raise Exception("Vehicle: script: invalid command \"%s\"" % name)
self.script_command_start_time = time.time()
elif self.script_command_state == 'running':
if name == 'wait':
t = time.time() - self.script_command_start_time
if t >= self.script_wait_time:
self.script_command += 1
self.script_command_state = 'ready'
def StopScript(self):
self.script_timer.Stop()
self.script = None
|
class Vehicle(glrenderer.GLCanvas):
def __init__(self, *k, **kw):
pass
def CreateRenderer(self):
pass
def SetVehicleWavefront(self, vehicle):
pass
def SetEuler(self, roll, pitch, yaw, callback=None):
pass
def SetAngvel(self, axis, speed):
pass
def StartActuation(self):
pass
def StopActuation(self):
pass
def OnActuationTimer(self, evt):
pass
def RunScript(self, script):
'''
Actuate on the vehicle through a script. The script is a sequence of
commands. Each command is a sequence with the first element as the
command name and the remaining values as parameters.
The script is executed asynchronously by a timer with a period of 0.1
seconds. At each timer tick, the next command is executed if it's ready
for execution.
If a command name starts with '.', then the remaining characters are a
method name and the arguments are passed to the method call. For
example, the command ('.SetEuler', 0, math.pi / 2, 0) sets the vehicle
nose up. The methods available for that type of command are in the
class property script_available_methods.
The other possible commands are:
- wait(sec): wait for sec seconds. Because of the timer period, some
inaccuracy is expected depending on the value of sec.
- restart: go back to the first command.
Example::
vehicle.RunScript((
('.SetEuler', 0, 0, 0), # Set vehicle level
('wait', 2), # Wait for 2 seconds
# Rotate continuously on the x-axis at a rate of 90 degrees per
# second
('.SetAngvel', (1, 0, 0), math.pi / 2),
('wait', 5), # Let the vehicle rotating for 5 seconds
('restart',), # Restart the script
))
'''
pass
def OnScriptTimer(self, evt):
pass
def callback():
pass
def StopScript(self):
pass
| 13 | 1 | 13 | 1 | 10 | 2 | 3 | 0.23 | 1 | 5 | 1 | 0 | 11 | 14 | 11 | 14 | 173 | 27 | 119 | 37 | 106 | 27 | 108 | 37 | 95 | 12 | 2 | 3 | 31 |
7,003 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/GAreader.py
|
MAVProxy.modules.mavproxy_map.GAreader.ERMap
|
class ERMap:
'''Class to read GA files'''
def __init__(self):
self.header = None
self.data = None
self.startlongitude = 0
self.startlatitude = 0
self.endlongitude = 0
self.endlatitude = 0
self.deltalongitude = 0
self.deltalatitude = 0
def read_ermapper(self, ifile):
'''Read in a DEM file and associated .ers file'''
ers_index = ifile.find('.ers')
if ers_index > 0:
data_file = ifile[0:ers_index]
header_file = ifile
else:
data_file = ifile
header_file = ifile + '.ers'
self.header = self.read_ermapper_header(header_file)
nroflines = int(self.header['nroflines'])
nrofcellsperlines = int(self.header['nrofcellsperline'])
self.data = self.read_ermapper_data(data_file, offset=int(self.header['headeroffset']))
self.data = numpy.reshape(self.data,(nroflines,nrofcellsperlines))
longy = numpy.fromstring(self.getHeaderParam('longitude'), sep=':')
latty = numpy.fromstring(self.getHeaderParam('latitude'), sep=':')
self.deltalatitude = float(self.header['ydimension'])
self.deltalongitude = float(self.header['xdimension'])
if longy[0] < 0:
self.startlongitude = longy[0]+-((longy[1]/60)+(longy[2]/3600))
self.endlongitude = self.startlongitude - int(self.header['nrofcellsperline'])*self.deltalongitude
else:
self.startlongitude = longy[0]+(longy[1]/60)+(longy[2]/3600)
self.endlongitude = self.startlongitude + int(self.header['nrofcellsperline'])*self.deltalongitude
if latty[0] < 0:
self.startlatitude = latty[0]-((latty[1]/60)+(latty[2]/3600))
self.endlatitude = self.startlatitude - int(self.header['nroflines'])*self.deltalatitude
else:
self.startlatitude = latty[0]+(latty[1]/60)+(latty[2]/3600)
self.endlatitude = self.startlatitude + int(self.header['nroflines'])*self.deltalatitude
def read_ermapper_header(self, ifile):
# function for reading an ERMapper header from file
header = {}
fid = open(ifile,'rt')
header_string = fid.readlines()
fid.close()
for line in header_string:
if line.find('=') > 0:
tmp_string = line.strip().split('=')
header[tmp_string[0].strip().lower()]= tmp_string[1].strip()
return header
def read_ermapper_data(self, ifile, data_format = numpy.float32, offset=0):
# open input file in a binary format and read the input string
fid = open(ifile,'rb')
if offset != 0:
fid.seek(offset)
input_string = fid.read()
fid.close()
# convert input string to required format (Note default format is numpy.float32)
grid_as_float = numpy.fromstring(input_string,data_format)
return grid_as_float
def getHeaderParam(self, key):
'''Find a parameter in the associated .ers file'''
return self.header[key]
def printBoundingBox(self):
'''Print the bounding box that this DEM covers'''
print("Bounding Latitude: ")
print(self.startlatitude)
print(self.endlatitude)
print("Bounding Longitude: ")
print(self.startlongitude)
print(self.endlongitude)
def getPercentBlank(self):
'''Print how many null cells are in the DEM - Quality measure'''
blank = 0
nonblank = 0
for x in self.data.flat:
if x == -99999.0:
blank = blank + 1
else:
nonblank = nonblank + 1
print("Blank tiles = ", blank, "out of ", (nonblank+blank))
def getAltitudeAtPoint(self, latty, longy):
'''Return the altitude at a particular long/lat'''
#check the bounds
if self.startlongitude > 0 and (longy < self.startlongitude or longy > self.endlongitude):
return -1
if self.startlongitude < 0 and (longy > self.startlongitude or longy < self.endlongitude):
return -1
if self.startlatitude > 0 and (latty < self.startlatitude or longy > self.endlatitude):
return -1
if self.startlatitude < 0 and (latty > self.startlatitude or longy < self.endlatitude):
return -1
x = numpy.abs((latty - self.startlatitude)/self.deltalatitude)
y = numpy.abs((longy - self.startlongitude)/self.deltalongitude)
#do some interpolation
# print("x,y", x, y)
x_int = int(x)
x_frac = x - int(x)
y_int = int(y)
y_frac = y - int(y)
#print("frac", x_int, x_frac, y_int, y_frac)
value00 = self.data[x_int, y_int]
value10 = self.data[x_int+1, y_int]
value01 = self.data[x_int, y_int+1]
value11 = self.data[x_int+1, y_int+1]
#print("values ", value00, value10, value01, value11)
#check for null values
if value00 == -99999:
value00 = 0
if value10 == -99999:
value10 = 0
if value01 == -99999:
value01 = 0
if value11 == -99999:
value11 = 0
value1 = self._avg(value00, value10, x_frac)
value2 = self._avg(value01, value11, x_frac)
value = self._avg(value1, value2, y_frac)
return value
@staticmethod
def _avg(value1, value2, weight):
"""Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned.
"""
if value1 is None:
return value2
if value2 is None:
return value1
return value2 * weight + value1 * (1 - weight)
|
class ERMap:
'''Class to read GA files'''
def __init__(self):
pass
def read_ermapper(self, ifile):
'''Read in a DEM file and associated .ers file'''
pass
def read_ermapper_header(self, ifile):
pass
def read_ermapper_data(self, ifile, data_format = numpy.float32, offset=0):
pass
def getHeaderParam(self, key):
'''Find a parameter in the associated .ers file'''
pass
def printBoundingBox(self):
'''Print the bounding box that this DEM covers'''
pass
def getPercentBlank(self):
'''Print how many null cells are in the DEM - Quality measure'''
pass
def getAltitudeAtPoint(self, latty, longy):
'''Return the altitude at a particular long/lat'''
pass
@staticmethod
def _avg(value1, value2, weight):
'''Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned.
'''
pass
| 11 | 7 | 16 | 2 | 12 | 2 | 3 | 0.16 | 0 | 2 | 0 | 0 | 8 | 8 | 9 | 9 | 155 | 24 | 113 | 50 | 102 | 18 | 108 | 49 | 98 | 9 | 0 | 2 | 27 |
7,004 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/__init__.py
|
MAVProxy.modules.mavproxy_map.MapModule
|
class MapModule(mp_module.MPModule):
def __init__(self, mpstate):
super(MapModule, self).__init__(mpstate, "map", "map display", public = True, multi_instance=True, multi_vehicle=True)
cmdname = "map"
if self.instance > 1:
cmdname += "%u" % self.instance
# lat/lon per system ID
self.lat_lon_heading = {}
self.wp_change_time = 0
self.fence_change_time = 0
self.rally_change_time = 0
self.have_simstate = False
self.have_vehicle = {}
self.move_wp = -1
self.moving_wp = None
self.moving_fencepoint = None
self.moving_rally = None
self.mission_list = None
self.moving_polygon_point = None
self.moving_circle = None
self.setting_circle_radius = None
self.icon_counter = 0
self.circle_counter = 0
self.draw_line = None
self.draw_callback = None
self.current_ROI = None
self.have_global_position = False
self.vehicle_type_by_sysid = {}
self.vehicle_type_name = 'plane'
self.last_unload_check_time = time.time()
self.unload_check_interval = 0.1 # seconds
self.trajectory_layers = set()
self.vehicle_type_override = {}
self.map_settings = mp_settings.MPSettings(
[ ('showgpspos', int, 1),
('showgps2pos', int, 1),
('showsimpos', int, 0),
('showahrspos', int, 1),
('showahrs2pos', int, 0),
('showahrs3pos', int, 0),
('brightness', float, 1),
('rallycircle', bool, False),
('loitercircle',bool, False),
('showclicktime',int, 2),
('showwpnum',bool, True),
('circle_linewidth', int, 1),
('showdirection', bool, False),
('setpos_accuracy', float, 50),
('mission_color', str, "white"),
('font_size', float, 0.5) ])
service='MicrosoftHyb'
if 'MAP_SERVICE' in os.environ:
service = os.environ['MAP_SERVICE']
import platform
from MAVProxy.modules.mavproxy_map import mp_slipmap
title = "Map"
if self.instance > 1:
title += str(self.instance)
elevation = None
terrain_module = self.module('terrain')
if terrain_module is not None:
elevation = terrain_module.ElevationModel.database
self.map = mp_slipmap.MPSlipMap(service=service, elevation=elevation, title=title)
if self.instance == 1:
self.mpstate.map = self.map
mpstate.map_functions = { 'draw_lines' : self.draw_lines }
self.map.add_callback(functools.partial(self.map_callback))
self.add_command(cmdname, self.cmd_map, "map control", ['icon',
'set (MAPSETTING)',
'vehicletype',
'zoom',
'center',
'follow',
'menu',
'marker',
'clear'])
self.add_completion_function('(MAPSETTING)', self.map_settings.completion)
self.default_popup = MPMenuSubMenu('Popup', items=[])
self.add_menu(MPMenuItem('Fly To', 'Fly To', '# guided ',
handler=MPMenuCallTextDialog(title='Altitude (FLYTOFRAMEUNITS)', default=self.mpstate.settings.guidedalt,
settings=self.settings)))
self.add_menu(MPMenuItem('Terrain Check', 'Terrain Check', '# terrain check'))
self.add_menu(MPMenuItem('Show Position', 'Show Position', 'showPosition'))
self.add_menu(MPMenuItem('Google Maps Link', 'Google Maps Link', 'printGoogleMapsLink'))
self.add_menu(MPMenuItem('Set ROI', 'Set ROI', '# map setroi '))
self.add_menu(MPMenuItem('Set Position', 'Set Position', '# map setposition '))
self.add_menu(MPMenuSubMenu('Home', items=[
MPMenuItem('Set Home', 'Set Home', '# confirm "Set HOME?" map sethomepos '),
MPMenuItem('Set Home (with height)', 'Set Home', '# confirm "Set HOME with height?" map sethome '),
MPMenuItem('Set Origin', 'Set Origin', '# confirm "Set ORIGIN?" map setoriginpos '),
MPMenuItem('Set Origin (with height)', 'Set Origin', '# confirm "Set ORIGIN with height?" map setorigin '),
]))
self.cmd_menu_add(["Marker:Flag", "map", "marker", "flag"])
self.cmd_menu_add(["Marker:Barrell", "map", "marker", "barrell"])
self.cmd_menu_add(["Marker:Flame", "map", "marker", "flame"])
self._colour_for_wp_command = {
# takeoff commands
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF: (255,0,0),
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF_LOCAL: (255,0,0),
mavutil.mavlink.MAV_CMD_NAV_VTOL_TAKEOFF: (255,0,0),
# land commands
mavutil.mavlink.MAV_CMD_NAV_LAND_LOCAL: (255,255,0),
mavutil.mavlink.MAV_CMD_NAV_LAND: (255,255,0),
mavutil.mavlink.MAV_CMD_NAV_VTOL_LAND: (255,255,0),
# waypoint commands
mavutil.mavlink.MAV_CMD_NAV_WAYPOINT: (0,255,255),
mavutil.mavlink.MAV_CMD_NAV_SPLINE_WAYPOINT: (64,255,64),
# other commands
mavutil.mavlink.MAV_CMD_DO_LAND_START: (255,127,0),
}
self._label_suffix_for_wp_command = {
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF: "TOff",
mavutil.mavlink.MAV_CMD_DO_LAND_START: "DLS",
mavutil.mavlink.MAV_CMD_NAV_SPLINE_WAYPOINT: "SW",
mavutil.mavlink.MAV_CMD_NAV_VTOL_LAND: "VL",
}
def add_menu(self, menu):
'''add to the default popup menu'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
self.default_popup.add(menu)
self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))
def cmd_menu_add(self, args):
'''add to map menus'''
if len(args) < 2:
print("Usage: map menu add MenuPath command")
return
menupath = args[0].strip('"').split(':')
name = menupath[-1]
cmd = '# ' + ' '.join(args[1:])
self.default_popup.add_to_submenu(menupath[:-1], MPMenuItem(name, name, cmd))
self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))
def cmd_menu(self, args):
'''control console menus'''
if len(args) < 2:
print("Usage: map menu <add>")
return
if args[0] == 'add':
self.cmd_menu_add(args[1:])
def remove_menu(self, menu):
'''add to the default popup menu'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
self.default_popup.remove(menu)
self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))
def show_position(self):
'''show map position click information'''
pos = self.mpstate.click_location
dms = (mp_util.degrees_to_dms(pos[0]), mp_util.degrees_to_dms(pos[1]))
msg = "Coordinates in WGS84\n"
msg += "Decimal: %.6f %.6f\n" % (pos[0], pos[1])
msg += "DMS: %s %s\n" % (dms[0], dms[1])
msg += "Grid: %s\n" % mp_util.latlon_to_grid(pos)
if self.logdir:
logf = open(os.path.join(self.logdir, "positions.txt"), "a")
logf.write("Position: %.6f %.6f at %s\n" % (pos[0], pos[1], time.ctime()))
logf.close()
posbox = MPMenuChildMessageDialog('Position', msg, font_size=32)
posbox.show()
def print_google_maps_link(self):
'''show map position click information'''
pos = self.mpstate.click_location
print("https://www.google.com/maps/search/?api=1&query=%f,%f" % (pos[0], pos[1]))
def write_JSON(self, fname, template, vardict):
'''write a JSON file in log directory'''
fname = os.path.join(self.logdir, fname)
json = template
for k in vardict.keys():
value = vardict[k]
json = json.replace("{{" + k + "}}", str(value))
open(fname, 'w').write(json)
def cmd_map_marker(self, args, latlon=None):
'''add a map marker'''
usage = "Usage: map marker <icon>"
if latlon is None:
latlon = self.mpstate.click_location
if latlon is None:
print("Need click position for marker")
return
(lat, lon) = latlon
marker = 'flag'
text = ''
if len(args) > 0:
marker = args[0]
if len(args) > 1:
text = ' '.join(args[1:])
flag = marker + '.png'
icon = self.map.icon(flag)
self.map.add_object(mp_slipmap.SlipIcon(
'icon - %s [%u]' % (str(flag),self.icon_counter),
(float(lat),float(lon)),
icon, layer=3, rotation=0, follow=False))
self.icon_counter += 1
now = time.time()
tstr = datetime.datetime.fromtimestamp(now).strftime("%Y_%m_%d_%H_%M_%S")
subsec = now - math.floor(now)
millis = int(subsec * 1000)
fname = "marker_%s_%03u.json" % (tstr, millis)
gpi = self.master.messages.get('GLOBAL_POSITION_INT',None)
att = self.master.messages.get('ATTITUDE',None)
self.write_JSON(fname,'''{
"marker" : {{MARKER}},
"text" : "{{TEXT}}",
"tsec" : {{TIMESEC}},
"mlat" : {{LAT}},
"mlon" : {{LON}},
"vlat" : {{VLAT}},
"vlon" : {{VLON}},
"valt" : {{VALT}},
"gspeed" : {{GSPEED}},
"ghead" : {{GHEAD}},
"roll" : {{ROLL}},
"pitch" : {{PITCH}},
"yaw" : {{YAW}},
}
''', {
"TIMESEC" : now,
"MARKER" : marker,
"TEXT" : text,
"LAT" : lat,
"LON" : lon,
"VLAT" : "%.9f" % (gpi.lat*1.0e-7),
"VLON" : "%.9f" % (gpi.lon*1.0e-7),
"VALT" : gpi.alt*1.0e-3,
"GSPEED" : math.sqrt(gpi.vx**2+gpi.vy**2)*0.01,
"GHEAD" : gpi.hdg*0.01,
"ROLL" : math.degrees(att.roll),
"PITCH" : math.degrees(att.pitch),
"YAW" : math.degrees(att.yaw)
})
print("Wrote marker %s" % fname)
def cmd_map(self, args):
'''map commands'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if len(args) < 1:
print("usage: map <icon|set|menu|marker>")
elif args[0] == "menu":
self.cmd_menu(args[1:])
elif args[0] == "icon":
usage = "Usage: map icon <lat> <lon> <icon>"
flag = 'flag.png'
if len(args) > 2:
lat = args[1]
lon = args[2]
if len(args) > 3:
flag = args[3] + '.png'
elif self.mpstate.click_location is not None:
if len(args) >= 1:
# i.e. "map icon"
(lat, lon) = self.mpstate.click_location
if len(args) == 2:
# i.e. map icon barrell
flag = args[1]
else:
print(usage)
return
icon = self.map.icon(flag)
self.map.add_object(mp_slipmap.SlipIcon(
'icon - %s [%u]' % (str(flag),self.icon_counter),
(float(lat),float(lon)),
icon, layer=3, rotation=0, follow=False))
self.icon_counter += 1
elif args[0] == "marker":
self.cmd_map_marker(args[1:])
elif args[0] == "vehicletype":
if len(args) < 3:
print("Usage: map vehicletype SYSID TYPE")
else:
sysid = int(args[1])
vtype = int(args[2])
self.vehicle_type_override[sysid] = vtype
print("Set sysid %u to vehicle type %u" % (sysid, vtype))
elif args[0] == "circle":
self.cmd_map_circle(args[1:])
elif args[0] == "set":
self.map_settings.command(args[1:])
self.map.add_object(mp_slipmap.SlipBrightness(self.map_settings.brightness))
elif args[0] == "sethome":
self.cmd_set_home(args)
elif args[0] == "sethomepos":
self.cmd_set_homepos(args)
elif args[0] == "setorigin":
self.cmd_set_origin(args)
elif args[0] == "setoriginpos":
self.cmd_set_originpos(args)
elif args[0] == "zoom":
self.cmd_zoom(args)
elif args[0] == "center":
self.cmd_center(args)
elif args[0] == "follow":
self.cmd_follow(args)
elif args[0] == "clear":
self.cmd_clear(args)
elif args[0] == "setroi":
self.cmd_set_roi(args)
elif args[0] == "setposition":
self.cmd_set_position(args)
else:
print("usage: map <icon|set>")
def cmd_map_circle(self, args):
usage = '''
Usage: map circle <lat> <lon> <radius> <colour>
Usage: map circle <radius> <colour>
'''
lat = None
colour = None
# syntax 1, lat/lon/radius/colour
if len(args) == 4:
colour = args[3]
args = args[0:3]
if len(args) == 3:
lat = args[0]
lon = args[1]
radius = args[2]
# syntax 2, radius/colour, uses click position
if len(args) == 2:
colour = args[1]
args = args[0:1]
if len(args) == 1:
pos = self.mpstate.click_location
if pos is None:
print("Need click or location")
print(usage)
return
(lat, lon) = pos
radius = args[0]
if lat is None:
print(usage)
return
if colour is None:
colour = "red"
if colour == "red":
colour = (255,0,0)
elif colour == "green":
colour = (0,255,0)
elif colour == "blue":
colour = (0,0,255)
else:
colour = eval(colour)
circle = mp_slipmap.SlipCircle(
"circle %u" % self.circle_counter,
3,
(float(lat), float(lon)),
float(radius),
colour,
linewidth=self.map_settings.circle_linewidth,
)
self.map.add_object(circle)
self.circle_counter += 1
def colour_for_wp(self, wp_num):
'''return a tuple describing the colour a waypoint should appear on the map'''
wp = self.module('wp').wploader.wp(wp_num)
command = wp.command
return self._colour_for_wp_command.get(command, (0,255,0))
def label_for_waypoint(self, wp_num):
'''return the label the waypoint which should appear on the map'''
wp = self.module('wp').wploader.wp(wp_num)
command = wp.command
if command not in self._label_suffix_for_wp_command:
return str(wp_num)
return str(wp_num) + "(" + self._label_suffix_for_wp_command[command] + ")"
def display_waypoints(self):
'''display the waypoints'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
self.mission_list = self.module('wp').wploader.view_list()
polygons = self.module('wp').wploader.polygon_list()
self.map.add_object(mp_slipmap.SlipClearLayer('Mission'))
items = [MPMenuItem('WP Set', returnkey='popupMissionSet'),
MPMenuItem('WP Remove', returnkey='popupMissionRemove'),
MPMenuItem('WP Move', returnkey='popupMissionMove'),
MPMenuItem('WP Split', returnkey='popupMissionSplit'),
]
for i in range(len(polygons)):
p = polygons[i]
if len(p) > 1:
popup = MPMenuSubMenu('Popup', items)
self.map.add_object(mp_slipmap.SlipPolygon('mission %u' % i, p,
layer='Mission', linewidth=2, colour=ImageColor.getrgb(self.map_settings.mission_color),
arrow = self.map_settings.showdirection, popup_menu=popup))
labeled_wps = {}
self.map.add_object(mp_slipmap.SlipClearLayer('LoiterCircles'))
if not self.map_settings.showwpnum:
return
font_size = self.map_settings.font_size
for i in range(len(self.mission_list)):
next_list = self.mission_list[i]
for j in range(len(next_list)):
#label already printed for this wp?
if (next_list[j] not in labeled_wps):
label = self.label_for_waypoint(next_list[j])
colour = self.colour_for_wp(next_list[j])
self.map.add_object(mp_slipmap.SlipLabel(
'miss_cmd %u/%u' % (i,j), polygons[i][j], label, 'Mission', colour=colour, size=font_size))
if (self.map_settings.loitercircle and
self.module('wp').wploader.wp_is_loiter(next_list[j])):
wp = self.module('wp').wploader.wp(next_list[j])
if wp.command != mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT and wp.param3 != 0:
# wp radius and direction is defined by the mission
loiter_rad = wp.param3
elif wp.command == mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT and wp.param2 != 0:
# wp radius and direction is defined by the mission
loiter_rad = wp.param2
else:
# wp radius and direction is defined by the parameter
loiter_rad = self.get_mav_param('WP_LOITER_RAD')
self.map.add_object(mp_slipmap.SlipCircle('Loiter Circle %u' % (next_list[j] + 1), 'LoiterCircles', polygons[i][j],
loiter_rad, (255, 255, 255), 2, arrow = self.map_settings.showdirection))
labeled_wps[next_list[j]] = (i,j)
# Start: handling of PolyFence popup menu items
def polyfence_remove_circle(self, id):
'''called when a fence is right-clicked and remove is selected;
removes the circle
'''
(seq, type) = id.split(":")
self.module('fence').removecircle(int(seq))
def polyfence_move_circle(self, id):
'''called when a fence is right-clicked and move circle is selected; start
moving the circle
'''
(seq, t) = id.split(":")
self.moving_circle = int(seq)
def polyfence_set_circle_radius(self, id):
'''called when a fence is right-clicked and change-circle-radius is selected; next click sets the radius
'''
(seq, t) = id.split(":")
self.setting_circle_radius = int(seq)
def polyfence_remove_returnpoint(self, id):
'''called when a returnpoint is right-clicked and remove is selected;
removes the return point
'''
(seq, type) = id.split(":")
self.module('fence').removereturnpoint(int(seq))
def polyfence_remove_polygon(self, id):
'''called when a fence is right-clicked and remove is selected;
removes the polygon
'''
(seq, type) = id.split(":")
self.module('fence').removepolygon(int(seq))
def polyfence_remove_polygon_point(self, id, extra):
'''called when a fence is right-clicked and remove point is selected;
removes the polygon point
'''
(seq, type) = id.split(":")
self.module('fence').removepolygon_point(int(seq), int(extra))
def polyfence_add_polygon_point(self, id, extra):
'''called when a fence is right-clicked and add point is selected;
adds a polygon *before* this one in the list
'''
(seq, type) = id.split(":")
self.module('fence').addpolygon_point(int(seq), int(extra))
def polyfence_move_polygon_point(self, id, extra):
'''called when a fence is right-clicked and move point is selected; start
moving the polygon point
'''
(seq, t) = id.split(":")
self.moving_polygon_point = (int(seq), extra)
# End: handling of PolyFence popup menu items
def display_polyfences_circles(self, circles, colour):
'''draws circles in the PolyFence layer with colour colour'''
for circle in circles:
lat = circle.x
lng = circle.y
if circle.get_type() == 'MISSION_ITEM_INT':
lat *= 1e-7
lng *= 1e-7
items = [
MPMenuItem('Remove Circle', returnkey='popupPolyFenceRemoveCircle'),
MPMenuItem('Move Circle', returnkey='popupPolyFenceMoveCircle'),
MPMenuItem('Set Circle Radius w/click', returnkey='popupPolyFenceSetCircleRadius'),
]
popup = MPMenuSubMenu('Popup', items)
slipcircle = mp_slipmap.SlipCircle(
str(circle.seq) + ":circle", # key
"PolyFence", # layer
(lat, lng), # latlon
circle.param1, # radius
colour,
linewidth=2,
popup_menu=popup)
self.map.add_object(slipcircle)
def display_polyfences_inclusion_circles(self):
'''draws inclusion circles in the PolyFence layer with colour colour'''
inclusions = self.module('fence').inclusion_circles()
self.display_polyfences_circles(inclusions, (0, 255, 0))
def display_polyfences_exclusion_circles(self):
'''draws exclusion circles in the PolyFence layer with colour colour'''
exclusions = self.module('fence').exclusion_circles()
self.display_polyfences_circles(exclusions, (255, 0, 0))
def display_polyfences_polygons(self, polygons, colour):
'''draws polygons in the PolyFence layer with colour colour'''
for polygon in polygons:
points = []
for point in polygon:
lat = point.x
lng = point.y
if point.get_type() == 'MISSION_ITEM_INT':
lat *= 1e-7
lng *= 1e-7
points.append((lat, lng))
items = [
MPMenuItem('Remove Polygon', returnkey='popupPolyFenceRemovePolygon'),
]
if len(points) > 3:
items.append(MPMenuItem('Remove Polygon Point', returnkey='popupPolyFenceRemovePolygonPoint'))
items.append(MPMenuItem('Move Polygon Point', returnkey='popupPolyFenceMovePolygonPoint'))
items.append(MPMenuItem('Add Polygon Point', returnkey='popupPolyFenceAddPolygonPoint'))
popup = MPMenuSubMenu('Popup', items)
poly = mp_slipmap.UnclosedSlipPolygon(
str(polygon[0].seq) + ":poly", # key,
points,
layer='PolyFence',
linewidth=2,
colour=colour,
popup_menu=popup)
self.map.add_object(poly)
def display_polyfences_returnpoint(self):
returnpoint = self.module('fence').returnpoint()
if returnpoint is None:
return
lat = returnpoint.x
lng = returnpoint.y
if returnpoint.get_type() == 'MISSION_ITEM_INT':
lat *= 1e-7
lng *= 1e-7
popup = MPMenuSubMenu('Popup', [
MPMenuItem('Remove Return Point', returnkey='popupPolyFenceRemoveReturnPoint'),
])
self.map.add_object(mp_slipmap.SlipCircle(
str(returnpoint.seq) + ":returnpoint", # key
'PolyFence',
(lat, lng),
10,
(255,127,127),
2,
popup_menu=popup,
))
def display_polyfences_inclusion_polygons(self):
'''draws inclusion polygons in the PolyFence layer with colour colour'''
inclusions = self.module('fence').inclusion_polygons()
self.display_polyfences_polygons(inclusions, (0, 255, 0))
def display_polyfences_exclusion_polygons(self):
'''draws exclusion polygons in the PolyFence layer with colour colour'''
exclusions = self.module('fence').exclusion_polygons()
self.display_polyfences_polygons(exclusions, (255, 0, 0))
def display_polyfences(self):
'''draws PolyFence items in the PolyFence layer'''
self.map.add_object(mp_slipmap.SlipClearLayer('PolyFence'))
self.display_polyfences_inclusion_circles()
self.display_polyfences_exclusion_circles()
self.display_polyfences_inclusion_polygons()
self.display_polyfences_exclusion_polygons()
self.display_polyfences_returnpoint()
def display_fence(self):
'''display the fence'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if getattr(self.module('fence'), "cmd_addcircle", None) is not None:
# we're doing fences via MissionItemProtocol and thus have
# much more work to do
return self.display_polyfences()
# traditional module, a single polygon fence transfered using
# FENCE_POINT protocol:
points = self.module('fence').fenceloader.polygon()
self.map.add_object(mp_slipmap.SlipClearLayer('Fence'))
if len(points) > 1:
popup = MPMenuSubMenu('Popup',
items=[MPMenuItem('FencePoint Remove', returnkey='popupFenceRemove'),
MPMenuItem('FencePoint Move', returnkey='popupFenceMove')])
self.map.add_object(mp_slipmap.SlipPolygon('Fence', points, layer=1,
linewidth=2, colour=(0,255,0), popup_menu=popup))
else:
self.map.remove_object('Fence')
def closest_waypoint(self, latlon):
'''find closest waypoint to a position'''
(lat, lon) = latlon
best_distance = -1
closest = -1
for i in range(self.module('wp').wploader.count()):
w = self.module('wp').wploader.wp(i)
distance = mp_util.gps_distance(lat, lon, w.x, w.y)
if best_distance == -1 or distance < best_distance:
best_distance = distance
closest = i
if best_distance < 20:
return closest
else:
return -1
def remove_rally(self, key):
'''remove a rally point'''
a = key.split(' ')
if a[0] != 'Rally' or len(a) != 2:
print("Bad rally object %s" % key)
return
i = int(a[1])
self.mpstate.functions.process_stdin('rally remove %u' % i)
def move_rally(self, key):
'''move a rally point'''
a = key.split(' ')
if a[0] != 'Rally' or len(a) != 2:
print("Bad rally object %s" % key)
return
i = int(a[1])
self.moving_rally = i
def selection_index_to_idx(self, key, selection_index):
'''return a mission idx from a selection_index'''
a = key.split(' ')
if a[0] != 'mission' or len(a) != 2:
print("Bad mission object %s" % key)
return None
midx = int(a[1])
if midx < 0 or midx >= len(self.mission_list):
print("Bad mission index %s" % key)
return None
mlist = self.mission_list[midx]
if selection_index < 0 or selection_index >= len(mlist):
print("Bad mission polygon %s" % selection_index)
return None
idx = mlist[selection_index]
return idx
def move_mission(self, key, selection_index):
'''move a mission point'''
idx = self.selection_index_to_idx(key, selection_index)
self.moving_wp = idx
print("Moving wp %u" % idx)
def remove_mission(self, key, selection_index):
'''remove a mission point'''
idx = self.selection_index_to_idx(key, selection_index)
self.mpstate.functions.process_stdin('wp remove %u' % idx)
def split_mission_wp(self, key, selection_index):
'''add wp before this one'''
idx = self.selection_index_to_idx(key, selection_index)
self.mpstate.functions.process_stdin('wp split %u' % idx)
def remove_fencepoint(self, key, selection_index):
'''remove a fence point'''
self.mpstate.functions.process_stdin('fence remove %u' % (selection_index+1))
def move_fencepoint(self, key, selection_index):
'''move a fence point'''
self.moving_fencepoint = selection_index
print("Moving fence point %u" % selection_index)
def set_mission(self, key, selection_index):
'''set a mission point'''
idx = self.selection_index_to_idx(key, selection_index)
self.mpstate.functions.process_stdin('wp set %u' % idx)
def handle_menu_event(self, obj):
'''handle a popup menu event from the map'''
menuitem = obj.menuitem
if menuitem.returnkey.startswith('# '):
cmd = menuitem.returnkey[2:]
if menuitem.handler is not None:
if menuitem.handler_result is None:
return
cmd += menuitem.handler_result
self.mpstate.functions.process_stdin(cmd)
elif menuitem.returnkey == 'popupRallyRemove':
self.remove_rally(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupRallyMove':
self.move_rally(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupMissionSet':
self.set_mission(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupMissionRemove':
self.remove_mission(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupMissionMove':
self.move_mission(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupMissionSplit':
self.split_mission_wp(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupFenceMove':
self.move_fencepoint(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupPolyFenceRemoveCircle':
self.polyfence_remove_circle(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupPolyFenceMoveCircle':
self.polyfence_move_circle(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupPolyFenceSetCircleRadius':
self.polyfence_set_circle_radius(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupPolyFenceRemoveReturnPoint':
self.polyfence_remove_returnpoint(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupPolyFenceRemovePolygon':
self.polyfence_remove_polygon(obj.selected[0].objkey)
elif menuitem.returnkey == 'popupPolyFenceMovePolygonPoint':
self.polyfence_move_polygon_point(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupPolyFenceAddPolygonPoint':
self.polyfence_add_polygon_point(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'popupPolyFenceRemovePolygonPoint':
self.polyfence_remove_polygon_point(obj.selected[0].objkey, obj.selected[0].extra_info)
elif menuitem.returnkey == 'showPosition':
self.show_position()
elif menuitem.returnkey == 'printGoogleMapsLink':
self.print_google_maps_link()
elif menuitem.returnkey == 'setServiceTerrain':
self.module('terrain').cmd_terrain(['set', 'source', menuitem.get_choice()])
def map_callback(self, obj):
'''called when an event happens on the slipmap'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if isinstance(obj, mp_slipmap.SlipMenuEvent):
self.handle_menu_event(obj)
return
if not isinstance(obj, mp_slipmap.SlipMouseEvent):
return
if obj.event.leftIsDown and self.moving_rally is not None:
self.mpstate.click(obj.latlon)
self.mpstate.functions.process_stdin("rally move %u" % self.moving_rally)
self.moving_rally = None
return
if obj.event.rightIsDown and self.moving_rally is not None:
print("Cancelled rally move")
self.moving_rally = None
return
if obj.event.leftIsDown and self.moving_wp is not None:
self.mpstate.click(obj.latlon)
self.mpstate.functions.process_stdin("wp move %u" % self.moving_wp)
self.moving_wp = None
return
if obj.event.leftIsDown and self.moving_fencepoint is not None:
self.mpstate.click(obj.latlon)
self.mpstate.functions.process_stdin("fence move %u" % (self.moving_fencepoint+1))
self.moving_fencepoint = None
return
if obj.event.rightIsDown and self.moving_wp is not None:
print("Cancelled wp move")
self.moving_wp = None
return
if obj.event.leftIsDown and self.moving_polygon_point is not None:
self.mpstate.click(obj.latlon)
(seq, offset) = self.moving_polygon_point
self.mpstate.functions.process_stdin("fence movepolypoint %u %u" % (int(seq), int(offset)))
self.moving_polygon_point = None
return
if obj.event.rightIsDown and self.moving_polygon_point is not None:
print("Cancelled polygon point move")
self.moving_polygon_point = None
return
if obj.event.rightIsDown and self.moving_fencepoint is not None:
print("Cancelled fence move")
self.moving_fencepoint = None
return
elif obj.event.leftIsDown:
if (self.mpstate.click_time is None or
time.time() - self.mpstate.click_time > 0.1):
self.mpstate.click(obj.latlon)
self.drawing_update()
if obj.event.rightIsDown:
if self.draw_callback is not None:
self.drawing_end()
return
if (self.mpstate.click_time is None or
time.time() - self.mpstate.click_time > 0.1):
self.mpstate.click(obj.latlon)
if obj.event.leftIsDown and self.moving_circle is not None:
self.mpstate.click(obj.latlon)
seq = self.moving_circle
self.mpstate.functions.process_stdin("fence movecircle %u" % int(seq))
self.moving_circle = None
return
if obj.event.rightIsDown and self.moving_circle is not None:
print("Cancelled circle move")
self.moving_circle = None
return
if obj.event.leftIsDown and self.setting_circle_radius is not None:
self.mpstate.click(obj.latlon)
seq = self.setting_circle_radius
self.mpstate.functions.process_stdin("fence setcircleradius %u" % int(seq))
self.setting_circle_radius = None
return
if obj.event.rightIsDown and self.setting_circle_radius is not None:
print("Cancelled circle move")
self.setting_circle_radius = None
return
def click_updated(self):
'''called when the click position has changed'''
if self.map_settings.showclicktime == 0:
return
self.map.add_object(mp_slipmap.SlipClickLocation(self.mpstate.click_location, timeout=self.map_settings.showclicktime))
def unload(self):
'''unload module'''
super(MapModule, self).unload()
self.map.close()
if self.instance == 1:
self.mpstate.map = None
self.mpstate.map_functions = {}
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.map.is_alive():
self.needs_unloading = True
# check for any events from the map
self.map.check_events()
def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None):
'''add a vehicle to the map'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if vehicle_type is None:
vehicle_type = self.vehicle_type_name
if name in self.have_vehicle and self.have_vehicle[name] == vehicle_type:
return
self.have_vehicle[name] = vehicle_type
icon = self.map.icon(colour + vehicle_type + '.png')
self.map.add_object(mp_slipmap.SlipIcon(name, (0,0), icon, layer=3, rotation=0, follow=follow,
trail=mp_slipmap.SlipTrail()))
def remove_vehicle_icon(self, name, vehicle_type=None):
from MAVProxy.modules.mavproxy_map import mp_slipmap
if vehicle_type is None:
vehicle_type = self.vehicle_type_name
if name not in self.have_vehicle or self.have_vehicle[name] != vehicle_type:
return
del self.have_vehicle[name]
self.map.remove_object(name)
def drawing_update(self):
'''update line drawing'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if self.draw_callback is None:
return
self.draw_line.append(self.mpstate.click_location)
if len(self.draw_line) > 1:
self.map.add_object(mp_slipmap.SlipPolygon('drawing', self.draw_line,
layer='Drawing', linewidth=2, colour=self.draw_colour))
def drawing_end(self):
'''end line drawing'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if self.draw_callback is None:
return
self.draw_callback(self.draw_line)
self.draw_callback = None
self.map.add_object(mp_slipmap.SlipDefaultPopup(self.default_popup, combine=True))
self.map.add_object(mp_slipmap.SlipClearLayer('Drawing'))
def draw_lines(self, callback, colour=(128,128,255)):
'''draw a series of connected lines on the map, calling callback when done'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
self.draw_callback = callback
self.draw_colour = colour
self.draw_line = []
self.map.add_object(mp_slipmap.SlipDefaultPopup(None))
def cmd_set_home(self, args):
'''called when user selects "Set Home (with height)" on map'''
(lat, lon) = (self.mpstate.click_location[0], self.mpstate.click_location[1])
alt = self.module('terrain').ElevationModel.GetElevation(lat, lon)
print("Setting home to: ", lat, lon, alt)
self.master.mav.command_long_send(
self.settings.target_system, self.settings.target_component,
mavutil.mavlink.MAV_CMD_DO_SET_HOME,
1, # set position
0, # param1
0, # param2
0, # param3
0, # param4
lat, # lat
lon, # lon
alt) # param7
def cmd_set_homepos(self, args):
'''called when user selects "Set Home" on map'''
(lat, lon) = (self.mpstate.click_location[0], self.mpstate.click_location[1])
print("Setting home to: ", lat, lon)
self.master.mav.command_int_send(
self.settings.target_system, self.settings.target_component,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT,
mavutil.mavlink.MAV_CMD_DO_SET_HOME,
1, # current
0, # autocontinue
0, # param1
0, # param2
0, # param3
0, # param4
int(lat*1e7), # lat
int(lon*1e7), # lon
0) # no height change
def cmd_set_roi(self, args):
'''called when user selects "Set ROI" on map'''
(lat, lon) = (self.mpstate.click_location[0], self.mpstate.click_location[1])
alt = self.module('terrain').ElevationModel.GetElevation(lat, lon)
print("Setting ROI to: ", lat, lon, alt)
self.current_ROI = (lat,lon,alt)
self.master.mav.command_int_send(
self.settings.target_system, self.settings.target_component,
mavutil.mavlink.MAV_FRAME_GLOBAL,
mavutil.mavlink.MAV_CMD_DO_SET_ROI_LOCATION,
0, # current
0, # autocontinue
0, # param1
0, # param2
0, # param3
0, # param4
int(lat*1e7), # lat
int(lon*1e7), # lon
alt) # param7
def cmd_set_position(self, args):
'''called when user selects "Set Position" on map'''
(lat, lon) = (self.mpstate.click_location[0], self.mpstate.click_location[1])
accuracy = self.map_settings.setpos_accuracy
print("Setting position to (%.7f %.7f) with accuracy %.1fm" % (lat, lon, accuracy))
now = time.time()
self.master.mav.command_int_send(
self.settings.target_system, self.settings.target_component,
mavutil.mavlink.MAV_FRAME_GLOBAL,
mavutil.mavlink.MAV_CMD_EXTERNAL_POSITION_ESTIMATE,
0, # current
0, # autocontinue
time.time() - self.mpstate.start_time_s, # transmission_time
0, # processing_time
self.map_settings.setpos_accuracy, # accuracy
0, # param4
int(lat*1e7), # lat
int(lon*1e7), # lon
float('NaN')) # alt, send as NaN for ignore
def cmd_set_origin(self, args):
'''called when user selects "Set Origin (with height)" on map'''
(lat, lon) = (self.mpstate.click_location[0], self.mpstate.click_location[1])
alt = self.module('terrain').ElevationModel.GetElevation(lat, lon)
print("Setting origin to: ", lat, lon, alt)
self.master.mav.set_gps_global_origin_send(
self.settings.target_system,
int(lat*10000000), # lat
int(lon*10000000), # lon
int(alt*1000)) # param7
def cmd_set_originpos(self, args):
'''called when user selects "Set Origin" on map'''
(lat, lon) = (self.mpstate.click_location[0], self.mpstate.click_location[1])
print("Setting origin to: ", lat, lon)
self.master.mav.set_gps_global_origin_send(
self.settings.target_system,
int(lat*10000000), # lat
int(lon*10000000), # lon
0*1000) # no height change
def cmd_zoom(self, args):
'''control zoom'''
if len(args) < 2:
print("map zoom WIDTH(m)")
return
ground_width = float(args[1])
self.map.set_zoom(ground_width)
def cmd_center(self, args):
'''control center of view'''
if len(args) < 3:
print("map center LAT LON")
return
lat = float(args[1])
lon = float(args[2])
self.map.set_center(lat, lon)
def cmd_follow(self, args):
'''control following of vehicle'''
if len(args) < 2:
print("map follow 0|1")
return
follow = int(args[1])
self.map.set_follow(follow)
def cmd_clear(self, args):
'''clear displayed vehicle icons'''
self.map.add_object(mp_slipmap.SlipClearLayer(3))
self.have_vehicle = {}
def set_secondary_vehicle_position(self, m):
'''show 2nd vehicle on map'''
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
# hack for OBC2016
alt = self.module('terrain').ElevationModel.GetElevation(lat, lon)
agl = m.alt * 0.001 - alt
agl_s = str(int(agl)) + 'm'
self.create_vehicle_icon('VehiclePos2', 'blue', follow=False, vehicle_type='plane')
self.map.set_position('VehiclePos2', (lat, lon), rotation=heading, label=agl_s, colour=(0,255,255))
def update_vehicle_icon(self, name, vehicle, colour, m, display):
'''update display of a vehicle on the map. m is expected to store
location in lat/lng *1e7
'''
latlon = (m.lat*1.0e-7, m.lng*1.0e-7)
yaw = math.degrees(m.yaw)
self.update_vehicle_icon_to_loc(name, vehicle, colour, display, latlon, yaw)
def update_vehicle_icon_to_loc(self, name, vehicle, colour, display, latlon, yaw):
'''update display of a vehicle on the map at latlon
'''
key = name + vehicle
# don't display this icon if the settings don't say so:
if not display:
# remove from display if it was being displayed:
self.remove_vehicle_icon(key)
return
# create the icon if we weren't displaying:
self.create_vehicle_icon(key, colour)
# update placement on map:
self.map.set_position(key, latlon, rotation=yaw)
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
mtype = m.get_type()
sysid = m.get_srcSystem()
if mtype == "HEARTBEAT" or mtype == "HIGH_LATENCY2":
vname = None
vtype = self.vehicle_type_override.get(sysid, m.type)
if vtype 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]:
vname = 'plane'
elif vtype in [mavutil.mavlink.MAV_TYPE_GROUND_ROVER]:
vname = 'rover'
elif vtype in [mavutil.mavlink.MAV_TYPE_SUBMARINE]:
vname = 'sub'
elif vtype in [mavutil.mavlink.MAV_TYPE_SURFACE_BOAT]:
vname = 'boat'
elif vtype in [mavutil.mavlink.MAV_TYPE_QUADROTOR,
mavutil.mavlink.MAV_TYPE_HEXAROTOR,
mavutil.mavlink.MAV_TYPE_OCTOROTOR,
mavutil.mavlink.MAV_TYPE_TRICOPTER,
mavutil.mavlink.MAV_TYPE_DODECAROTOR,
mavutil.mavlink.MAV_TYPE_DECAROTOR]:
vname = 'copter'
elif vtype in [mavutil.mavlink.MAV_TYPE_COAXIAL]:
vname = 'singlecopter'
elif vtype in [mavutil.mavlink.MAV_TYPE_HELICOPTER]:
vname = 'heli'
elif vtype in [mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER]:
vname = 'antenna'
elif vtype in [mavutil.mavlink.MAV_TYPE_AIRSHIP]:
vname = 'blimp'
if vname is not None:
self.vehicle_type_by_sysid[sysid] = vname
if not sysid in self.vehicle_type_by_sysid:
self.vehicle_type_by_sysid[sysid] = 'plane'
self.vehicle_type_name = self.vehicle_type_by_sysid[sysid]
# this is the beginnings of allowing support for multiple vehicles
# in the air at the same time
vehicle = 'Vehicle%u' % m.get_srcSystem()
if mtype == "SIMSTATE":
self.update_vehicle_icon('Sim', vehicle, 'green', m, self.map_settings.showsimpos)
elif mtype == "AHRS2" and self.map_settings.showahrs2pos:
self.update_vehicle_icon('AHRS2', vehicle, 'purple', m, self.map_settings.showahrs2pos)
elif mtype == "AHRS3" and self.map_settings.showahrs3pos:
self.update_vehicle_icon('AHRS3', vehicle, 'orange', m, self.map_settings.showahrs3pos)
elif mtype == "GPS_RAW_INT":
(lat, lon) = (m.lat*1.0e-7, m.lon*1.0e-7)
if lat != 0 or lon != 0:
if m.vel > 300 or m.get_srcSystem() not in self.lat_lon_heading:
heading = m.cog*0.01
else:
(_,_,heading) = self.lat_lon_heading[m.get_srcSystem()]
self.update_vehicle_icon_to_loc('GPS', vehicle, 'blue', self.map_settings.showgpspos, (lat, lon), heading)
elif mtype == "GPS2_RAW":
(lat, lon) = (m.lat*1.0e-7, m.lon*1.0e-7)
if lat != 0 or lon != 0:
self.update_vehicle_icon_to_loc('GPS2', vehicle, 'green', self.map_settings.showgps2pos, (lat, lon), m.cog*0.01)
elif mtype == 'GLOBAL_POSITION_INT':
(lat, lon, heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01)
self.lat_lon_heading[m.get_srcSystem()] = (lat,lon,heading)
if self.map_settings.showahrspos:
if abs(lat) > 1.0e-3 or abs(lon) > 1.0e-3:
self.have_global_position = True
self.create_vehicle_icon('Pos' + vehicle, 'red', follow=True)
if len(self.vehicle_type_by_sysid) > 1:
label = str(sysid)
else:
label = None
self.map.set_position('Pos' + vehicle, (lat, lon), rotation=heading, label=label, colour=(255,255,255))
self.map.set_follow_object('Pos' + vehicle, self.message_is_from_primary_vehicle(m))
else:
self.remove_vehicle_icon('Pos' + vehicle)
elif mtype == "HIGH_LATENCY2" and self.map_settings.showahrspos:
(lat, lon) = (m.latitude*1.0e-7, m.longitude*1.0e-7)
if lat != 0 or lon != 0:
cog = m.heading * 2
self.have_global_position = True
self.create_vehicle_icon('Pos' + vehicle, 'red', follow=True)
if len(self.vehicle_type_by_sysid) > 1:
label = str(sysid)
else:
label = None
self.map.set_position('Pos' + vehicle, (lat, lon), rotation=cog, label=label, colour=(255,255,255))
self.map.set_follow_object('Pos' + vehicle, self.message_is_from_primary_vehicle(m))
elif mtype == 'HOME_POSITION':
(lat, lon) = (m.latitude*1.0e-7, m.longitude*1.0e-7)
icon = self.map.icon('home.png')
self.map.add_object(mp_slipmap.SlipIcon('HOME_POSITION',
(lat,lon),
icon, layer=3, rotation=0, follow=False))
elif mtype == "NAV_CONTROLLER_OUTPUT":
tlayer = 'Trajectory%u' % m.get_srcSystem()
if (self.master.flightmode in [ "AUTO", "GUIDED", "LOITER", "RTL", "QRTL", "QLOITER", "QLAND", "FOLLOW", "ZIGZAG" ] and
m.get_srcSystem() in self.lat_lon_heading):
(lat,lon,_) = self.lat_lon_heading[m.get_srcSystem()]
trajectory = [ (lat, lon),
mp_util.gps_newpos(lat, lon, m.target_bearing, m.wp_dist) ]
self.map.add_object(mp_slipmap.SlipPolygon('trajectory',
trajectory, layer=tlayer,
linewidth=2, colour=(255,0,180)))
self.trajectory_layers.add(tlayer)
else:
if tlayer in self.trajectory_layers:
self.map.add_object(mp_slipmap.SlipClearLayer(tlayer))
self.trajectory_layers.remove(tlayer)
elif mtype == "POSITION_TARGET_GLOBAL_INT":
# FIXME: base this off SYS_STATUS.MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL?
if not m.get_srcSystem() in self.lat_lon_heading:
return
tlayer = 'PostionTarget%u' % m.get_srcSystem()
(lat,lon,_) = self.lat_lon_heading[m.get_srcSystem()]
if (self.master.flightmode in [ "AUTO", "GUIDED", "LOITER", "RTL", "QRTL", "QLOITER", "QLAND", "FOLLOW" ]):
lat_float = m.lat_int*1e-7
lon_float = m.lon_int*1e-7
vec = [ (lat_float, lon_float),
(lat, lon) ]
self.map.add_object(mp_slipmap.SlipPolygon('position_target',
vec,
layer=tlayer,
linewidth=2,
colour=(0,255,0)))
else:
self.map.add_object(mp_slipmap.SlipClearLayer(tlayer))
if not self.message_is_from_primary_vehicle(m):
# the rest should only be done for the primary vehicle
return
self.check_redisplay_waypoints()
self.check_redisplay_fencepoints()
self.check_redisplay_rallypoints()
# check for any events from the map
self.map.check_events()
def check_redisplay_waypoints(self):
# if the waypoints have changed, redisplay
wp_module = self.module('wp')
if wp_module is None:
'''wp nodule not loaded'''
return
last_wp_change = wp_module.wploader.last_change
if self.wp_change_time != last_wp_change and abs(time.time() - last_wp_change) > 1:
self.wp_change_time = last_wp_change
self.display_waypoints()
#this may have affected the landing lines from the rally points:
self.rally_change_time = time.time()
def check_redisplay_fencepoints(self):
# if the fence has changed, redisplay
fence_module = self.module('fence')
if fence_module is not None:
if hasattr(fence_module, 'last_change'):
# new fence module
last_change = fence_module.last_change()
else:
# old fence module
last_change = fence_module.fenceloader.last_change
if self.fence_change_time != last_change:
self.fence_change_time = last_change
self.display_fence()
def check_redisplay_rallypoints(self):
# if the rallypoints have changed, redisplay
if (self.module('rally') and
self.rally_change_time != self.module('rally').last_change()):
self.rally_change_time = self.module('rally').last_change()
icon = self.map.icon('rallypoint.png')
self.map.add_object(mp_slipmap.SlipClearLayer('RallyPoints'))
for i in range(self.module('rally').rally_count()):
rp = self.module('rally').rally_point(i)
popup = MPMenuSubMenu('Popup',
items=[MPMenuItem('Rally Remove', returnkey='popupRallyRemove'),
MPMenuItem('Rally Move', returnkey='popupRallyMove')])
self.map.add_object(mp_slipmap.SlipIcon('Rally %u' % (i+1), (rp.lat*1.0e-7, rp.lng*1.0e-7), icon,
layer='RallyPoints', rotation=0, follow=False,
popup_menu=popup))
loiter_rad = self.get_mav_param('WP_LOITER_RAD')
if self.map_settings.rallycircle:
self.map.add_object(mp_slipmap.SlipCircle('Rally Circ %u' % (i+1), 'RallyPoints', (rp.lat*1.0e-7, rp.lng*1.0e-7),
loiter_rad, (255,255,0), 2, arrow = self.map_settings.showdirection))
#draw a line between rally point and nearest landing point
nearest_land_wp = None
nearest_distance = 10000000.0
for j in range(self.module('wp').wploader.count()):
w = self.module('wp').wploader.wp(j)
if (w.command == 21): #if landing waypoint
#get distance between rally point and this waypoint
dis = mp_util.gps_distance(w.x, w.y, rp.lat*1.0e-7, rp.lng*1.0e-7)
if (dis < nearest_distance):
nearest_land_wp = w
nearest_distance = dis
if nearest_land_wp is not None:
points = []
#tangential approach?
if self.get_mav_param('LAND_BREAK_PATH') == 0:
theta = math.degrees(math.atan(loiter_rad / nearest_distance))
tan_dis = math.sqrt(nearest_distance * nearest_distance - (loiter_rad * loiter_rad))
ral_bearing = mp_util.gps_bearing(nearest_land_wp.x, nearest_land_wp.y,rp.lat*1.0e-7, rp.lng*1.0e-7)
points.append(mp_util.gps_newpos(nearest_land_wp.x,nearest_land_wp.y, ral_bearing + theta, tan_dis))
else: #not tangential approach
points.append((rp.lat*1.0e-7, rp.lng*1.0e-7))
points.append((nearest_land_wp.x, nearest_land_wp.y))
self.map.add_object(mp_slipmap.SlipPolygon('Rally Land %u' % (i+1), points, 'RallyPoints', (255,255,0), 2))
|
class MapModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def add_menu(self, menu):
'''add to the default popup menu'''
pass
def cmd_menu_add(self, args):
'''add to map menus'''
pass
def cmd_menu_add(self, args):
'''control console menus'''
pass
def remove_menu(self, menu):
'''add to the default popup menu'''
pass
def show_position(self):
'''show map position click information'''
pass
def print_google_maps_link(self):
'''show map position click information'''
pass
def write_JSON(self, fname, template, vardict):
'''write a JSON file in log directory'''
pass
def cmd_map_marker(self, args, latlon=None):
'''add a map marker'''
pass
def cmd_map_marker(self, args, latlon=None):
'''map commands'''
pass
def cmd_map_circle(self, args):
pass
def colour_for_wp(self, wp_num):
'''return a tuple describing the colour a waypoint should appear on the map'''
pass
def label_for_waypoint(self, wp_num):
'''return the label the waypoint which should appear on the map'''
pass
def display_waypoints(self):
'''display the waypoints'''
pass
def polyfence_remove_circle(self, id):
'''called when a fence is right-clicked and remove is selected;
removes the circle
'''
pass
def polyfence_move_circle(self, id):
'''called when a fence is right-clicked and move circle is selected; start
moving the circle
'''
pass
def polyfence_set_circle_radius(self, id):
'''called when a fence is right-clicked and change-circle-radius is selected; next click sets the radius
'''
pass
def polyfence_remove_returnpoint(self, id):
'''called when a returnpoint is right-clicked and remove is selected;
removes the return point
'''
pass
def polyfence_remove_polygon(self, id):
'''called when a fence is right-clicked and remove is selected;
removes the polygon
'''
pass
def polyfence_remove_polygon_point(self, id, extra):
'''called when a fence is right-clicked and remove point is selected;
removes the polygon point
'''
pass
def polyfence_add_polygon_point(self, id, extra):
'''called when a fence is right-clicked and add point is selected;
adds a polygon *before* this one in the list
'''
pass
def polyfence_move_polygon_point(self, id, extra):
'''called when a fence is right-clicked and move point is selected; start
moving the polygon point
'''
pass
def display_polyfences_circles(self, circles, colour):
'''draws circles in the PolyFence layer with colour colour'''
pass
def display_polyfences_inclusion_circles(self):
'''draws inclusion circles in the PolyFence layer with colour colour'''
pass
def display_polyfences_exclusion_circles(self):
'''draws exclusion circles in the PolyFence layer with colour colour'''
pass
def display_polyfences_polygons(self, polygons, colour):
'''draws polygons in the PolyFence layer with colour colour'''
pass
def display_polyfences_returnpoint(self):
pass
def display_polyfences_inclusion_polygons(self):
'''draws inclusion polygons in the PolyFence layer with colour colour'''
pass
def display_polyfences_exclusion_polygons(self):
'''draws exclusion polygons in the PolyFence layer with colour colour'''
pass
def display_polyfences_circles(self, circles, colour):
'''draws PolyFence items in the PolyFence layer'''
pass
def display_fence(self):
'''display the fence'''
pass
def closest_waypoint(self, latlon):
'''find closest waypoint to a position'''
pass
def remove_rally(self, key):
'''remove a rally point'''
pass
def move_rally(self, key):
'''move a rally point'''
pass
def selection_index_to_idx(self, key, selection_index):
'''return a mission idx from a selection_index'''
pass
def move_mission(self, key, selection_index):
'''move a mission point'''
pass
def remove_mission(self, key, selection_index):
'''remove a mission point'''
pass
def split_mission_wp(self, key, selection_index):
'''add wp before this one'''
pass
def remove_fencepoint(self, key, selection_index):
'''remove a fence point'''
pass
def move_fencepoint(self, key, selection_index):
'''move a fence point'''
pass
def set_mission(self, key, selection_index):
'''set a mission point'''
pass
def handle_menu_event(self, obj):
'''handle a popup menu event from the map'''
pass
def map_callback(self, obj):
'''called when an event happens on the slipmap'''
pass
def click_updated(self):
'''called when the click position has changed'''
pass
def unload(self):
'''unload module'''
pass
def idle_task(self):
pass
def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None):
'''add a vehicle to the map'''
pass
def remove_vehicle_icon(self, name, vehicle_type=None):
pass
def drawing_update(self):
'''update line drawing'''
pass
def drawing_end(self):
'''end line drawing'''
pass
def draw_lines(self, callback, colour=(128,128,255)):
'''draw a series of connected lines on the map, calling callback when done'''
pass
def cmd_set_home(self, args):
'''called when user selects "Set Home (with height)" on map'''
pass
def cmd_set_homepos(self, args):
'''called when user selects "Set Home" on map'''
pass
def cmd_set_roi(self, args):
'''called when user selects "Set ROI" on map'''
pass
def cmd_set_position(self, args):
'''called when user selects "Set Position" on map'''
pass
def cmd_set_origin(self, args):
'''called when user selects "Set Origin (with height)" on map'''
pass
def cmd_set_originpos(self, args):
'''called when user selects "Set Origin" on map'''
pass
def cmd_zoom(self, args):
'''control zoom'''
pass
def cmd_center(self, args):
'''control center of view'''
pass
def cmd_follow(self, args):
'''control following of vehicle'''
pass
def cmd_clear(self, args):
'''clear displayed vehicle icons'''
pass
def set_secondary_vehicle_position(self, m):
'''show 2nd vehicle on map'''
pass
def update_vehicle_icon(self, name, vehicle, colour, m, display):
'''update display of a vehicle on the map. m is expected to store
location in lat/lng *1e7
'''
pass
def update_vehicle_icon_to_loc(self, name, vehicle, colour, display, latlon, yaw):
'''update display of a vehicle on the map at latlon
'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def check_redisplay_waypoints(self):
pass
def check_redisplay_fencepoints(self):
pass
def check_redisplay_rallypoints(self):
pass
| 69 | 60 | 18 | 1 | 16 | 3 | 4 | 0.17 | 1 | 25 | 16 | 0 | 68 | 33 | 68 | 106 | 1,306 | 129 | 1,059 | 282 | 976 | 178 | 773 | 282 | 690 | 36 | 2 | 5 | 248 |
7,005 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap.MPSlipMap
|
class MPSlipMap():
'''
a generic map viewer widget for use in mavproxy
'''
def __init__(self,
title='SlipMap',
lat=-35.362938,
lon=149.165085,
width=800,
height=600,
ground_width=1000,
tile_delay=0.3,
service="MicrosoftSat",
max_zoom=19,
debug=False,
brightness=0,
elevation=None,
download=True,
show_flightmode_legend=True,
timelim_pipe=None):
self.lat = lat
self.lon = lon
self.width = width
self.height = height
self.ground_width = ground_width
self.download = download
self.service = service
self.tile_delay = tile_delay
self.debug = debug
self.max_zoom = max_zoom
self.elevation = elevation
self.oldtext = None
self.brightness = brightness
self.legend = show_flightmode_legend
self.timelim_pipe = timelim_pipe
self.drag_step = 10
self.title = title
self.app_ready = multiproc.Event()
self.event_queue = multiproc.Queue()
self.object_queue = multiproc.Queue()
self.close_window = multiproc.Semaphore()
self.close_window.acquire()
self.child = multiproc.Process(target=self.child_task)
self.child.start()
self._callbacks = set()
# ensure the map application is ready before returning
if not self._wait_ready(timeout=5.0):
raise Exception("map not ready")
def child_task(self):
'''child process - this holds all the GUI elements'''
mp_util.child_close_fds()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.mavproxy_map.mp_slipmap_ui import MPSlipMapFrame
state = self
self.mt = mp_tile.MPTile(download=self.download,
service=self.service,
tile_delay=self.tile_delay,
debug=self.debug,
max_zoom=self.max_zoom)
state.layers = {}
state.info = {}
state.need_redraw = True
self.app = wx.App(False)
self.app.SetExitOnFrameDelete(True)
self.app.frame = MPSlipMapFrame(state=self)
self.app.frame.Show()
self.app_ready.set()
self.app.MainLoop()
def close(self):
'''close the window'''
self.close_window.release()
count=0
while self.child.is_alive() and count < 30: # 3 seconds to die...
time.sleep(0.1) #?
count+=1
if self.child.is_alive():
self.child.terminate()
self.child.join()
def is_alive(self):
'''check if graph is still going'''
return self.child.is_alive()
def add_object(self, obj):
'''add or update an object on the map'''
self.object_queue.put(obj)
def remove_object(self, key):
'''remove an object on the map by key'''
self.object_queue.put(SlipRemoveObject(key))
def set_zoom(self, ground_width):
'''set ground width of view'''
self.object_queue.put(SlipZoom(ground_width))
def set_center(self, lat, lon):
'''set center of view'''
self.object_queue.put(SlipCenter((lat,lon)))
def set_follow(self, enable):
'''set follow on/off'''
self.object_queue.put(SlipFollow(enable))
def set_follow_object(self, key, enable):
'''set follow on/off on an object'''
self.object_queue.put(SlipFollowObject(key, enable))
def hide_object(self, key, hide=True):
'''hide an object on the map by key'''
self.object_queue.put(SlipHideObject(key, hide))
def set_position(self, key, latlon, layer='', rotation=0, label=None, colour=None):
'''move an object on the map'''
self.object_queue.put(SlipPosition(key, latlon, layer, rotation, label, colour))
def event_queue_empty(self):
'''return True if there are no events waiting to be processed'''
return self.event_queue.empty()
def set_layout(self, layout):
'''set window layout'''
self.object_queue.put(layout)
def get_event(self):
'''return next event or None'''
if self.event_queue.empty():
return None
evt = self.event_queue.get()
while isinstance(evt, win_layout.WinLayout):
win_layout.set_layout(evt, self.set_layout)
if self.event_queue.empty():
return None
evt = self.event_queue.get()
return evt
def add_callback(self, callback):
'''add a callback for events from the map'''
self._callbacks.add(callback)
def check_events(self):
'''check for events, calling registered callbacks as needed'''
while not self.event_queue_empty():
event = self.get_event()
for callback in self._callbacks:
callback(event)
def icon(self, filename):
'''load an icon from the data directory'''
return mp_tile.mp_icon(filename)
def _wait_ready(self, timeout):
'''Wait at most timeout for the application to be ready
Param
-----
timeout: float
timeout in seconds
Returns True if the map is ready, False if the timeout is reached.
'''
start_time = time.time()
while time.time() - start_time < timeout:
if self.app_ready.is_set():
return True
time.sleep(0.1)
return False
|
class MPSlipMap():
'''
a generic map viewer widget for use in mavproxy
'''
def __init__(self,
title='SlipMap',
lat=-35.362938,
lon=149.165085,
width=800,
height=600,
ground_width=1000,
tile_delay=0.3,
service="MicrosoftSat",
max_zoom=19,
debug=False,
brightness=0,
elevation=None,
download=True,
show_flightmode_legend=True,
timelim_pipe=None):
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 graph is still going'''
pass
def add_object(self, obj):
'''add or update an object on the map'''
pass
def remove_object(self, key):
'''remove an object on the map by key'''
pass
def set_zoom(self, ground_width):
'''set ground width of view'''
pass
def set_center(self, lat, lon):
'''set center of view'''
pass
def set_follow(self, enable):
'''set follow on/off'''
pass
def set_follow_object(self, key, enable):
'''set follow on/off on an object'''
pass
def hide_object(self, key, hide=True):
'''hide an object on the map by key'''
pass
def set_position(self, key, latlon, layer='', rotation=0, label=None, colour=None):
'''move an object on the map'''
pass
def event_queue_empty(self):
'''return True if there are no events waiting to be processed'''
pass
def set_layout(self, layout):
'''set window layout'''
pass
def get_event(self):
'''return next event or None'''
pass
def add_callback(self, callback):
'''add a callback for events from the map'''
pass
def check_events(self):
'''check for events, calling registered callbacks as needed'''
pass
def icon(self, filename):
'''load an icon from the data directory'''
pass
def _wait_ready(self, timeout):
'''Wait at most timeout for the application to be ready
Param
-----
timeout: float
timeout in seconds
Returns True if the map is ready, False if the timeout is reached.
'''
pass
| 20 | 19 | 8 | 1 | 6 | 1 | 2 | 0.25 | 0 | 12 | 10 | 0 | 19 | 25 | 19 | 19 | 179 | 30 | 121 | 69 | 83 | 30 | 102 | 54 | 79 | 4 | 0 | 2 | 29 |
7,006 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_ui.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_ui.MPSlipMapPanel
|
class MPSlipMapPanel(wx.Panel):
""" The image panel
"""
def __init__(self, parent, state):
from MAVProxy.modules.lib import mp_widgets
wx.Panel.__init__(self, parent)
self.state = state
self.img = None
self.map_img = None
self.redraw_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
self.Bind(wx.EVT_SET_FOCUS, self.on_focus)
self.redraw_timer.Start(200)
self.mouse_pos = None
self.mouse_down = None
self.click_pos = None
self.last_click_pos = None
self.last_click_pos_used_for_text = None
self.last_terrain_height = None
if state.elevation != "None":
state.ElevationMap = mp_elevation.ElevationModel(database=state.elevation)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.mainSizer)
# display for lat/lon/elevation
self.position = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY)
if os.name == 'nt':
self.position.SetValue("line 1\nline 2\n")
size = self.position.GetBestSize()
self.position.SetMinSize(size)
self.position.SetValue("")
else:
textsize = tuple(self.position.GetFullTextExtent('line 1\nline 2\n')[0:2])
self.position.SetMinSize(textsize)
self.mainSizer.AddSpacer(2)
self.mainSizer.Add(self.position, flag=wx.LEFT | wx.BOTTOM | wx.GROW, border=0)
self.position.Bind(wx.EVT_SET_FOCUS, self.on_focus)
# a place to put control flags
self.controls = wx.BoxSizer(wx.HORIZONTAL)
self.mainSizer.Add(self.controls, 0, flag=wx.ALIGN_LEFT | wx.TOP | wx.GROW)
self.mainSizer.AddSpacer(2)
# a place to put information like image details
self.information = wx.BoxSizer(wx.HORIZONTAL)
self.mainSizer.Add(self.information, 0, flag=wx.ALIGN_LEFT | wx.TOP | wx.GROW)
self.mainSizer.AddSpacer(2)
# panel for the main map image
self.imagePanel = mp_widgets.ImagePanel(self, np.zeros((state.height, state.width, 3), dtype=np.uint8))
self.mainSizer.Add(self.imagePanel, flag=wx.GROW, border=5)
self.imagePanel.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse)
self.imagePanel.Bind(wx.EVT_KEY_DOWN, self.on_key_down)
self.imagePanel.Bind(wx.EVT_MOUSEWHEEL, self.on_mouse_wheel)
# a function to convert from (lat,lon) to (px,py) on the map
self.pixmapper = functools.partial(self.pixel_coords)
self.last_view = None
self.redraw_map()
state.frame.Fit()
def on_focus(self, event):
'''called when the panel gets focus'''
self.imagePanel.SetFocus()
def current_view(self):
'''return a tuple representing the current view'''
state = self.state
return (state.lat, state.lon, state.width, state.height,
state.ground_width, state.mt.tiles_pending())
def coordinates(self, x, y):
'''return coordinates of a pixel in the map'''
state = self.state
return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, state.ground_width)
def constrain_latlon(self):
self.state.lat = mp_util.constrain(self.state.lat, -85, 85)
self.state.lon = mp_util.wrap_180(self.state.lon)
def re_center(self, x, y, lat, lon):
'''re-center view for pixel x,y'''
state = self.state
if lat is None or lon is None:
return
(lat2,lon2) = self.coordinates(x, y)
distance = mp_util.gps_distance(lat2, lon2, lat, lon)
bearing = mp_util.gps_bearing(lat2, lon2, lat, lon)
(state.lat, state.lon) = mp_util.gps_newpos(state.lat, state.lon, bearing, distance)
self.constrain_latlon()
def set_ground_width(self, ground_width):
'''set ground width of view'''
state = self.state
state.ground_width = ground_width
state.panel.re_center(state.width/2, state.height/2, state.lat, state.lon)
def change_zoom(self, zoom):
'''zoom in or out by zoom factor, keeping centered'''
state = self.state
if self.mouse_pos:
(x,y) = (self.mouse_pos.x, self.mouse_pos.y)
else:
(x,y) = (state.width/2, state.height/2)
(lat,lon) = self.coordinates(x, y)
lat = mp_util.constrain(lat, -85, 85)
lon = mp_util.constrain(lon, -180, 180)
state.ground_width *= zoom
# limit ground_width to sane values
state.ground_width = max(state.ground_width, 2)
state.ground_width = min(state.ground_width, 20000000)
self.re_center(x,y, lat, lon)
def enter_position(self):
'''enter new position'''
state = self.state
dlg = wx.TextEntryDialog(self, 'Enter new position', 'Position')
dlg.SetValue("%f %f" % (state.lat, state.lon))
if dlg.ShowModal() == wx.ID_OK:
latlon = dlg.GetValue().split()
dlg.Destroy()
state.lat = float(latlon[0])
state.lon = float(latlon[1])
self.constrain_latlon()
self.re_center(state.width/2,state.height/2, state.lat, state.lon)
self.redraw_map()
def update_position(self):
'''update position text'''
state = self.state
pos = self.mouse_pos
newtext = ''
alt = 0
if pos is not None:
(lat,lon) = self.coordinates(pos.x, pos.y)
newtext += 'Cursor: %.8f %.8f (%s)' % (lat, lon, mp_util.latlon_to_grid((lat, lon)))
if state.elevation != "None":
alt = state.ElevationMap.GetElevation(lat, lon)
if alt is not None:
newtext += ' %.1fm %uft' % (alt, alt*3.28084)
state.mt.set_download(state.download)
pending = 0
if state.download:
pending = state.mt.tiles_pending()
if pending:
newtext += ' Map Downloading %u ' % pending
if alt == -1:
newtext += ' SRTM Downloading '
newtext += '\n'
cpt = self.click_position_text()
if cpt is not None:
newtext += cpt
if newtext != self.state.oldtext:
self.position.Clear()
self.position.WriteText(newtext)
self.state.oldtext = newtext
def click_position_text(self):
if self.click_pos is None:
return None
if self.click_pos == self.last_click_pos:
return self.last_click_position_text
if self.click_pos == self.last_click_pos_used_for_text:
return self.last_click_position_text
terrain_height = None
terrain_height_str = "?"
if self.state.elevation != "None":
terrain_height = self.state.ElevationMap.GetElevation(self.click_pos[0], self.click_pos[1])
if terrain_height is not None:
terrain_height_str = ' %.1fm' % (terrain_height,)
newtext = 'Click: %.8f %.8f %s (%s %s) (%s)' % (
self.click_pos[0],
self.click_pos[1],
terrain_height_str,
mp_util.degrees_to_dms(self.click_pos[0]),
mp_util.degrees_to_dms(self.click_pos[1]),
mp_util.latlon_to_grid(self.click_pos)
)
if self.last_click_pos is not None:
# provide information about the differences between the
# previous click position:
distance = mp_util.gps_distance(self.last_click_pos[0], self.last_click_pos[1],
self.click_pos[0], self.click_pos[1])
bearing = mp_util.gps_bearing(self.last_click_pos[0], self.last_click_pos[1],
self.click_pos[0], self.click_pos[1])
newtext += ' Distance: %.3fm %.3fnm Bearing %.1f' % (distance, distance*0.000539957, bearing)
if terrain_height_str == "?":
self.last_terrain_height = None
else:
if self.last_terrain_height is not None:
delta = terrain_height - self.last_terrain_height
newtext += " (height %f)" % (delta, )
self.last_terrain_height = terrain_height
self.last_click_pos_used_for_text = self.click_pos
self.last_click_position_text = newtext
return newtext
def pixel_coords(self, latlon, reverse=False):
'''return pixel coordinates in the map image for a (lat,lon)
if reverse is set, then return lat/lon for a pixel coordinate
'''
state = self.state
if reverse:
(x,y) = latlon
return self.coordinates(x,y)
(lat,lon) = (latlon[0], latlon[1])
return state.mt.coord_to_pixel(state.lat, state.lon, state.width, state.ground_width, lat, lon)
def draw_objects(self, objects, bounds, img):
'''draw objects on the image'''
keys = sorted(objects.keys())
for k in keys:
obj = objects[k]
if not self.state.legend and isinstance(obj, SlipFlightModeLegend):
continue
bounds2 = obj.bounds()
if bounds2 is None or mp_util.bounds_overlap(bounds, bounds2):
obj.draw(img, self.pixmapper, bounds)
def redraw_map(self):
'''redraw the map with current settings'''
state = self.state
view_same = (self.last_view is not None and self.map_img is not None and self.last_view == self.current_view())
if view_same and not state.need_redraw:
return
# get the new map
self.map_img = state.mt.area_to_image(state.lat, state.lon,
state.width, state.height, state.ground_width)
if state.brightness != 0: # valid state.brightness range is [-255, 255]
brightness = np.uint8(np.abs(state.brightness))
if state.brightness > 0:
self.map_img = np.where((255 - self.map_img) < brightness, 255, self.map_img + brightness)
else:
self.map_img = np.where((255 + self.map_img) < brightness, 0, self.map_img - brightness)
# find display bounding box
(lat2,lon2) = self.coordinates(state.width-1, state.height-1)
bounds = (lat2, state.lon, state.lat-lat2, mp_util.wrap_180(lon2-state.lon))
# get the image
img = self.map_img.copy()
# possibly draw a grid
if state.grid:
SlipGrid('grid', layer=3, linewidth=1, colour=(255,255,0)).draw(img, self.pixmapper, bounds)
# draw layer objects
keys = state.layers.keys()
keys = sorted(list(keys))
for k in keys:
self.draw_objects(state.layers[k], bounds, img)
# draw information objects
for key in state.info:
state.info[key].draw(state.panel, state.panel.information)
# display the image
self.imagePanel.set_image(img)
self.update_position()
self.mainSizer.Fit(self)
self.Refresh()
self.last_view = self.current_view()
state.need_redraw = False
def on_redraw_timer(self, event):
'''the redraw timer ensures we show new map tiles as they
are downloaded'''
self.redraw_map()
def on_size(self, event):
'''handle window size changes'''
state = self.state
size = event.GetSize()
state.width = size.width
state.height = size.height
self.redraw_map()
def on_mouse_wheel(self, event):
'''handle mouse wheel zoom changes'''
# >>> print -1/120
# -1
wheel_rotation = event.GetWheelRotation()
rotation = abs(wheel_rotation) // event.GetWheelDelta()
if rotation == 0:
return
zoom = 1.1 * rotation
if wheel_rotation > 0:
# zooming out
zoom = 1.0/zoom
self.change_zoom(zoom)
self.redraw_map()
def selected_objects(self, pos):
'''return a list of matching objects for a position'''
state = self.state
selected = []
(px, py) = pos
for layer in state.layers:
for key in state.layers[layer]:
obj = state.layers[layer][key]
distance = obj.clicked(px, py)
if distance is not None:
selected.append(SlipObjectSelection(key, distance, layer, extra_info=obj.selection_info()))
selected.sort(key=lambda c: c.distance)
return selected
def show_popup(self, objs, pos):
'''show popup menu for an object'''
state = self.state
popup_menu = None
popups = [ p.popup_menu for p in objs ]
if state.default_popup is not None and state.default_popup.combine:
popups.append(state.default_popup.popup)
popup_menu = popups[0]
if len(popups) > 1:
for p in popups[1:]:
popup_menu = copy.deepcopy(popup_menu)
popup_menu.add(MPMenuSeparator())
popup_menu.combine(p)
wx_menu = popup_menu.wx_menu()
state.frame.PopupMenu(wx_menu, pos)
def show_default_popup(self, pos):
'''show default popup menu'''
state = self.state
if state.default_popup.popup is not None:
wx_menu = state.default_popup.popup.wx_menu()
state.frame.PopupMenu(wx_menu, pos)
def on_mouse(self, event):
'''handle mouse events'''
state = self.state
pos = event.GetPosition()
if event.Leaving():
self.mouse_pos = None
else:
self.mouse_pos = pos
self.update_position()
if hasattr(event, 'ButtonIsDown'):
any_button_down = event.ButtonIsDown(wx.MOUSE_BTN_ANY)
left_button_down = event.ButtonIsDown(wx.MOUSE_BTN_LEFT)
right_button_down = event.ButtonIsDown(wx.MOUSE_BTN_RIGHT)
else:
left_button_down = event.leftIsDown
right_button_down = event.rightIsDown
any_button_down = left_button_down or right_button_down
if any_button_down or event.ButtonUp():
# send any event with a mouse button to the parent
latlon = self.coordinates(pos.x, pos.y)
selected = self.selected_objects(pos)
state.event_queue.put(SlipMouseEvent(latlon, event, selected))
if event.RightDown():
state.popup_objects = None
state.popup_latlon = None
if len(selected) > 0:
objs = [ state.layers[s.layer][s.objkey] for s in selected if state.layers[s.layer][s.objkey].popup_menu is not None ]
if len(objs) > 0:
state.popup_objects = objs
state.popup_latlon = latlon
self.show_popup(objs, pos)
state.popup_started = True
if not state.popup_started and state.default_popup is not None:
state.popup_latlon = latlon
self.show_default_popup(pos)
state.popup_started = True
if not right_button_down:
state.popup_started = False
if event.LeftDown() or event.RightDown():
self.mouse_down = pos
self.last_click_pos = self.click_pos
self.click_pos = self.coordinates(pos.x, pos.y)
if event.Dragging() and left_button_down:
# drag map to new position
newpos = pos
if self.mouse_down and newpos:
dx = (self.mouse_down.x - newpos.x)
dy = -(self.mouse_down.y - newpos.y)
pdist = math.sqrt(dx**2 + dy**2)
if pdist > state.drag_step:
bearing = math.degrees(math.atan2(dx, dy))
distance = (state.ground_width/float(state.width)) * pdist
newlatlon = mp_util.gps_newpos(state.lat, state.lon, bearing, distance)
(state.lat, state.lon) = newlatlon
self.constrain_latlon()
self.mouse_down = newpos
self.redraw_map()
def clear_thumbnails(self):
'''clear all thumbnails from the map'''
state = self.state
for l in state.layers:
keys = list(state.layers[l].keys())[:]
for key in keys:
if (isinstance(state.layers[l][key], SlipThumbnail)
and not isinstance(state.layers[l][key], SlipIcon)):
state.layers[l].pop(key)
def on_key_down(self, event):
'''handle keyboard input'''
state = self.state
# send all key events to the parent
if self.mouse_pos:
latlon = self.coordinates(self.mouse_pos.x, self.mouse_pos.y)
selected = self.selected_objects(self.mouse_pos)
state.event_queue.put(SlipKeyEvent(latlon, event, selected))
if hasattr(event,'GetUnicodeKey'):
c = event.GetUnicodeKey()
else:
c = event.GetUniChar()
if c == ord('+') or (c == ord('=') and event.ShiftDown()):
self.change_zoom(1.0/1.2)
elif c == ord('-'):
self.change_zoom(1.2)
elif c == ord('G') and not event.ControlDown():
self.enter_position()
elif c == ord('C'):
self.clear_thumbnails()
else:
# propogate event:
event.Skip()
|
class MPSlipMapPanel(wx.Panel):
''' The image panel
'''
def __init__(self, parent, state):
pass
def on_focus(self, event):
'''called when the panel gets focus'''
pass
def current_view(self):
'''return a tuple representing the current view'''
pass
def coordinates(self, x, y):
'''return coordinates of a pixel in the map'''
pass
def constrain_latlon(self):
pass
def re_center(self, x, y, lat, lon):
'''re-center view for pixel x,y'''
pass
def set_ground_width(self, ground_width):
'''set ground width of view'''
pass
def change_zoom(self, zoom):
'''zoom in or out by zoom factor, keeping centered'''
pass
def enter_position(self):
'''enter new position'''
pass
def update_position(self):
'''update position text'''
pass
def click_position_text(self):
pass
def pixel_coords(self, latlon, reverse=False):
'''return pixel coordinates in the map image for a (lat,lon)
if reverse is set, then return lat/lon for a pixel coordinate
'''
pass
def draw_objects(self, objects, bounds, img):
'''draw objects on the image'''
pass
def redraw_map(self):
'''redraw the map with current settings'''
pass
def on_redraw_timer(self, event):
'''the redraw timer ensures we show new map tiles as they
are downloaded'''
pass
def on_size(self, event):
'''handle window size changes'''
pass
def on_mouse_wheel(self, event):
'''handle mouse wheel zoom changes'''
pass
def selected_objects(self, pos):
'''return a list of matching objects for a position'''
pass
def show_popup(self, objs, pos):
'''show popup menu for an object'''
pass
def show_default_popup(self, pos):
'''show default popup menu'''
pass
def on_mouse_wheel(self, event):
'''handle mouse events'''
pass
def clear_thumbnails(self):
'''clear all thumbnails from the map'''
pass
def on_key_down(self, event):
'''handle keyboard input'''
pass
| 24 | 21 | 18 | 2 | 15 | 2 | 4 | 0.14 | 1 | 14 | 10 | 0 | 23 | 18 | 23 | 23 | 444 | 57 | 340 | 128 | 315 | 48 | 317 | 128 | 292 | 13 | 1 | 4 | 84 |
7,007 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipArrow
|
class SlipArrow(SlipObject):
'''an arrow to display direction of movement'''
def __init__(self, key, layer, xy_pix, colour, linewidth, rotation, reverse = False, arrow_size = 7, popup_menu=None):
SlipObject.__init__(self, key, layer, popup_menu=popup_menu)
self.xy_pix = xy_pix
self.colour = colour
self.arrow_size = arrow_size
self.linewidth = linewidth
if reverse:
self.rotation = rotation + math.pi
else:
self.rotation = rotation
def draw(self, img):
if self.hidden:
return
crot = self.arrow_size*math.cos(self.rotation)
srot = self.arrow_size*math.sin(self.rotation)
x1 = -crot-srot
x2 = crot-srot
y1 = crot-srot
y2 = crot+srot
pix1 = (int(self.xy_pix[0]+x1), int(self.xy_pix[1]+y1))
pix2 = (int(self.xy_pix[0]+x2), int(self.xy_pix[1]+y2))
cv2.line(img, pix1, self.xy_pix, self.colour, self.linewidth)
cv2.line(img, pix2, self.xy_pix, self.colour, self.linewidth)
|
class SlipArrow(SlipObject):
'''an arrow to display direction of movement'''
def __init__(self, key, layer, xy_pix, colour, linewidth, rotation, reverse = False, arrow_size = 7, popup_menu=None):
pass
def draw(self, img):
pass
| 3 | 1 | 12 | 0 | 12 | 0 | 2 | 0.04 | 1 | 1 | 0 | 0 | 2 | 5 | 2 | 11 | 26 | 1 | 24 | 16 | 21 | 1 | 23 | 16 | 20 | 2 | 1 | 1 | 4 |
7,008 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipBrightness
|
class SlipBrightness:
'''an object to change map brightness'''
def __init__(self, brightness):
self.brightness = brightness
|
class SlipBrightness:
'''an object to change map brightness'''
def __init__(self, brightness):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 3 | 3 | 1 | 1 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
7,009 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipCenter
|
class SlipCenter:
'''an object to move the view center'''
def __init__(self, latlon):
self.latlon = latlon
|
class SlipCenter:
'''an object to move the view center'''
def __init__(self, latlon):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 3 | 3 | 1 | 1 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
7,010 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/tools/MAVExplorer.py
|
MAVExplorer.MEState
|
class MEState(object):
'''holds state of MAVExplorer'''
def __init__(self):
self.input_queue = multiproc.Queue()
self.rl = None
self.console = wxconsole.MessageConsole(title='MAVExplorer')
self.exit = False
self.status = MEStatus()
self.settings = MPSettings(
[ MPSetting('marker', str, '+', 'data marker', tab='Graph'),
MPSetting('condition', str, None, 'condition'),
MPSetting('xaxis', str, None, 'xaxis'),
MPSetting('linestyle', str, None, 'linestyle'),
MPSetting('show_flightmode', int, 1, 'show flightmode'),
MPSetting('sync_xzoom', bool, True, 'sync X-axis zoom'),
MPSetting('sync_xmap', bool, True, 'sync X-axis zoom for map'),
MPSetting('legend', str, 'upper left', 'legend position'),
MPSetting('legend2', str, 'upper right', 'legend2 position'),
MPSetting('title', str, None, 'Graph title'),
MPSetting('debug', int, 0, 'debug level'),
MPSetting('paramdocs', bool, True, 'show param docs'),
MPSetting('max_rate', float, 0, 'maximum display rate of graphs in Hz'),
MPSetting('vehicle_type', str, 'Auto', 'force vehicle type for mode handling'),
]
)
self.mlog = None
self.mav_param = None
self.filename = None
self.command_map = command_map
self.completions = {
"set" : ["(SETTING)"],
"condition" : ["(VARIABLE)"],
"graph" : ['(VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE)'],
"dump" : ['(MESSAGETYPE)', '--verbose (MESSAGETYPE)'],
"map" : ['(VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE)'],
"param" : ['download', 'check', 'help (PARAMETER)', 'save', 'savechanged', 'diff', 'show', 'check'],
"logmessage": ['download', 'help (MESSAGETYPE)'],
}
self.aliases = {}
self.graphs = []
self.flightmode_selections = []
self.last_graph = GraphDefinition(self.settings.title, '', '', [], None)
#pipe to the wxconsole for any child threads (such as the save dialog box)
self.parent_pipe_recv_console,self.child_pipe_send_console = multiproc.Pipe(duplex=False)
#pipe for creating graphs (such as from the save dialog box)
self.parent_pipe_recv_graph,self.child_pipe_send_graph = multiproc.Pipe(duplex=False)
self.param_help = param_help.ParamHelp()
tConsoleWrite = threading.Thread(target=self.pipeRecvConsole)
tConsoleWrite.daemon = True
tConsoleWrite.start()
tGraphWrite = threading.Thread(target=self.pipeRecvGraph)
tGraphWrite.daemon = True
tGraphWrite.start()
def pipeRecvConsole(self):
'''watch for piped data from save dialog'''
try:
while True:
console_msg = self.parent_pipe_recv_console.recv()
if console_msg is not None:
self.console.writeln(console_msg)
time.sleep(0.1)
except EOFError:
pass
def pipeRecvGraph(self):
'''watch for piped data from save dialog'''
try:
while True:
graph_rec = self.parent_pipe_recv_graph.recv()
if graph_rec is not None:
mestate.input_queue.put(graph_rec)
time.sleep(0.1)
except EOFError:
pass
|
class MEState(object):
'''holds state of MAVExplorer'''
def __init__(self):
pass
def pipeRecvConsole(self):
'''watch for piped data from save dialog'''
pass
def pipeRecvGraph(self):
'''watch for piped data from save dialog'''
pass
| 4 | 3 | 25 | 1 | 22 | 1 | 3 | 0.07 | 1 | 11 | 5 | 0 | 3 | 20 | 3 | 3 | 78 | 5 | 68 | 26 | 64 | 5 | 44 | 26 | 40 | 4 | 1 | 3 | 9 |
7,011 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
|
MAVProxy.modules.lib.mp_image.MPImageTrackPos
|
class MPImageTrackPos:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
|
class MPImageTrackPos:
def __init__(self, x, y, shape):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 3 | 1 | 1 | 5 | 0 | 5 | 5 | 3 | 0 | 5 | 5 | 3 | 1 | 0 | 0 | 1 |
7,012 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.PrintoutWx
|
class PrintoutWx(wx.Printout):
"""Simple wrapper around wx Printout class -- all the real work
here is scaling the matplotlib canvas bitmap to the current
printer's definition.
"""
def __init__(self, canvas, width=5.5,margin=0.5, title='matplotlib'):
wx.Printout.__init__(self,title=title)
self.canvas = canvas
# width, in inches of output figure (approximate)
self.width = width
self.margin = margin
def HasPage(self, page):
#current only supports 1 page print
return page == 1
def GetPageInfo(self):
return (1, 1, 1, 1)
def OnPrintPage(self, page):
self.canvas.draw()
dc = self.GetDC()
(ppw,pph) = self.GetPPIPrinter() # printer's pixels per in
(pgw,pgh) = self.GetPageSizePixels() # page size in pixels
(dcw,dch) = dc.GetSize()
(grw,grh) = self.canvas.GetSizeTuple()
# save current figure dpi resolution and bg color,
# so that we can temporarily set them to the dpi of
# the printer, and the bg color to white
bgcolor = self.canvas.figure.get_facecolor()
fig_dpi = self.canvas.figure.dpi
# draw the bitmap, scaled appropriately
vscale = float(ppw) / fig_dpi
# set figure resolution,bg color for printer
self.canvas.figure.dpi = ppw
self.canvas.figure.set_facecolor('#FFFFFF')
renderer = RendererWx(self.canvas.bitmap, self.canvas.figure.dpi)
self.canvas.figure.draw(renderer)
self.canvas.bitmap.SetWidth( int(self.canvas.bitmap.GetWidth() * vscale))
self.canvas.bitmap.SetHeight( int(self.canvas.bitmap.GetHeight()* vscale))
self.canvas.draw()
# page may need additional scaling on preview
page_scale = 1.0
if self.IsPreview(): page_scale = float(dcw)/pgw
# get margin in pixels = (margin in in) * (pixels/in)
top_margin = int(self.margin * pph * page_scale)
left_margin = int(self.margin * ppw * page_scale)
# set scale so that width of output is self.width inches
# (assuming grw is size of graph in inches....)
user_scale = (self.width * fig_dpi * page_scale)/float(grw)
dc.SetDeviceOrigin(left_margin,top_margin)
dc.SetUserScale(user_scale,user_scale)
# this cute little number avoid API inconsistencies in wx
try:
dc.DrawBitmap(self.canvas.bitmap, 0, 0)
except:
try:
dc.DrawBitmap(self.canvas.bitmap, (0, 0))
except:
pass
# restore original figure resolution
self.canvas.figure.set_facecolor(bgcolor)
self.canvas.figure.dpi = fig_dpi
self.canvas.draw()
return True
|
class PrintoutWx(wx.Printout):
'''Simple wrapper around wx Printout class -- all the real work
here is scaling the matplotlib canvas bitmap to the current
printer's definition.
'''
def __init__(self, canvas, width=5.5,margin=0.5, title='matplotlib'):
pass
def HasPage(self, page):
pass
def GetPageInfo(self):
pass
def OnPrintPage(self, page):
pass
| 5 | 1 | 17 | 3 | 11 | 4 | 2 | 0.44 | 1 | 3 | 1 | 0 | 4 | 3 | 4 | 4 | 76 | 14 | 45 | 21 | 40 | 20 | 46 | 21 | 41 | 4 | 1 | 2 | 7 |
7,013 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.Show
|
class Show(ShowBase):
def mainloop(self):
needmain = not wx.App.IsMainLoopRunning()
if needmain:
wxapp = wx.GetApp()
if wxapp is not None:
wxapp.MainLoop()
|
class Show(ShowBase):
def mainloop(self):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 3 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 0 | 7 | 4 | 5 | 0 | 7 | 4 | 5 | 3 | 1 | 2 | 3 |
7,014 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_graph.py
|
MAVProxy.modules.mavproxy_graph.GraphModule
|
class GraphModule(mp_module.MPModule):
def __init__(self, mpstate):
super(GraphModule, self).__init__(mpstate, "graph", "graph control")
self.timespan = 20
self.tickresolution = 0.2
self.graphs = []
self.add_command('graph', self.cmd_graph, "[expression...] add a live graph",
['(VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE) (VARIABLE)',
'legend',
'timespan',
'tickresolution'])
self.legend = {
}
def cmd_graph(self, args):
'''graph command'''
if len(args) == 0:
# list current graphs
for i in range(len(self.graphs)):
print("Graph %u: %s" % (i, self.graphs[i].fields))
return
elif args[0] == "help":
print("graph <timespan|tickresolution|expression>")
elif args[0] == "timespan":
if len(args) == 1:
print("timespan: %.1f" % self.timespan)
return
self.timespan = float(args[1])
elif args[0] == "tickresolution":
if len(args) == 1:
print("tickresolution: %.1f" % self.tickresolution)
return
self.tickresolution = float(args[1])
elif args[0] == "legend":
self.cmd_legend(args[1:])
else:
# start a new graph
self.graphs.append(Graph(self, args[:]))
def cmd_legend(self, args):
'''setup legend for graphs'''
if len(args) == 0:
for leg in self.legend.keys():
print("%s -> %s" % (leg, self.legend[leg]))
elif len(args) == 1:
leg = args[0]
if leg in self.legend:
print("Removing legend %s" % leg)
self.legend.pop(leg)
elif len(args) >= 2:
leg = args[0]
leg2 = args[1]
print("Adding legend %s -> %s" % (leg, leg2))
self.legend[leg] = leg2
def unload(self):
'''unload module'''
for g in self.graphs:
g.close()
self.graphs = []
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
# check for any closed graphs
for i in range(len(self.graphs) - 1, -1, -1):
if not self.graphs[i].is_alive():
self.graphs[i].close()
self.graphs.pop(i)
# add data to the rest
for g in self.graphs:
g.add_mavlink_packet(msg)
|
class GraphModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_graph(self, args):
'''graph command'''
pass
def cmd_legend(self, args):
'''setup legend for graphs'''
pass
def unload(self):
'''unload module'''
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
| 6 | 4 | 14 | 1 | 12 | 2 | 4 | 0.14 | 1 | 4 | 1 | 0 | 5 | 4 | 5 | 43 | 75 | 8 | 59 | 16 | 53 | 8 | 47 | 16 | 41 | 9 | 2 | 2 | 22 |
7,015 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_heliplane.py
|
MAVProxy.modules.mavproxy_heliplane.HeliPlaneModule
|
class HeliPlaneModule(mp_module.MPModule):
def __init__(self, mpstate):
super(HeliPlaneModule, self).__init__(mpstate, "heliplane", "HeliPlane", public=False)
self.last_chan_check = 0
self.update_channels()
def get_rc_input(self, msg, chan):
'''extract RC input value'''
if chan <= 0:
return -1
return getattr(msg, 'chan%u_raw' % chan, -1)
def get_pwm_output(self, msg, chan):
'''extract PWM output value'''
if chan <= 0:
return -1
return getattr(msg, 'servo%u_raw' % chan, -1)
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
type = msg.get_type()
master = self.master
# add some status fields
if type in [ 'RC_CHANNELS' ]:
ilock = self.get_rc_input(msg, self.interlock_channel)
if ilock <= 0:
self.console.set_status('ILOCK', 'ILOCK:--', fg='grey', row=4)
elif ilock >= 1800:
self.console.set_status('ILOCK', 'ILOCK:ON', fg='red', row=4)
else:
self.console.set_status('ILOCK', 'ILOCK:OFF', fg='green', row=4)
override = self.get_rc_input(msg, self.override_channel)
if override <= 0:
self.console.set_status('OVR', 'OVR:--', fg='grey', row=4)
elif override >= 1800:
self.console.set_status('OVR', 'OVR:ON', fg='red', row=4)
else:
self.console.set_status('OVR', 'OVR:OFF', fg='green', row=4)
zeroi = self.get_rc_input(msg, self.zero_I_channel)
if zeroi <= 0:
self.console.set_status('ZEROI', 'ZEROI:--', fg='grey', row=4)
elif zeroi >= 1800:
self.console.set_status('ZEROI', 'ZEROI:ON', fg='red', row=4)
else:
self.console.set_status('ZEROI', 'ZEROI:OFF', fg='green', row=4)
novtol = self.get_rc_input(msg, self.no_vtol_channel)
if novtol <= 0:
self.console.set_status('NOVTOL', 'NOVTOL:--', fg='grey', row=4)
elif novtol >= 1800:
self.console.set_status('NOVTOL', 'NOVTOL:ON', fg='red', row=4)
else:
self.console.set_status('NOVTOL', 'NOVTOL:OFF', fg='green', row=4)
if type in [ 'SERVO_OUTPUT_RAW' ]:
rsc = self.get_pwm_output(msg, self.rsc_out_channel)
if rsc <= 0:
self.console.set_status('RSC', 'RSC:--', fg='grey', row=4)
elif rsc <= 1200:
self.console.set_status('RSC', 'RSC:%u' % rsc, fg='red', row=4)
elif rsc <= 1600:
self.console.set_status('RSC', 'RSC:%u' % rsc, fg='orange', row=4)
else:
self.console.set_status('RSC', 'RSC:%u' % rsc, fg='green', row=4)
thr = self.get_pwm_output(msg, self.fwd_thr_channel)
if thr <= 0:
self.console.set_status('FTHR', 'FTHR:--', fg='grey', row=4)
elif thr <= 1100:
self.console.set_status('FTHR', 'FTHR:%u' % thr, fg='red', row=4)
elif thr <= 1500:
self.console.set_status('FTHR', 'FTHR:%u' % thr, fg='orange', row=4)
else:
self.console.set_status('FTHR', 'FTHR:%u' % thr, fg='green', row=4)
if type in [ 'RPM' ]:
rpm = msg.rpm1
if rpm < 1000:
rpm_colour = 'red'
elif rpm < 2000:
rpm_colour = 'orange'
else:
rpm_colour = 'green'
self.console.set_status('RPM', 'RPM: %u' % rpm, fg=rpm_colour, row=4)
def update_channels(self):
'''update which channels provide input'''
self.interlock_channel = -1
self.override_channel = -1
self.zero_I_channel = -1
self.no_vtol_channel = -1
# output channels
self.rsc_out_channel = 9
self.fwd_thr_channel = 10
for ch in range(1,16):
option = self.get_mav_param("RC%u_OPTION" % ch, 0)
if option == 32:
self.interlock_channel = ch;
elif option == 63:
self.override_channel = ch;
elif option == 64:
self.zero_I_channel = ch;
elif option == 65:
self.override_channel = ch;
elif option == 66:
self.no_vtol_channel = ch;
function = self.get_mav_param("SERVO%u_FUNCTION" % ch, 0)
if function == 32:
self.rsc_out_channel = ch
if function == 70:
self.fwd_thr_channel = ch
def idle_task(self):
'''run periodic tasks'''
now = time.time()
if now - self.last_chan_check >= 1:
self.last_chan_check = now
self.update_channels()
|
class HeliPlaneModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def get_rc_input(self, msg, chan):
'''extract RC input value'''
pass
def get_pwm_output(self, msg, chan):
'''extract PWM output value'''
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def update_channels(self):
'''update which channels provide input'''
pass
def idle_task(self):
'''run periodic tasks'''
pass
| 7 | 5 | 20 | 2 | 17 | 1 | 6 | 0.07 | 1 | 2 | 0 | 0 | 6 | 7 | 6 | 44 | 126 | 17 | 102 | 28 | 95 | 7 | 82 | 28 | 75 | 20 | 2 | 2 | 36 |
7,016 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_help.py
|
MAVProxy.modules.mavproxy_help.HelpModule
|
class HelpModule(mp_module.MPModule):
def __init__(self, mpstate):
super(HelpModule, self).__init__(mpstate, "mavhelp", "Help and version information", public = True) # noqa
self.enabled = False
self.add_command('mavhelp', self.cmd_help, "help and version information", "<about|site>")
self.have_list = False
# versioning info
# pkg_resources doesn't work in the windows exe build, so read the version file
try:
import pkg_resources
self.version = pkg_resources.Environment()["mavproxy"][0].version
except Exception:
start_script = mp_util.dot_mavproxy("version.txt")
f = open(start_script, 'r')
self.version = f.readline()
self.host = platform.system() + platform.release()
self.pythonversion = str(platform.python_version())
if mp_util.has_wxpython:
self.wxVersion = str(wx.__version__)
else:
self.wxVersion = ''
# check for updates, if able
self.check_for_updates()
if mp_util.has_wxpython:
self.menu_added_console = False
self.menu = MPMenuSubMenu(
'Help',
items=[
MPMenuItem(
'MAVProxy website',
'MAVProxy website',
'',
handler=MPMenuOpenWeblink('https://ardupilot.org/mavproxy/index.html'),
),
MPMenuItem(
'Check for Updates',
'Check for Updates',
'',
handler=MPMenuChildMessageDialog(
title="Updates",
message=self.newversion,
)
),
MPMenuItem(
'About',
'About',
'',
handler=MPMenuChildMessageDialog(
title="About MAVProxy",
message=self.about_string(),
))
])
def check_for_updates(self):
url = "https://pypi.org/pypi/MAVProxy/json"
try:
response = requests.get(url)
except requests.exceptions.RequestException as e:
self.newversion = f"Error finding update: {e}"
return
if response.status_code != 200:
self.newversion = f"HTTP error getting update ({response.status_code})"
return
self.newversion = response.json()['info']['version']
# and format the update string
if not isinstance(self.newversion, str):
self.newversion = "Error finding update"
elif re.search('[a-zA-Z]', self.newversion):
self.newversion = "Error finding update: " + self.newversion
elif self.newversion.strip() == self.version.strip():
self.newversion = "Running latest version"
else:
self.newversion = "New version " + self.newversion + " available (currently running " + self.version + ")"
def about_string(self):
bits = {
"MAVProxy Version": self.version,
"OS": self.host,
"Python": self.pythonversion,
"WXPython": self.wxVersion,
"LatestVersion": self.newversion,
}
return "".join([f"{x[0]}: {x[1]}\n" for x in bits.items()])
def idle_task(self):
'''called on idle'''
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
def cmd_help(self, args):
'''help commands'''
if len(args) < 1:
self.print_usage()
return
if args[0] == "about":
print(self.about_string())
elif args[0] == "site":
print("See https://ardupilot.org/mavproxy/index.html for documentation")
else:
self.print_usage()
def mavlink_packet(self, m):
'''handle and incoming mavlink packets'''
def print_usage(self):
print("usage: mavhelp <about|site>")
|
class HelpModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def check_for_updates(self):
pass
def about_string(self):
pass
def idle_task(self):
'''called on idle'''
pass
def cmd_help(self, args):
'''help commands'''
pass
def mavlink_packet(self, m):
'''handle and incoming mavlink packets'''
pass
def print_usage(self):
pass
| 8 | 3 | 16 | 1 | 14 | 1 | 3 | 0.08 | 1 | 8 | 4 | 0 | 7 | 9 | 7 | 45 | 117 | 13 | 97 | 24 | 88 | 8 | 58 | 22 | 49 | 6 | 2 | 2 | 20 |
7,017 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_horizon.py
|
MAVProxy.modules.mavproxy_horizon.HorizonModule
|
class HorizonModule(mp_module.MPModule):
def __init__(self, mpstate):
# Define module load/unload reference and window title
super(HorizonModule, self).__init__(mpstate, "horizon", "Horizon Indicator", public=True)
self.mpstate.horizonIndicator = wxhorizon.HorizonIndicator(title='Horizon Indicator')
self.mode = ''
self.armed = ''
self.currentWP = 0
self.finalWP = 0
self.currentDist = 0
self.nextWPTime = 0
self.speed = 0
self.wpBearing = 0
self.msgList = []
self.lastSend = 0.0
self.fps = 10.0
self.sendDelay = (1.0/self.fps)*0.9
self.add_command('horizon-fps',self.fpsInformation,"Get or change frame rate for horizon. Usage: horizon-fps set <fps>, horizon-fps get. Set fps to zero to get unrestricted framerate.")
def unload(self):
'''unload module'''
self.mpstate.horizonIndicator.close()
def fpsInformation(self,args):
'''fps command'''
invalidStr = 'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.'
if len(args)>0:
if args[0] == "get":
'''Get the current framerate.'''
if (self.fps == 0.0):
print('Horizon Framerate: Unrestricted')
else:
print("Horizon Framerate: " + str(self.fps))
elif args[0] == "set":
if len(args)==2:
self.fps = float(args[1])
if (self.fps != 0):
self.sendDelay = 1.0/self.fps
else:
self.sendDelay = 0.0
self.msgList.append(FPS(self.fps))
if (self.fps == 0.0):
print('Horizon Framerate: Unrestricted')
else:
print("Horizon Framerate: " + str(self.fps))
else:
print(invalidStr)
else:
print(invalidStr)
else:
print(invalidStr)
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
msgType = msg.get_type()
master = self.master
if msgType == 'HEARTBEAT':
# Update state and mode information
self.armed = master.motors_armed()
self.mode = master.flightmode
# Send Flight State information down pipe
self.msgList.append(FlightState(self.mode,self.armed))
elif msgType == 'ATTITUDE':
# Send attitude information down pipe
self.msgList.append(Attitude(msg))
elif msgType == 'VFR_HUD':
# Send HUD information down pipe
self.msgList.append(VFR_HUD(msg))
elif msgType == 'GLOBAL_POSITION_INT':
# Send altitude information down pipe
self.msgList.append(Global_Position_INT(msg,time.time()))
elif msgType == 'SYS_STATUS':
# Mode and Arm State
self.msgList.append(BatteryInfo(msg))
elif msgType in ['MISSION_CURRENT']:
# Waypoints
self.currentWP = msg.seq
self.finalWP = self.module('wp').wploader.count()
self.msgList.append(WaypointInfo(self.currentWP,self.finalWP,self.currentDist,self.nextWPTime,self.wpBearing))
elif msgType == 'NAV_CONTROLLER_OUTPUT':
self.currentDist = msg.wp_dist
self.speed = master.field('VFR_HUD', 'airspeed', 30)
if self.speed > 1:
self.nextWPTime = self.currentDist / self.speed
else:
self.nextWPTime = '-'
self.wpBearing = msg.target_bearing
self.msgList.append(WaypointInfo(self.currentWP,self.finalWP,self.currentDist,self.nextWPTime,self.wpBearing))
def idle_task(self):
if self.mpstate.horizonIndicator.close_event.wait(0.001):
self.needs_unloading = True # tell MAVProxy to unload this module
if (time.time() - self.lastSend) > self.sendDelay:
self.mpstate.horizonIndicator.parent_pipe_send.send(self.msgList)
self.msgList = []
self.lastSend = time.time()
|
class HorizonModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def unload(self):
'''unload module'''
pass
def fpsInformation(self,args):
'''fps command'''
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def idle_task(self):
pass
| 6 | 3 | 18 | 0 | 16 | 3 | 4 | 0.16 | 1 | 11 | 8 | 0 | 5 | 13 | 5 | 43 | 98 | 6 | 80 | 22 | 74 | 13 | 66 | 22 | 60 | 9 | 2 | 4 | 22 |
7,018 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_instructor.py
|
MAVProxy.modules.mavproxy_instructor.InstructorModule
|
class InstructorModule(mp_module.MPModule):
def __init__(self, mpstate):
#self.in_pipe, self.out_pipe = multiproc.Pipe()
super(InstructorModule, self).__init__(mpstate, "instructor", "instructor module")
self.instructor = mp_instructor.InstructorUI()
self.voltage_is_dropping = False
self.voltage_drop = 0.0 # accumulated voltage drop
self.voltage_start = 0 # voltage before drop
self.voltage_drop_rate = 0.1 # v/s drop rate
def unload(self):
'''unload module'''
print('unloading') # self.mpstate.horizonIndicator.close()
def mavlink_packet(self, msg):
"""handle an incoming mavlink packet"""
if not isinstance(self.instructor, mp_instructor.InstructorUI):
return
if not self.instructor.is_alive():
return
type = msg.get_type()
master = self.master
if type == 'HEARTBEAT':
'beforeEngineList - APM booted'
if self.mpstate.status.heartbeat_error == True:
self.instructor.set_check("Pixhawk Booted", 0)
else:
self.instructor.set_check("Pixhawk Booted", 1)
if self.voltage_is_dropping:
self.voltage_drop += self.voltage_drop_rate
self.param_set('SIM_BATT_VOLTAGE', (self.voltage_start - self.voltage_drop))
# if mp_instructor.InstructorFrame.out_pipe.poll():
if self.instructor.pipe_to_gui.poll():
obj = self.instructor.pipe_to_gui.recv()
if obj[0] == "dis_gnss":
# print(str(obj[1]))
self.param_set('SIM_GPS_DISABLE', int(obj[1]))
elif obj[0] == "setmode":
self.master.set_mode("RTL")
elif obj[0] == "volt_drop_rate":
self.voltage_drop_rate = obj[1]
#print(self.voltage_drop_rate)
elif obj[0] == "volt_drop":
if obj[1]:
self.voltage_is_dropping = True
self.voltage_start = self.get_mav_param('SIM_BATT_VOLTAGE')
print('voltage dropping')
else:
self.voltage_is_dropping = False
self.param_set('SIM_BATT_VOLTAGE', self.voltage_start)
print('voltage restored')
#print(self.voltage_start)
#print(self.voltage_is_dropping)
#print(self.voltage_drop_rate)
#print(self.voltage_drop)
#print(self.get_mav_param('SIM_BATT_VOLTAGE'))
#self.mav_param('SIM_BATT_VOLTAGE', int(obj[1]))
elif obj[0] == "gcs_comm_loss":
if obj[1]:
print('on')
#MAVProxy.modules.mavproxy_link.LinkModule.cmd_link_add("udp:127.0.0.1:9777")
else:
print('off')
#MAVProxy.modules.mavproxy_link.LinkModule.cmd_link_remove("127.0.0.1:14550")
elif obj[0] == "wind_dir":
self.param_set('SIM_WIND_DIR', obj[1])
elif obj[0] == "wind_vel":
self.param_set('SIM_WIND_SPD', obj[1])
elif obj[0] == "wind_turbulence":
self.param_set('SIM_WIND_TURB', obj[1])
self.param_set('SIM_WIND_T', obj[1])
# self.instructor.set_check("Odroid Booted", 1)
#print(obj)
# Plane Actions
elif obj[0] == "pitot_fail_low":
self.param_set('SIM_ARSPD_FAIL', obj[1])
elif obj[0] == "pitot_fail_high":
self.param_set('SIM_ARSPD_FAILP', obj[1])
elif obj[0] == "arspd_offset":
self.param_set('SIM_ARSPD_OFS', obj[1])
elif obj[0] == "plane_thrust_loss":
self.param_set('SERVO3_MAX', 2000 - obj[1])
elif obj[0] == "plane_thrust_loss_curr":
self.param_set('SERVO3_MAX', 2000 - obj[1])
# simulate increased current by 0...-2 offset
self.param_set('BATT_AMP_OFFSET', (-obj[1]/500))
# Copter Actions
elif obj[0] == "copter_thrust_loss":
self.param_set('MOT_PWM_MAX', 2000 - obj[1])
# simulate increased current
self.param_set('BATT_AMP_PERVLT', 17 + (obj[1]/40))
elif obj[0] == "copter_reset":
print("MOT_PWM_MAX 2000")
self.param_set('MOT_PWM_MAX', 2000)
print("BATT_AMP_PERVLT 17")
self.param_set('BATT_AMP_PERVLT', 17)
print('Done')
'''beforeEngineList - Flight mode MANUAL'''
if self.mpstate.status.flightmode == "MANUAL":
self.instructor.set_check("Flight mode MANUAL", 1)
else:
self.instructor.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.instructor.set_check("GNSS FIX", 1)
else:
self.instructor.set_check("GNSS FIX", 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.instructor.set_check("Radio links > 6db margin", 0)
else:
self.instructor.set_check("Radio Links > 6db margin", 0)
if type == 'HWSTATUS':
'''beforeEngineList - Avionics Battery'''
if msg.Vcc >= 4600 and msg.Vcc <= 5300:
self.instructor.set_check("Avionics Power", 1)
else:
self.instructor.set_check("Avionics Power", 0)
if type == 'POWER_STATUS':
'''beforeEngineList - Servo Power'''
if msg.Vservo >= 4900 and msg.Vservo <= 6500:
self.instructor.set_check("Servo Power", 1)
else:
self.instructor.set_check("Servo Power", 0)
'''beforeEngineList - Waypoints Loaded'''
if type == 'HEARTBEAT':
if self.module('wp').wploader.count() == 0:
self.instructor.set_check("Waypoints Loaded", 0)
else:
self.instructor.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.instructor.set_check("Compass active", 1)
else:
self.instructor.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.instructor.set_check("Altitude > 30 m", 1)
else:
self.instructor.set_check("Altitude > 30 m", 0)
if msg.airspeed > 10 or msg.groundspeed > 10:
self.instructor.set_check("Airspeed > 10 m/s", 1)
else:
self.instructor.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.instructor.set_check("IMU Check", 1)
else:
self.instructor.set_check("IMU Check", 0)
def unload(self):
'''unload module'''
self.instructor.close()
|
class InstructorModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def unload(self):
'''unload module'''
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def unload(self):
'''unload module'''
pass
| 5 | 3 | 49 | 9 | 33 | 9 | 11 | 0.26 | 1 | 3 | 1 | 0 | 4 | 5 | 4 | 42 | 200 | 36 | 133 | 18 | 128 | 35 | 102 | 18 | 97 | 42 | 2 | 3 | 45 |
7,019 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_joystick/__init__.py
|
MAVProxy.modules.mavproxy_joystick.Joystick
|
class Joystick(mp_module.MPModule):
'''
joystick set verbose
joystick set debug
joystick status
joystick probe
'''
def __init__(self, mpstate):
"""Initialise module"""
super(Joystick, self).__init__(mpstate, 'joystick',
'A flexible joystick driver')
self.joystick = None
self.init_pygame()
self.init_settings()
self.init_commands()
self.probe()
def log(self, msg, level=0):
if self.mpstate.settings.moddebug < level:
return
print('{}: {}'.format(__name__, msg))
def init_pygame(self):
self.log('Initializing pygame', 2)
pygame.init()
pygame.joystick.init()
def init_settings(self):
pass
def init_commands(self):
self.log('Initializing commands', 2)
self.add_command('joystick', self.cmd_joystick,
"A flexible joystick drvier",
['status', 'probe'])
def load_definitions(self):
self.log('Loading joystick definitions', 1)
self.joydefs = []
search = []
userjoysticks = os.environ.get(
'MAVPROXY_JOYSTICK_DIR',
mp_util.dot_mavproxy('joysticks'))
if userjoysticks is not None and os.path.isdir(userjoysticks):
search.append(userjoysticks)
search.append(pkg_resources.resource_filename(__name__, 'joysticks'))
for path in search:
self.log('Looking for joystick definitions in {}'.format(path),
2)
path = os.path.expanduser(path)
for dirpath, dirnames, filenames in os.walk(path):
for joyfile in filenames:
root, ext = os.path.splitext(joyfile)
if ext[1:] not in ['yml', 'yaml', 'json']:
continue
joypath = os.path.join(dirpath, joyfile)
self.log('Loading definition from {}'.format(joypath), 2)
with open(joypath, 'r') as fd:
joydef = yaml.safe_load(fd)
joydef['path'] = joypath
self.joydefs.append(joydef)
def probe(self):
self.load_definitions()
for jid in range(pygame.joystick.get_count()):
joy = pygame.joystick.Joystick(jid)
self.log("Found joystick (%s)" % (joy.get_name(),))
for joydef in self.joydefs:
if 'match' not in joydef:
self.log('{} has no match patterns, ignoring.'.format(
joydef['path']), 0)
continue
for pattern in joydef['match']:
if fnmatch.fnmatch(joy.get_name().lower(),
pattern.lower()):
self.log('Using {} ("{}" matches pattern "{}")'.format(
joydef['path'], joy.get_name(), pattern))
self.joystick = controls.Joystick(joy, joydef)
return
print('{}: Failed to find matching joystick.'.format(__name__))
def usage(self):
'''show help on command line options'''
return "Usage: joystick <status|set>"
def cmd_joystick(self, args):
if not len(args):
self.log('No subcommand specified.')
elif args[0] == 'status':
self.cmd_status()
elif args[0] == 'probe':
self.cmd_probe()
elif args[0] == 'help':
self.cmd_help()
def cmd_help(self):
print('joystick probe -- reload and match joystick definitions')
print('joystick status -- show currently loaded definition, if any')
def cmd_probe(self):
self.log('Re-detecting available joysticks', 0)
self.probe()
def cmd_status(self):
if self.joystick is None:
print('No active joystick')
else:
print('Active joystick:')
print('Path: {path}'.format(**self.joystick.controls))
print('Description: {description}'.format(
**self.joystick.controls))
def idle_task(self):
if self.joystick is None:
return
for e in pygame.event.get():
override = self.module('rc').override[:]
values = self.joystick.read()
override = values + override[len(values):]
# self.log('channels: {}'.format(override), level=3)
if override != self.module('rc').override:
self.module('rc').override = override
self.module('rc').override_period.force()
|
class Joystick(mp_module.MPModule):
'''
joystick set verbose
joystick set debug
joystick status
joystick probe
'''
def __init__(self, mpstate):
'''Initialise module'''
pass
def log(self, msg, level=0):
pass
def init_pygame(self):
pass
def init_settings(self):
pass
def init_commands(self):
pass
def load_definitions(self):
pass
def probe(self):
pass
def usage(self):
'''show help on command line options'''
pass
def cmd_joystick(self, args):
pass
def cmd_help(self):
pass
def cmd_probe(self):
pass
def cmd_status(self):
pass
def idle_task(self):
pass
| 14 | 3 | 9 | 1 | 8 | 0 | 2 | 0.09 | 1 | 3 | 1 | 0 | 13 | 2 | 13 | 51 | 138 | 27 | 102 | 32 | 88 | 9 | 88 | 31 | 74 | 6 | 2 | 4 | 32 |
7,020 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_joystick/controls.py
|
MAVProxy.modules.mavproxy_joystick.controls.Axis
|
class Axis (Control):
'''An Axis maps a joystick axis to a channel. Set `invert` to
`True` in order to reverse the direction of the input.'''
def __init__(self, joystick, id, invert=False, **kwargs):
super(Axis, self).__init__(joystick, **kwargs)
self.id = id
self.invert = invert
@property
def value(self):
val = self.joystick.get_axis(self.id)
if self.invert:
val = -val
return scale(val, inlow=self.inlow, inhigh=self.inhigh, outlow=self.outlow, outhigh=self.outhigh)
|
class Axis (Control):
'''An Axis maps a joystick axis to a channel. Set `invert` to
`True` in order to reverse the direction of the input.'''
def __init__(self, joystick, id, invert=False, **kwargs):
pass
@property
def value(self):
pass
| 4 | 1 | 5 | 1 | 5 | 0 | 2 | 0.18 | 1 | 1 | 0 | 0 | 2 | 5 | 2 | 3 | 16 | 3 | 11 | 8 | 7 | 2 | 10 | 6 | 7 | 2 | 2 | 1 | 3 |
7,021 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_joystick/controls.py
|
MAVProxy.modules.mavproxy_joystick.controls.Button
|
class Button (Control):
'''A Button acts like a momentary switch. When pressed, the
corresponding channel value is set to `outhigh`; when released,
the value is set to `outlow`.'''
def __init__(self, joystick, id, **kwargs):
super(Button, self).__init__(joystick, **kwargs)
self.id = id
@property
def value(self):
state = self.joystick.get_button(self.id)
if state:
return self.outhigh
else:
return self.outlow
|
class Button (Control):
'''A Button acts like a momentary switch. When pressed, the
corresponding channel value is set to `outhigh`; when released,
the value is set to `outlow`.'''
def __init__(self, joystick, id, **kwargs):
pass
@property
def value(self):
pass
| 4 | 1 | 5 | 0 | 5 | 0 | 2 | 0.27 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 3 | 16 | 2 | 11 | 6 | 7 | 3 | 9 | 5 | 6 | 2 | 2 | 1 | 3 |
7,022 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_joystick/controls.py
|
MAVProxy.modules.mavproxy_joystick.controls.Hat
|
class Hat (Control):
'''A Hat maps one axis of a hat as if it were a toggle switch.
When the axis goes negative, the corresponding channel value is
set to `outputlow`. When the axis goes positive, the value is set
to `outputhigh`. No change is made when the axis returns to 0.'''
def __init__(self, joystick, id, axis, **kwargs):
super(Hat, self).__init__(joystick, **kwargs)
self.id = id
self.axis = axis
self._value = self.outlow
@property
def value(self):
x, y = self.joystick.get_hat(self.id)
value = x if self.axis == 'x' else y
if value != 0:
self._value = scale(value,
outlow=self.outlow, outhigh=self.outhigh)
return self._value
|
class Hat (Control):
'''A Hat maps one axis of a hat as if it were a toggle switch.
When the axis goes negative, the corresponding channel value is
set to `outputlow`. When the axis goes positive, the value is set
to `outputhigh`. No change is made when the axis returns to 0.'''
def __init__(self, joystick, id, axis, **kwargs):
pass
@property
def value(self):
pass
| 4 | 1 | 8 | 2 | 6 | 0 | 2 | 0.29 | 1 | 1 | 0 | 0 | 2 | 4 | 2 | 3 | 23 | 5 | 14 | 10 | 10 | 4 | 12 | 8 | 9 | 3 | 2 | 1 | 4 |
7,023 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_joystick/controls.py
|
MAVProxy.modules.mavproxy_joystick.controls.MultiButton
|
class MultiButton (Control):
'''A MultiButton maps multiple buttons to the same channel like a
multiple-position switch. When a button is pressed, the channel
is set to the corresponding value. When a button is released, no
changes is made to the channel.'''
def __init__(self, joystick, buttons, **kwargs):
super(MultiButton, self).__init__(joystick, **kwargs)
self.buttons = buttons
self._value = buttons[0]['value']
@property
def value(self):
for button in self.buttons:
state = self.joystick.get_button(button['id'])
if state:
self._value = button['value']
break
return self._value
|
class MultiButton (Control):
'''A MultiButton maps multiple buttons to the same channel like a
multiple-position switch. When a button is pressed, the channel
is set to the corresponding value. When a button is released, no
changes is made to the channel.'''
def __init__(self, joystick, buttons, **kwargs):
pass
@property
def value(self):
pass
| 4 | 1 | 6 | 1 | 6 | 0 | 2 | 0.31 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 3 | 20 | 3 | 13 | 8 | 9 | 4 | 12 | 7 | 9 | 3 | 2 | 2 | 4 |
7,024 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_kmlread.py
|
MAVProxy.modules.mavproxy_kmlread.KmlReadModule
|
class KmlReadModule(mp_module.MPModule):
def __init__(self, mpstate):
super(KmlReadModule, self).__init__(mpstate, "kmlread", "Add kml or kmz layers to map", public=True)
self.add_command('kml', self.cmd_param, "kml map handling",
["<clear|snapwp|snapfence>",
"<load> (FILENAME)", '<layers>'])
# allayers is all the loaded layers (slimap objects)
# curlayers is only the layers displayed (checked) on the map (text list of layer names)
self.allayers = []
self.curlayers = []
self.alltextlayers = []
self.curtextlayers = []
self.initialised_map_module = False
self.menu_needs_refreshing = True
self.map_objects = {}
self.counter = 0
# the fence manager
self.snap_points = []
# make the initial map menu
if mp_util.has_wxpython:
self.menu_fence = MPMenuSubMenu('Set Geofence', items=[])
self.menu = MPMenuSubMenu(
'KML Layers',
items=[
MPMenuItem('Clear', 'Clear', '# kml clear'),
]
)
def cmd_param(self, args):
'''control kml reading'''
usage = "Usage: kml <clear | load (filename) | layers | toggle (layername) | colour (layername) (colour) | fence (inc|exc) (layername)> | snapfence | snapwp" # noqa
if len(args) < 1:
print(usage)
return
elif args[0] == "clear":
self.clearkml()
elif args[0] == "snapwp":
self.cmd_snap_wp(args[1:])
elif args[0] == "snapfence":
self.cmd_snap_fence(args[1:])
elif args[0] == "load":
if len(args) != 2:
print("usage: kml load <filename>")
return
self.loadkml(args[1])
elif args[0] == "layers":
for layer in self.curlayers:
print("Found layer: " + layer)
elif args[0] == "toggle":
self.togglekml(args[1])
elif args[0] == "colour" or args[0] == "color":
self.cmd_colour(args[1:])
elif args[0] == "fence":
self.fencekml(args[1:])
else:
print(usage)
return
def cmd_snap_wp(self, args):
'''snap waypoints to KML'''
threshold = 10.0
if len(args) > 0:
threshold = float(args[0])
wpmod = self.module('wp')
wploader = wpmod.wploader
changed = False
for i in range(1, wploader.count()):
w = wploader.wp(i)
if not wploader.is_location_command(w.command):
continue
lat = w.x
lon = w.y
best = None
best_dist = (threshold+1)*3
for (snap_lat, snap_lon) in self.snap_points:
dist = mp_util.gps_distance(lat, lon, snap_lat, snap_lon)
if dist < best_dist:
best_dist = dist
best = (snap_lat, snap_lon)
if best is not None and best_dist <= threshold:
if w.x != best[0] or w.y != best[1]:
w.x = best[0]
w.y = best[1]
print("Snapping WP %u to %f %f" % (i, w.x, w.y))
wploader.set(w, i)
changed = True
elif best is not None:
if best_dist <= (threshold+1)*3:
print("Not snapping wp %u dist %.1f" % (i, best_dist))
if changed:
wpmod.send_all_waypoints()
def cmd_snap_fence(self, args):
'''snap fence to KML'''
threshold = 10.0
if len(args) > 0:
threshold = float(args[0])
fencemod = self.module('fence')
if fencemod is None:
print("fence module not loaded")
return
def fencepoint_snapper(offset, point_obj):
best = None
best_dist = (threshold+1)*3
if isinstance(point_obj, mavutil.mavlink.MAVLink_mission_item_message):
point = (point_obj.x, point_obj.y)
elif isinstance(point_obj, mavutil.mavlink.MAVLink_mission_item_int_message):
point = (point_obj.x * 1e-7, point_obj.y * 1e-7)
else:
raise TypeError(f"What's a {type(point_obj)}?")
for snap_point in copy.copy(self.snap_points):
if point == snap_point:
return
dist = mp_util.gps_distance(point[0], point[1], snap_point[0], snap_point[1])
if dist < best_dist:
best_dist = dist
best = snap_point
if best is None:
return
if best_dist <= threshold:
print("Snapping fence point %u to %f %f" % (offset, best[0], best[1]))
if isinstance(point_obj, mavutil.mavlink.MAVLink_mission_item_message):
point_obj.x = best[0]
point_obj.y = best[1]
elif isinstance(point_obj, mavutil.mavlink.MAVLink_mission_item_int_message):
point_obj.x = best[0] * 1e7
point_obj.y = best[1] * 1e7
else:
raise TypeError(f"What's a {type(point_obj)}?")
self.snapped_fencepoint = True
return
if best_dist <= (threshold+1)*3:
print("Not snapping fence point %u dist %.1f" % (offset, best_dist))
self.snapped_fencepoint = False
fencemod.apply_function_to_points(fencepoint_snapper)
if self.snapped_fencepoint:
fencemod.push_to_vehicle()
def cmd_colour(self, args):
if len(args) < 2:
print("kml colour LAYERNAME 0xBBGGRR")
return
(layername, colour) = args
layer = self.find_layer(layername)
if layer is None:
print(f"No layer {layername}")
return
m = re.match(r"(?:0x)?(?P<red>[0-9A-Fa-f]{2})(?P<green>[0-9A-Fa-f]{2})(?P<blue>[0-9A-Fa-f]{2})", colour)
if m is None:
print("bad colour")
return
(red, green, blue) = (int(m.group("red"), 16),
int(m.group("green"), 16),
int(m.group("blue"), 16))
self.remove_map_object(layer)
layer.set_colour((red, green, blue))
self.add_map_object(layer)
def remove_map_object(self, obj):
'''remove an object from our stored list of objects, and the map
module if it is loaded'''
if obj.layer not in self.map_objects:
raise ValueError(f"{obj.layer=} not in added map_objects")
if obj.key not in self.map_objects[obj.layer]:
raise ValueError(f"{obj.key=} not in added map_objects[{obj.key}] (map_objects[{obj.layer}][{obj.key}]")
del self.map_objects[obj.layer][obj.key]
if len(self.map_objects[obj.layer]) == 0:
del self.map_objects[obj.layer]
map_module = self.mpstate.map
if map_module is not None:
map_module.remove_object(obj.key)
def remove_all_map_objects(self):
for layer in copy.deepcopy(self.map_objects):
for key in copy.deepcopy(self.map_objects[layer]):
self.remove_map_object(self.map_objects[layer][key])
def add_map_object(self, obj):
'''add an object to our stored list of objects, and the map
module if it is loaded'''
if obj.layer in self.map_objects and obj.key in self.map_objects[obj.layer]:
raise ValueError(f"Already have self.map_objects[{obj.layer=}][{obj.key=}]")
if obj.layer not in self.map_objects:
self.map_objects[obj.layer] = {}
self.map_objects[obj.layer][obj.key] = obj
map_module = self.mpstate.map
if map_module is not None:
map_module.add_object(obj)
def add_objects_to_map_module_from_map_objects(self):
for layer in self.map_objects:
for obj in self.map_objects[layer].values():
map_module = self.mpstate.map
map_module.add_object(obj)
def fencekml(self, args):
'''create a geofence from a layername'''
usage = "kml fence inc|exc layername"
if len(args) != 2:
print(usage)
return
fencemod = self.module('fence')
if fencemod is None:
print("fence module not loaded")
return
(inc_or_exc, layername) = (args[0], args[1])
if inc_or_exc in ["inc", "inclusion"]:
fence_type = mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION
elif inc_or_exc in ["exc", "exclusion"]:
fence_type = mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION
else:
print(usage)
return
# find the layer, add it if found
for layer in self.allayers:
if layer.key != layername:
continue
points_copy = copy.copy(layer.points)
if points_copy[-1] == points_copy[0]:
points_copy.pop(-1)
fencemod.add_polyfence(fence_type, points_copy)
return
print("Layer not found")
def togglekml(self, layername):
'''toggle the display of a kml'''
# Strip quotation marks if neccessary
if layername.startswith('"') and layername.endswith('"'):
layername = layername[1:-1]
# toggle layer off (plus associated text element)
if layername in self.curlayers:
for layer in self.curlayers:
if layer == layername:
self.remove_map_object(self.find_layer(layer))
self.curlayers.remove(layername)
if layername in self.curtextlayers:
for clayer in self.curtextlayers:
if clayer == layername:
self.remove_map_object(self.find_layer(clayer))
self.curtextlayers.remove(clayer)
# toggle layer on (plus associated text element)
else:
for layer in self.allayers:
if layer.key == layername:
self.add_map_object(layer)
self.curlayers.append(layername)
for alayer in self.alltextlayers:
if alayer.key == layername:
self.add_map_object(alayer)
self.curtextlayers.append(layername)
self.menu_needs_refreshing = True
def find_layer(self, layername):
for layer in self.allayers:
if layer.key == layername:
return layer
return None
def clearkml(self):
'''Clear the kmls from the map'''
# go through all the current layers and remove them
self.remove_all_map_objects()
self.allayers = []
self.curlayers = []
self.alltextlayers = []
self.curtextlayers = []
self.menu_needs_refreshing = True
def add_polygon(self, name, coords):
'''add a polygon to the KML list. coords is a list of lat/lng tuples in degrees'''
self.snap_points.extend(coords)
# print("Adding " + name)
newcolour = (random.randint(0, 255), 0, random.randint(0, 255))
layer_name = f"{name}-{self.counter}"
curpoly = mp_slipmap.SlipPolygon(
layer_name,
coords,
layer=2,
linewidth=2,
colour=newcolour,
)
self.add_map_object(curpoly)
self.allayers.append(curpoly)
self.curlayers.append(layer_name)
self.counter += 1
def loadkml(self, filename):
'''Load a kml from file and put it on the map'''
# Open the zip file
nodes = kmlread.readkmz(filename)
self.snap_points = []
# go through each object in the kml...
if nodes is None:
print("No nodes found")
return
for n in nodes:
try:
point = kmlread.readObject(n)
except Exception:
continue
if point is None:
continue
# and place any polygons on the map
(pointtype, name, coords) = point
if pointtype == 'Polygon':
self.add_polygon(name, coords)
# and points - barrell image and text
if pointtype == 'Point':
# print("Adding " + point[1])
curpoint = mp_slipmap.SlipIcon(
point[1],
latlon=(point[2][0][0], point[2][0][1]),
layer=3,
img='barrell.png',
rotation=0,
follow=False,
)
curtext = mp_slipmap.SlipLabel(
point[1],
point=(point[2][0][0], point[2][0][1]),
layer=4,
label=point[1],
colour=(0, 255, 255),
)
self.add_map_object(curpoint)
self.add_map_object(curtext)
self.allayers.append(curpoint)
self.alltextlayers.append(curtext)
self.curlayers.append(point[1])
self.curtextlayers.append(point[1])
self.menu_needs_refreshing = True
def idle_task(self):
'''handle GUI elements'''
if self.module('map') is None:
self.initialised_map_module = False
return
if not self.initialised_map_module:
self.menu_needs_refreshing = True
self.add_objects_to_map_module_from_map_objects()
self.initialised_map_module = True
if self.menu_needs_refreshing:
self.refresh_menu()
self.menu_needs_refreshing = False
def refresh_menu(self):
if True:
if not mp_util.has_wxpython:
return
# (re)create the menu
# we don't dynamically update these yet due to a wx bug
self.menu.items = [
MPMenuItem('Clear', 'Clear', '# kml clear'),
MPMenuItem(
'Load', 'Load', '# kml load ',
handler=MPMenuCallFileDialog(
flags=('open',),
title='KML Load',
wildcard='*.kml;*.kmz',
)
),
self.menu_fence,
MPMenuSeparator(),
]
self.menu_fence.items = []
for layer in self.allayers:
# if it's a polygon, add it to the "set Geofence" list
if isinstance(layer, mp_slipmap.SlipPolygon):
self.menu_fence.items.append(MPMenuItem(
layer.key,
layer.key,
'# kml fence \"' + layer.key + '\"',
))
# then add all the layers to the menu, ensuring to
# check the active layers text elements aren't
# included on the menu
if layer.key.endswith('-text'):
continue
checked = layer.key in self.curlayers
self.menu.items.append(MPMenuCheckbox(
layer.key,
layer.key,
f'# kml toggle \"{layer.key}\"',
checked=checked,
))
# and add the menu to the map popu menu
self.module('map').add_menu(self.menu)
self.menu_needs_refreshing = False
def mavlink_packet(self, m):
'''handle a mavlink packet'''
|
class KmlReadModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_param(self, args):
'''control kml reading'''
pass
def cmd_snap_wp(self, args):
'''snap waypoints to KML'''
pass
def cmd_snap_fence(self, args):
'''snap fence to KML'''
pass
def fencepoint_snapper(offset, point_obj):
pass
def cmd_colour(self, args):
pass
def remove_map_object(self, obj):
'''remove an object from our stored list of objects, and the map
module if it is loaded'''
pass
def remove_all_map_objects(self):
pass
def add_map_object(self, obj):
'''add an object to our stored list of objects, and the map
module if it is loaded'''
pass
def add_objects_to_map_module_from_map_objects(self):
pass
def fencekml(self, args):
'''create a geofence from a layername'''
pass
def togglekml(self, layername):
'''toggle the display of a kml'''
pass
def find_layer(self, layername):
pass
def clearkml(self):
'''Clear the kmls from the map'''
pass
def add_polygon(self, name, coords):
'''add a polygon to the KML list. coords is a list of lat/lng tuples in degrees'''
pass
def loadkml(self, filename):
'''Load a kml from file and put it on the map'''
pass
def idle_task(self):
'''handle GUI elements'''
pass
def refresh_menu(self):
pass
def mavlink_packet(self, m):
'''handle a mavlink packet'''
pass
| 20 | 12 | 23 | 2 | 19 | 2 | 5 | 0.12 | 1 | 16 | 8 | 0 | 18 | 12 | 18 | 56 | 418 | 44 | 338 | 85 | 318 | 42 | 272 | 85 | 252 | 12 | 2 | 6 | 102 |
7,025 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_layout.py
|
MAVProxy.modules.mavproxy_layout.LayoutModule
|
class LayoutModule(mp_module.MPModule):
def __init__(self, mpstate):
super(LayoutModule, self).__init__(mpstate, "layout", "window layout handling", public = False)
self.add_command('layout', self.cmd_layout,
'window layout management',
["<save|load>"])
def cmd_layout(self, args):
'''handle layout command'''
from MAVProxy.modules.lib import win_layout
if len(args) < 1:
print("usage: layout <save|load>")
return
if args[0] == "load":
win_layout.load_layout(self.mpstate.settings.vehicle_name)
elif args[0] == "save":
win_layout.save_layout(self.mpstate.settings.vehicle_name)
|
class LayoutModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_layout(self, args):
'''handle layout command'''
pass
| 3 | 1 | 8 | 0 | 7 | 1 | 3 | 0.07 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 40 | 17 | 1 | 15 | 4 | 11 | 1 | 12 | 4 | 8 | 4 | 2 | 1 | 5 |
7,026 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.RendererWx
|
class RendererWx(RendererBase):
"""
The renderer handles all the drawing primitives using a graphics
context instance that controls the colors/styles. It acts as the
'renderer' instance used by many classes in the hierarchy.
"""
#In wxPython, drawing is performed on a wxDC instance, which will
#generally be mapped to the client aread of the window displaying
#the plot. Under wxPython, the wxDC instance has a wx.Pen which
#describes the colour and weight of any lines drawn, and a wxBrush
#which describes the fill colour of any closed polygon.
fontweights = {
100 : wx.LIGHT,
200 : wx.LIGHT,
300 : wx.LIGHT,
400 : wx.NORMAL,
500 : wx.NORMAL,
600 : wx.NORMAL,
700 : wx.BOLD,
800 : wx.BOLD,
900 : wx.BOLD,
'ultralight' : wx.LIGHT,
'light' : wx.LIGHT,
'normal' : wx.NORMAL,
'medium' : wx.NORMAL,
'semibold' : wx.NORMAL,
'bold' : wx.BOLD,
'heavy' : wx.BOLD,
'ultrabold' : wx.BOLD,
'black' : wx.BOLD
}
fontangles = {
'italic' : wx.ITALIC,
'normal' : wx.NORMAL,
'oblique' : wx.SLANT }
# wxPython allows for portable font styles, choosing them appropriately
# for the target platform. Map some standard font names to the portable
# styles
# QUESTION: Is it be wise to agree standard fontnames across all backends?
fontnames = { 'Sans' : wx.SWISS,
'Roman' : wx.ROMAN,
'Script' : wx.SCRIPT,
'Decorative' : wx.DECORATIVE,
'Modern' : wx.MODERN,
'Courier' : wx.MODERN,
'courier' : wx.MODERN }
def __init__(self, bitmap, dpi):
"""
Initialise a wxWindows renderer instance.
"""
RendererBase.__init__(self)
DEBUG_MSG("__init__()", 1, self)
if wx.VERSION_STRING < "2.8":
raise RuntimeError("matplotlib no longer supports wxPython < 2.8 for the Wx backend.\nYou may, however, use the WxAgg backend.")
self.width = bitmap.GetWidth()
self.height = bitmap.GetHeight()
self.bitmap = bitmap
self.fontd = {}
self.dpi = dpi
self.gc = None
def flipy(self):
return True
def offset_text_height(self):
return True
def get_text_width_height_descent(self, s, prop, ismath):
"""
get the width and height in display coords of the string s
with FontPropertry prop
"""
#return 1, 1
if ismath: s = self.strip_math(s)
if self.gc is None:
gc = self.new_gc()
else:
gc = self.gc
gfx_ctx = gc.gfx_ctx
font = self.get_wx_font(s, prop)
gfx_ctx.SetFont(font, wx.BLACK)
w, h, descent, leading = gfx_ctx.GetFullTextExtent(s)
return w, h, descent
def get_canvas_width_height(self):
'return the canvas width and height in display coords'
return self.width, self.height
def handle_clip_rectangle(self, gc):
new_bounds = gc.get_clip_rectangle()
if new_bounds is not None:
new_bounds = new_bounds.bounds
gfx_ctx = gc.gfx_ctx
if gfx_ctx._lastcliprect != new_bounds:
gfx_ctx._lastcliprect = new_bounds
if new_bounds is None:
gfx_ctx.ResetClip()
else:
gfx_ctx.Clip(new_bounds[0], self.height - new_bounds[1] - new_bounds[3],
new_bounds[2], new_bounds[3])
@staticmethod
def convert_path(gfx_ctx, path, transform):
wxpath = gfx_ctx.CreatePath()
for points, code in path.iter_segments(transform):
if code == Path.MOVETO:
wxpath.MoveToPoint(*points)
elif code == Path.LINETO:
wxpath.AddLineToPoint(*points)
elif code == Path.CURVE3:
wxpath.AddQuadCurveToPoint(*points)
elif code == Path.CURVE4:
wxpath.AddCurveToPoint(*points)
elif code == Path.CLOSEPOLY:
wxpath.CloseSubpath()
return wxpath
def draw_path(self, gc, path, transform, rgbFace=None):
gc.select()
self.handle_clip_rectangle(gc)
gfx_ctx = gc.gfx_ctx
transform = transform + Affine2D().scale(1.0, -1.0).translate(0.0, self.height)
wxpath = self.convert_path(gfx_ctx, path, transform)
if rgbFace is not None:
gfx_ctx.SetBrush(wx.Brush(gc.get_wxcolour(rgbFace)))
gfx_ctx.DrawPath(wxpath)
else:
gfx_ctx.StrokePath(wxpath)
gc.unselect()
def draw_image(self, gc, x, y, im):
bbox = gc.get_clip_rectangle()
if bbox != None:
l,b,w,h = bbox.bounds
else:
l=0
b=0,
w=self.width
h=self.height
rows, cols, image_str = im.as_rgba_str()
image_array = np.fromstring(image_str, np.uint8)
image_array.shape = rows, cols, 4
bitmap = wx.BitmapFromBufferRGBA(cols,rows,image_array)
gc = self.get_gc()
gc.select()
gc.gfx_ctx.DrawBitmap(bitmap,int(l),int(self.height-b),int(w),int(-h))
gc.unselect()
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
if ismath: s = self.strip_math(s)
DEBUG_MSG("draw_text()", 1, self)
gc.select()
self.handle_clip_rectangle(gc)
gfx_ctx = gc.gfx_ctx
font = self.get_wx_font(s, prop)
color = gc.get_wxcolour(gc.get_rgb())
gfx_ctx.SetFont(font, color)
w, h, d = self.get_text_width_height_descent(s, prop, ismath)
x = int(x)
y = int(y-h)
if angle == 0.0:
gfx_ctx.DrawText(s, x, y)
else:
rads = angle / 180.0 * math.pi
xo = h * math.sin(rads)
yo = h * math.cos(rads)
gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)
gc.unselect()
def new_gc(self):
"""
Return an instance of a GraphicsContextWx, and sets the current gc copy
"""
DEBUG_MSG('new_gc()', 2, self)
self.gc = GraphicsContextWx(self.bitmap, self)
self.gc.select()
self.gc.unselect()
return self.gc
def get_gc(self):
"""
Fetch the locally cached gc.
"""
# This is a dirty hack to allow anything with access to a renderer to
# access the current graphics context
assert self.gc != None, "gc must be defined"
return self.gc
def get_wx_font(self, s, prop):
"""
Return a wx font. Cache instances in a font dictionary for
efficiency
"""
DEBUG_MSG("get_wx_font()", 1, self)
key = hash(prop)
fontprop = prop
fontname = fontprop.get_name()
font = self.fontd.get(key)
if font is not None:
return font
# Allow use of platform independent and dependent font names
wxFontname = self.fontnames.get(fontname, wx.ROMAN)
wxFacename = '' # Empty => wxPython chooses based on wx_fontname
# Font colour is determined by the active wx.Pen
# TODO: It may be wise to cache font information
size = self.points_to_pixels(fontprop.get_size_in_points())
font =wx.Font(int(size+0.5), # Size
wxFontname, # 'Generic' name
self.fontangles[fontprop.get_style()], # Angle
self.fontweights[fontprop.get_weight()], # Weight
False, # Underline
wxFacename) # Platform font name
# cache the font and gc and return it
self.fontd[key] = font
return font
def points_to_pixels(self, points):
"""
convert point measures to pixes using dpi and the pixels per
inch of the display
"""
return points*(PIXELS_PER_INCH/72.0*self.dpi/72.0)
|
class RendererWx(RendererBase):
'''
The renderer handles all the drawing primitives using a graphics
context instance that controls the colors/styles. It acts as the
'renderer' instance used by many classes in the hierarchy.
'''
def __init__(self, bitmap, dpi):
'''
Initialise a wxWindows renderer instance.
'''
pass
def flipy(self):
pass
def offset_text_height(self):
pass
def get_text_width_height_descent(self, s, prop, ismath):
'''
get the width and height in display coords of the string s
with FontPropertry prop
'''
pass
def get_canvas_width_height(self):
'''return the canvas width and height in display coords'''
pass
def handle_clip_rectangle(self, gc):
pass
@staticmethod
def convert_path(gfx_ctx, path, transform):
pass
def draw_path(self, gc, path, transform, rgbFace=None):
pass
def draw_image(self, gc, x, y, im):
pass
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
pass
def new_gc(self):
'''
Return an instance of a GraphicsContextWx, and sets the current gc copy
'''
pass
def get_gc(self):
'''
Fetch the locally cached gc.
'''
pass
def get_wx_font(self, s, prop):
'''
Return a wx font. Cache instances in a font dictionary for
efficiency
'''
pass
def points_to_pixels(self, points):
'''
convert point measures to pixes using dpi and the pixels per
inch of the display
'''
pass
| 16 | 8 | 13 | 1 | 10 | 3 | 2 | 0.3 | 1 | 3 | 1 | 0 | 13 | 6 | 14 | 14 | 242 | 33 | 166 | 54 | 150 | 50 | 124 | 53 | 109 | 7 | 1 | 2 | 31 |
7,027 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_link.py
|
MAVProxy.modules.mavproxy_link.LinkModule
|
class LinkModule(mp_module.MPModule):
def __init__(self, mpstate):
super(LinkModule, self).__init__(mpstate, "link", "link control", public=True, multi_vehicle=True)
self.add_command('link', self.cmd_link, "link control",
["<list|ports|resetstats>",
'add (SERIALPORT)',
'attributes (LINK) (ATTRIBUTES)',
'remove (LINKS)',
'dataratelogging (DLSTATE)',
'hl (HLSTATE)'])
self.add_command('vehicle', self.cmd_vehicle, "vehicle control")
self.add_command('alllinks', self.cmd_alllinks, "send command on all links", ["(COMMAND)"])
self.add_command('ping', self.cmd_ping, "ping mavlink nodes")
self.no_fwd_types = set()
self.no_fwd_types.add("BAD_DATA")
self.add_completion_function('(SERIALPORT)', self.complete_serial_ports)
self.add_completion_function('(LINKS)', self.complete_links)
self.add_completion_function('(LINK)', self.complete_links)
self.add_completion_function('(HLSTATE)', self.complete_hl)
self.add_completion_function('(DLSTATE)', self.complete_dl)
self.last_altitude_announce = 0.0
self.vehicle_list = set()
self.high_latency = False
self.datarate_logging = False
self.datarate_logging_timer = mavutil.periodic_event(1)
self.old_streamrate = 0
self.old_streamrate2 = 0
# a list of TimeSync requests which are listening for and
# sending TIMESYNC messages at the moment:
self.outstanding_timesyncs = []
self.menu_added_console = False
if mp_util.has_wxpython:
self.menu_rm = MPMenuSubMenu('Remove', items=[])
items = [
MPMenuItem('Add...', 'Add...', '# link add ', handler=MPMenulinkAddDialog()),
self.menu_rm,
MPMenuItem('Ports', 'Ports', '# link ports'),
MPMenuItem('List', 'List', '# link list'),
MPMenuItem('Status', 'Status', '# link')]
# wsproto is not installed by default.
# Only add the menu if it's available.
try:
import wsproto # noqa: F401
except ImportError:
pass
else:
items.append(
MPMenuItem('Start Websocket Server', 'Start Websocket Server', '# output add wsserver:0.0.0.0:',
handler=MPMenuCallTextDialog(
title='Websocket Port',
default=56781
)))
self.menu = MPMenuSubMenu('Link', items=items)
self.last_menu_update = 0
def idle_task(self):
'''called on idle'''
if mp_util.has_wxpython:
if self.module('console') is not None:
if not self.menu_added_console:
self.menu_added_console = True
# we don't dynamically update these yet due to a wx bug
self.menu_rm.items = [
MPMenuItem(p, p, '# link remove %s' % p) for p in self.complete_links('')
]
self.module('console').add_menu(self.menu)
else:
self.menu_added_console = False
for m in self.mpstate.mav_master:
m.source_system = self.settings.source_system
m.mav.srcSystem = m.source_system
m.mav.srcComponent = self.settings.source_component
# don't let pending statustext wait forever for last chunk:
for src in self.status.statustexts_by_sysidcompid:
msgids = list(self.status.statustexts_by_sysidcompid[src].keys())
for msgid in msgids:
pending = self.status.statustexts_by_sysidcompid[src][msgid]
if time.time() - pending.last_chunk_time > 1:
self.emit_accumulated_statustext(src, msgid, pending)
# datarate logging if enabled, at 1 Hz
if self.datarate_logging_timer.trigger() and self.datarate_logging:
with open(self.datarate_logging, 'a') as logfile:
for master in self.mpstate.mav_master:
highest_msec_key = (self.target_system, self.target_component)
linkdelay = (self.status.highest_msec.get(highest_msec_key, 0) - master.highest_msec.get(highest_msec_key, 0))*1.0e-3 # noqa
logfile.write(str(time.strftime("%H:%M:%S")) + "," +
str(self.link_label(master)) + "," +
str(master.linknum) + "," +
str(self.status.counters['MasterIn'][master.linknum]) + "," +
str(self.status.bytecounters['MasterIn'][master.linknum].total()) + "," +
str(linkdelay) + "," +
str(100 * round(master.packet_loss(), 3)) + "\n")
# update outstanding TimeSyncRequest objects. Reap any which
# are past their use-by date:
new_timesyncs = []
for ts in self.outstanding_timesyncs:
if ts.age_limit_exceeded():
continue
ts.update()
new_timesyncs.append(ts)
self.outstanding_timesyncs = new_timesyncs
def complete_serial_ports(self, text):
'''return list of serial ports'''
ports = mavutil.auto_detect_serial(preferred_list=preferred_ports)
return [p.device for p in ports]
def complete_hl(self, text):
'''return list of hl options'''
return ['on', 'off']
def complete_dl(self, text):
'''return list of datarate_logging options'''
return ['on', 'off']
def complete_links(self, text):
'''return list of links'''
try:
ret = [m.address for m in self.mpstate.mav_master]
for m in self.mpstate.mav_master:
ret.append(m.address)
if hasattr(m, 'label'):
ret.append(m.label)
return ret
except Exception as e:
print("Caught exception: %s" % str(e))
def cmd_link(self, args):
'''handle link commands'''
if len(args) < 1:
self.show_link()
elif args[0] == "list":
self.cmd_link_list()
elif args[0] == "hl":
self.cmd_hl(args[1:])
elif args[0] == "dataratelogging":
self.cmd_dl(args[1:])
elif args[0] == "add":
if len(args) != 2:
print("Usage: link add LINK")
print('Usage: e.g. link add 127.0.0.1:9876')
print('Usage: e.g. link add 127.0.0.1:9876:{"label":"rfd900"}')
return
self.cmd_link_add(args[1:])
elif args[0] == "attributes":
if len(args) != 3:
print("Usage: link attributes LINK ATTRIBUTES")
print('Usage: e.g. link attributes rfd900 {"label":"bob"}')
return
self.cmd_link_attributes(args[1:])
elif args[0] == "ports":
self.cmd_link_ports()
elif args[0] == "remove":
if len(args) != 2:
print("Usage: link remove LINK")
return
self.cmd_link_remove(args[1:])
elif args[0] == "resetstats":
self.reset_link_stats()
elif args[0] == "ping":
self.cmd_ping(args[1:])
else:
print("usage: link <list|add|remove|attributes|hl|dataratelogging|resetstats>")
def cmd_dl(self, args):
'''Toggle datarate logging'''
if len(args) < 1:
print("Datarate logging is " + ("on" if self.datarate_logging else "off"))
return
elif args[0] == "on":
self.datarate_logging = os.path.join(self.logdir, "dataratelog.csv")
print("Datarate Logging ON, logfile: " + self.datarate_logging)
# Open a new file handle (don't append) for logging
with open(self.datarate_logging, 'w') as logfile:
logfile.write("time, linkname, linkid, packetsreceived, bytesreceived, delaysec, lostpercent\n")
elif args[0] == "off":
print("Datarate Logging OFF")
self.datarate_logging = None
else:
print("usage: dataratelogging <on|off>")
def cmd_hl(self, args):
'''Toggle high latency mode'''
if len(args) < 1:
print("High latency mode is " + str(self.high_latency))
return
elif args[0] == "on":
print("High latency mode ON")
self.high_latency = True
# Tell ArduPilot to start sending HIGH_LATENCY2 messages
self.master.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavutil.mavlink.MAV_CMD_CONTROL_HIGH_LATENCY, # command
0, # confirmation
1, # param1 (yes/no)
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
return
elif args[0] == "off":
print("High latency mode OFF")
self.high_latency = False
self.master.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavutil.mavlink.MAV_CMD_CONTROL_HIGH_LATENCY, # command
0, # confirmation
0, # param1 (yes/no)
0, # param2
0, # param3
0, # param4
0, # param5
0, # param6
0) # param7
return
else:
print("usage: hl <on|off>")
def show_link(self):
'''show link information'''
for master in self.mpstate.mav_master:
highest_msec_key = (self.target_system, self.target_component)
linkdelay = (self.status.highest_msec.get(highest_msec_key, 0) - master.highest_msec.get(highest_msec_key, 0))*1.0e-3 # noqa
if master.linkerror:
status = "DOWN"
else:
status = "OK"
sign_string = ''
try:
if master.mav.signing.sig_count:
if master.mav.signing.secret_key is None:
# unsigned/reject counts are not updated if we
# don't have a signing secret
sign_string = ", (no-signing-secret)"
else:
sign_string = ", unsigned %u reject %u" % (master.mav.signing.unsigned_count, master.mav.signing.reject_count) # noqa
except AttributeError:
# some mav objects may not have a "signing" attribute
pass
print("link %s %s (%u packets, %u bytes, %.2fs delay, %u lost, %.1f%% loss, rate:%uB/s%s)" % (
self.link_label(master),
status,
self.status.counters['MasterIn'][master.linknum],
self.status.bytecounters['MasterIn'][master.linknum].total(),
linkdelay,
master.mav_loss,
master.packet_loss(),
self.status.bytecounters['MasterIn'][master.linknum].rate(),
sign_string,
))
def reset_link_stats(self):
'''reset link statistics'''
for master in self.mpstate.mav_master:
self.status.counters['MasterIn'][master.linknum] = 0
self.status.bytecounters['MasterIn'][master.linknum].__init__()
master.mav_loss = 0
master.mav_count = 0
def cmd_alllinks(self, args):
'''send command on all links'''
saved_target = self.mpstate.settings.target_system
print("Sending to: ", self.vehicle_list)
for v in sorted(self.vehicle_list):
self.cmd_vehicle([str(v)])
self.mpstate.functions.process_stdin(' '.join(args), True)
self.cmd_vehicle([str(saved_target)])
def cmd_link_list(self):
'''list links'''
print("%u links" % len(self.mpstate.mav_master))
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
if hasattr(conn, 'label'):
print("%u (%s): %s" % (i, conn.label, conn.address))
else:
print("%u: %s" % (i, conn.address))
def parse_link_attributes(self, some_json):
'''return a dict based on some_json (empty if json invalid)'''
try:
return json.loads(some_json)
except ValueError:
print('Invalid JSON argument: {0}'.format(some_json))
return {}
def parse_link_descriptor(self, descriptor):
'''parse e.g. 'udpin:127.0.0.1:9877:{"foo":"bar"}' into
python structure ("udpin:127.0.0.1:9877", {"foo":"bar"})'''
optional_attributes = {}
link_components = descriptor.split(":{", 1)
device = link_components[0]
if (len(link_components) == 2 and link_components[1].endswith("}")):
# assume json
some_json = "{" + link_components[1]
optional_attributes = self.parse_link_attributes(some_json)
return (device, optional_attributes)
def apply_link_attributes(self, conn, optional_attributes):
for attr in optional_attributes:
print("Applying attribute to link: %s = %s" % (attr, optional_attributes[attr]))
setattr(conn, attr, optional_attributes[attr])
def link_add(self, descriptor, force_connected=False, retries=3):
'''add new link'''
try:
(device, optional_attributes) = self.parse_link_descriptor(descriptor)
# if there's only 1 colon for port:baud
# and if the first string is a valid serial port, it's a serial connection
if len(device.split(':')) == 2:
ports = mavutil.auto_detect_serial(preferred_list=preferred_ports)
for p in ports:
if p.device == device.split(':')[0]:
# it's a valid serial port, reformat arguments to fit
self.settings.baudrate = int(device.split(':')[1])
device = device.split(':')[0]
break
print("Connect %s source_system=%d" % (device, self.settings.source_system))
try:
conn = mavutil.mavlink_connection(device, autoreconnect=True,
source_system=self.settings.source_system,
baud=self.settings.baudrate,
force_connected=force_connected,
retries=retries)
except Exception:
# try the same thing but without force-connected for
# backwards-compatability
conn = mavutil.mavlink_connection(device, autoreconnect=True,
source_system=self.settings.source_system,
baud=self.settings.baudrate,
retries=retries)
conn.mav.srcComponent = self.settings.source_component
except Exception as msg:
print("Failed to connect to %s : %s" % (descriptor, msg))
return False
if self.settings.rtscts:
conn.set_rtscts(True)
conn.mav.set_callback(self.master_callback, conn)
if hasattr(conn.mav, 'set_send_callback'):
conn.mav.set_send_callback(self.master_send_callback, conn)
conn.linknum = len(self.mpstate.mav_master)
conn.linkerror = False
conn.link_delayed = False
conn.last_heartbeat = 0
conn.last_message = 0
conn.highest_msec = {}
conn.target_system = self.settings.target_system
self.apply_link_attributes(conn, optional_attributes)
self.mpstate.mav_master.append(conn)
self.status.counters['MasterIn'].append(0)
self.status.bytecounters['MasterIn'].append(self.status.ByteCounter())
self.mpstate.vehicle_link_map[conn.linknum] = set(())
try:
mp_util.child_fd_list_add(conn.port.fileno())
except Exception:
pass
return True
def cmd_link_add(self, args):
'''add new link'''
descriptor = args[0]
print("Adding link %s" % descriptor)
self.link_add(descriptor)
def link_attributes(self, link, attributes):
i = self.find_link(link)
if i is None:
print("Connection (%s) not found" % (link,))
return
conn = self.mpstate.mav_master[i]
atts = self.parse_link_attributes(attributes)
self.apply_link_attributes(conn, atts)
def cmd_link_attributes(self, args):
'''change optional link attributes'''
link = args[0]
attributes = args[1]
print("Setting link %s attributes (%s)" % (link, attributes))
self.link_attributes(link, attributes)
def cmd_link_ports(self):
'''show available ports'''
ports = mavutil.auto_detect_serial(preferred_list=preferred_ports)
for p in ports:
print("%s : %s : %s" % (p.device, p.description, p.hwid))
def find_link(self, device):
'''find a device based on number, name or label'''
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
if (str(i) == device or
conn.address == device or
getattr(conn, 'label', None) == device):
return i
return None
def cmd_link_remove(self, args):
'''remove an link'''
device = args[0]
if len(self.mpstate.mav_master) <= 1:
print("Not removing last link")
return
i = self.find_link(device)
if i is None:
return
conn = self.mpstate.mav_master[i]
print("Removing link %s" % conn.address)
try:
try:
mp_util.child_fd_list_remove(conn.port.fileno())
except Exception:
pass
self.mpstate.mav_master[i].close()
except Exception as msg:
print(msg)
pass
self.mpstate.mav_master.pop(i)
self.status.counters['MasterIn'].pop(i)
self.status.bytecounters['MasterIn'].pop(i)
del self.mpstate.vehicle_link_map[conn.linknum]
# renumber the links
vehicle_link_map_reordered = {}
for j in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[j]
map_old = self.mpstate.vehicle_link_map[conn.linknum]
conn.linknum = j
vehicle_link_map_reordered[j] = map_old
self.mpstate.vehicle_link_map = vehicle_link_map_reordered
def get_usec(self):
'''time since 1970 in microseconds'''
return int(time.time() * 1.0e6)
def dump_message_verbose(self, m):
'''return verbose dump of m. Wraps the pymavlink routine which
inconveniently takes a filehandle'''
f = StringIO.StringIO()
mavutil.dump_message_verbose(f, m)
return f.getvalue()
def check_watched_message(self, m, direction_string):
'''if we are watching a message, print it out'''
if self.status.watch is None:
return
mtype = m.get_type().upper()
for msg_type in self.status.watch:
if not fnmatch.fnmatch(mtype, msg_type.upper()):
continue
if self.status.watch_verbose:
message_string = self.dump_message_verbose(m)
else:
message_string = str(m)
self.mpstate.console.writeln(direction_string + ' ' + message_string)
break
def master_send_callback(self, m, master):
'''called on sending a message'''
self.check_watched_message(m, '>')
mtype = m.get_type()
if mtype != 'BAD_DATA' and self.mpstate.logqueue:
usec = self.get_usec()
usec = (usec & ~3) | 3 # linknum 3
self.mpstate.logqueue.put(bytearray(struct.pack('>Q', usec) + m.get_msgbuf()))
def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
if m.get_type() == 'GLOBAL_POSITION_INT':
# this is fix time, not boot time
return
msec = m.time_boot_ms
if msec == 0:
return
sysid = m.get_srcSystem()
compid = m.get_srcComponent()
highest_msec_key = (sysid, compid)
highest = master.highest_msec.get(highest_msec_key, 0)
if msec + 30000 < highest:
self.say('Time has wrapped')
print('Time has wrapped', msec, highest)
self.status.highest_msec[highest_msec_key] = msec
for mm in self.mpstate.mav_master:
mm.link_delayed = False
mm.highest_msec[highest_msec_key] = msec
return
# we want to detect when a link is delayed
master.highest_msec[highest_msec_key] = msec
if msec > self.status.highest_msec.get(highest_msec_key, 0):
self.status.highest_msec[highest_msec_key] = msec
if msec < self.status.highest_msec.get(highest_msec_key, 0) and len(self.mpstate.mav_master) > 1 and self.mpstate.settings.checkdelay: # noqa
master.link_delayed = True
else:
master.link_delayed = False
def colors_for_severity(self, severity):
# Windows and Linux have wildly difference concepts of
# "green",so use specific RGB values:
green = (0, 128, 0)
severity_colors = {
# tuple is (fg, bg) (as in "white on red")
mavutil.mavlink.MAV_SEVERITY_EMERGENCY: ('white', 'red'),
mavutil.mavlink.MAV_SEVERITY_ALERT: ('white', 'red'),
mavutil.mavlink.MAV_SEVERITY_CRITICAL: ('white', 'red'),
mavutil.mavlink.MAV_SEVERITY_ERROR: ('black', 'orange'),
mavutil.mavlink.MAV_SEVERITY_WARNING: ('black', 'orange'),
mavutil.mavlink.MAV_SEVERITY_NOTICE: ('black', 'yellow'),
mavutil.mavlink.MAV_SEVERITY_INFO: ('white', green),
mavutil.mavlink.MAV_SEVERITY_DEBUG: ('white', green),
}
try:
return severity_colors[severity]
except Exception as e:
print("Exception: %s" % str(e))
return ('white', 'red')
def report_altitude(self, altitude):
'''possibly report a new altitude'''
master = self.master
if len(self.module_matching('terrain')) > 0 and self.mpstate.settings.basealt != 0:
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0)*1.0e-7
lon = master.field('GLOBAL_POSITION_INT', 'lon', 0)*1.0e-7
alt1 = self.module('terrain').ElevationModel.GetElevation(lat, lon)
if alt1 is not None:
alt2 = self.mpstate.settings.basealt
altitude += alt2 - alt1
self.status.altitude = altitude
altitude_converted = self.height_convert_units(altitude)
if (int(self.mpstate.settings.altreadout) > 0 and
math.fabs(altitude_converted - self.last_altitude_announce) >=
int(self.settings.altreadout)):
self.last_altitude_announce = altitude_converted
rounded_alt = int(self.settings.altreadout) * ((self.settings.altreadout/2 + int(altitude_converted)) / int(self.settings.altreadout)) # noqa
self.say("height %u" % rounded_alt, priority='notification')
def emit_accumulated_statustext(self, key, id, pending):
out = pending.accumulated_statustext()
if out != self.status.last_apm_msg or time.time() > self.status.last_apm_msg_time+2:
(fg, bg) = self.colors_for_severity(pending.severity)
out = pending.accumulated_statustext()
self.mpstate.console.writeln("AP: %s" % out, bg=bg, fg=fg)
self.status.last_apm_msg = out
self.status.last_apm_msg_time = time.time()
del self.status.statustexts_by_sysidcompid[key][id]
mav_types_which_are_not_vehicles = frozenset([
"MAV_TYPE_GCS",
"MAV_TYPE_ONBOARD_CONTROLLER",
"MAV_TYPE_GIMBAL",
"MAV_TYPE_ADSB",
"MAV_TYPE_CAMERA",
"MAV_TYPE_CHARGING_STATION",
"MAV_TYPE_SERVO",
"MAV_TYPE_ODID",
"MAV_TYPE_BATTERY",
"MAV_TYPE_LOG",
"MAV_TYPE_OSD",
"MAV_TYPE_IMU",
"MAV_TYPE_GPS",
"MAV_TYPE_WINCH",
])
mav_autopilots_which_are_not_vehicles = frozenset([
mavutil.mavlink.MAV_AUTOPILOT_INVALID,
mavutil.mavlink.MAV_AUTOPILOT_RESERVED,
])
component_ids_which_are_not_vehicles = frozenset([
mavutil.mavlink.MAV_COMP_ID_ADSB,
mavutil.mavlink.MAV_COMP_ID_ODID_TXRX_1,
mavutil.mavlink.MAV_COMP_ID_ODID_TXRX_2,
mavutil.mavlink.MAV_COMP_ID_ODID_TXRX_3
])
def heartbeat_is_from_autopilot(self, m):
'''returns true if m is a HEARTBEAT (or HIGH_LATENCY2) message and
looks like it is from an actual autopilot rather than from e.g. a
mavlink-connected camera'''
mtype = m.get_type()
if mtype not in ['HEARTBEAT', 'HIGH_LATENCY2']:
return False
if m.autopilot in LinkModule.mav_autopilots_which_are_not_vehicles:
return False
# this is a rather bogus assumption - and might break people's
# setups. It should probably be removed in favour of trusting
# the MAV_TYPE field.
if m.get_srcComponent() in LinkModule.component_ids_which_are_not_vehicles:
return False
found_mav_type = False
# not all of these are present in all versions of mavlink:
for t in LinkModule.mav_types_which_are_not_vehicles:
if getattr(mavutil.mavlink, t, None) is not None:
found_mav_type = True
break
if not found_mav_type:
return False
return True
mav_type_planes = [
mavutil.mavlink.MAV_TYPE_FIXED_WING,
mavutil.mavlink.MAV_TYPE_VTOL_QUADROTOR,
mavutil.mavlink.MAV_TYPE_VTOL_TILTROTOR,
]
# VTOL_DUOROTOR was renamed to VTOL_TAILSITTER_DUOROTOR
for possible_plane_type in "VTOL_DUOROTOR", "VTOL_TAILSITTER_DUOROTOR":
t = f"MAV_TYPE_{possible_plane_type}"
attr = getattr(mavutil.mavlink, t, None)
if attr is None:
continue
mav_type_planes.append(attr)
def master_msg_handling(self, m, master):
'''link message handling for an upstream link'''
# handle TIMESYNC messages from all mavlink nodes:
if m.get_type() == "TIMESYNC":
self.handle_TIMESYNC(m, master)
if not self.message_is_from_primary_vehicle(m):
# don't process messages not from our target
if m.get_type() == "BAD_DATA":
if self.mpstate.settings.shownoise and mavutil.all_printable(m.data):
out = m.data
if isinstance(m.data, bytearray):
out = m.data.decode('ascii')
self.mpstate.console.write(out, bg='red')
return
if self.settings.target_system != 0 and master.target_system != self.settings.target_system:
# keep the pymavlink level target system aligned with the MAVProxy setting
master.target_system = self.settings.target_system
if self.settings.target_component != 0 and master.target_component != self.settings.target_component:
# keep the pymavlink level target component aligned with the MAVProxy setting
print("change target_component %u" % self.settings.target_component)
master.target_component = self.settings.target_component
mtype = m.get_type()
if self.heartbeat_is_from_autopilot(m):
if self.settings.target_system == 0 and self.settings.target_system != m.get_srcSystem():
self.settings.target_system = m.get_srcSystem()
self.settings.target_component = m.get_srcComponent()
self.say("online system %u" % self.settings.target_system, 'message')
for mav in self.mpstate.mav_master:
mav.target_system = self.settings.target_system
mav.target_component = self.settings.target_component
if self.status.heartbeat_error:
self.status.heartbeat_error = False
self.say("heartbeat OK")
if master.linkerror:
master.linkerror = False
self.say("link %s OK" % (self.link_label(master)))
self.status.last_heartbeat = time.time()
master.last_heartbeat = self.status.last_heartbeat
armed = self.master.motors_armed()
if armed != self.status.armed:
self.status.armed = armed
if armed:
self.say("ARMED")
else:
self.say("DISARMED")
if master.flightmode != self.status.flightmode:
self.status.flightmode = master.flightmode
if self.mpstate.functions.input_handler is None:
self.set_prompt(self.status.flightmode + "> ")
if master.flightmode != self.status.last_mode_announced and time.time() > self.status.last_mode_announce + 2:
self.status.last_mode_announce = time.time()
self.status.last_mode_announced = master.flightmode
self.say("Mode " + self.status.flightmode)
if m.type in self.mav_type_planes:
self.mpstate.vehicle_type = 'plane'
self.mpstate.vehicle_name = 'ArduPlane'
elif m.type in [mavutil.mavlink.MAV_TYPE_GROUND_ROVER,
mavutil.mavlink.MAV_TYPE_SURFACE_BOAT]:
self.mpstate.vehicle_type = 'rover'
self.mpstate.vehicle_name = 'APMrover2'
elif m.type in [mavutil.mavlink.MAV_TYPE_SUBMARINE]:
self.mpstate.vehicle_type = 'sub'
self.mpstate.vehicle_name = 'ArduSub'
elif m.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_HELICOPTER,
mavutil.mavlink.MAV_TYPE_DODECAROTOR]:
self.mpstate.vehicle_type = 'copter'
self.mpstate.vehicle_name = 'ArduCopter'
elif m.type in [mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER]:
self.mpstate.vehicle_type = 'antenna'
self.mpstate.vehicle_name = 'AntennaTracker'
elif m.type in [mavutil.mavlink.MAV_TYPE_AIRSHIP]:
self.mpstate.vehicle_type = 'blimp'
self.mpstate.vehicle_name = 'Blimp'
elif mtype == 'STATUSTEXT':
class PendingText(object):
def __init__(self):
self.expected_count = None
self.severity = None
self.chunks = {}
self.start_time = time.time()
self.last_chunk_time = time.time()
def add_chunk(self, m): # m is a statustext message
self.severity = m.severity
self.last_chunk_time = time.time()
if hasattr(m, 'chunk_seq'):
# mavlink extensions are present.
chunk_seq = m.chunk_seq
mid = m.id
else:
# Note that m.id may still exist! It will
# contain the value 253, STATUSTEXT's mavlink
# message id. Thus our reliance on the
# presence of chunk_seq.
chunk_seq = 0
mid = 0
self.chunks[chunk_seq] = m.text
if len(m.text) != 50 or mid == 0:
self.expected_count = chunk_seq + 1
def complete(self):
return (self.expected_count is not None and
self.expected_count == len(self.chunks))
def accumulated_statustext(self):
next_expected_chunk = 0
out = ""
for chunk_seq in sorted(self.chunks.keys()):
if chunk_seq != next_expected_chunk:
out += " ... "
next_expected_chunk = chunk_seq
if isinstance(self.chunks[chunk_seq], str):
out += self.chunks[chunk_seq]
else:
out += self.chunks[chunk_seq].decode(errors="ignore")
next_expected_chunk += 1
return out
key = "%s.%s" % (m.get_srcSystem(), m.get_srcComponent())
if key not in self.status.statustexts_by_sysidcompid:
self.status.statustexts_by_sysidcompid[key] = {}
if hasattr(m, 'chunk_seq'):
mid = m.id
else:
# m.id will have the value of 253, STATUSTEXT mavlink id
mid = 0
if mid not in self.status.statustexts_by_sysidcompid[key]:
self.status.statustexts_by_sysidcompid[key][mid] = PendingText()
pending = self.status.statustexts_by_sysidcompid[key][mid]
pending.add_chunk(m)
if pending.complete():
# we have all of the chunks!
self.emit_accumulated_statustext(key, mid, pending)
elif mtype == "VFR_HUD":
have_gps_lock = False
if 'GPS_RAW' in self.status.msgs and self.status.msgs['GPS_RAW'].fix_type == 2:
have_gps_lock = True
elif 'GPS_RAW_INT' in self.status.msgs and self.status.msgs['GPS_RAW_INT'].fix_type == 3:
have_gps_lock = True
if have_gps_lock and not self.status.have_gps_lock and m.alt != 0:
self.say("GPS lock at %u meters" % m.alt, priority='notification')
self.status.have_gps_lock = True
elif mtype == "GPS_RAW":
if self.status.have_gps_lock:
if m.fix_type != 2 and not self.status.lost_gps_lock and (time.time() - self.status.last_gps_lock) > 3:
self.say("GPS fix lost")
self.status.lost_gps_lock = True
if m.fix_type == 2 and self.status.lost_gps_lock:
self.say("GPS OK")
self.status.lost_gps_lock = False
if m.fix_type == 2:
self.status.last_gps_lock = time.time()
elif mtype == "GPS_RAW_INT":
if self.status.have_gps_lock:
if m.fix_type < 3 and not self.status.lost_gps_lock and (time.time() - self.status.last_gps_lock) > 3:
self.say("GPS fix lost")
self.status.lost_gps_lock = True
if m.fix_type >= 3 and self.status.lost_gps_lock:
self.say("GPS OK")
self.status.lost_gps_lock = False
if m.fix_type >= 3:
self.status.last_gps_lock = time.time()
elif mtype == "NAV_CONTROLLER_OUTPUT" and self.status.flightmode == "AUTO" and self.mpstate.settings.distreadout:
rounded_dist = int(m.wp_dist/self.mpstate.settings.distreadout)*self.mpstate.settings.distreadout
if math.fabs(rounded_dist - self.status.last_distance_announce) >= self.mpstate.settings.distreadout:
if rounded_dist != 0:
self.say("%u" % rounded_dist, priority="progress")
self.status.last_distance_announce = rounded_dist
elif mtype == "GLOBAL_POSITION_INT":
self.report_altitude(m.relative_alt*0.001)
elif mtype == "COMPASSMOT_STATUS":
print(m)
elif mtype == "SIMSTATE":
self.mpstate.is_sitl = True
elif mtype == "ATTITUDE":
att_time = m.time_boot_ms * 0.001
self.mpstate.attitude_time_s = max(self.mpstate.attitude_time_s, att_time)
if self.mpstate.attitude_time_s - att_time > 120:
# cope with wrap
self.mpstate.attitude_time_s = att_time
elif mtype == "COMMAND_ACK":
try:
cmd = mavutil.mavlink.enums["MAV_CMD"][m.command].name
cmd = cmd[8:]
res = mavutil.mavlink.enums["MAV_RESULT"][m.result].name
res = res[11:]
if (m.target_component not in [mavutil.mavlink.MAV_COMP_ID_MAVCAN] and
m.command not in [mavutil.mavlink.MAV_CMD_GET_HOME_POSITION,
mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL]):
self.mpstate.console.writeln("Got COMMAND_ACK: %s: %s" % (cmd, res))
except Exception:
self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
if m.command == mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION:
if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED:
self.say("Calibrated")
elif m.result == mavutil.mavlink.MAV_RESULT_FAILED:
self.say("Calibration failed")
elif m.result == mavutil.mavlink.MAV_RESULT_UNSUPPORTED:
self.say("Calibration unsupported")
elif m.result == mavutil.mavlink.MAV_RESULT_IN_PROGRESS:
# don't bother the user with this
pass
elif m.result == mavutil.mavlink.MAV_RESULT_TEMPORARILY_REJECTED:
self.say("Calibration temporarily rejected")
else:
self.say("Calibration response (%u)" % m.result)
elif mtype == "MISSION_ACK":
try:
t = mavutil.mavlink.enums["MAV_MISSION_TYPE"][m.mission_type].name
t = t[12:]
res = mavutil.mavlink.enums["MAV_MISSION_RESULT"][m.type].name
res = res[12:]
self.mpstate.console.writeln("Got MISSION_ACK: %s: %s" % (t, res))
except Exception:
self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
else:
# self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
pass
self.check_watched_message(m, '<')
def handle_TIMESYNC(self, m, master):
'''handle received TIMESYNC message m from link master'''
# pass to any outstanding TimeSyncRequest objects:
for ot in self.outstanding_timesyncs:
ot.handle_TIMESYNC(m, master)
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def master_callback(self, m, master):
'''process mavlink message m on master, sending any messages to recipients'''
sysid = m.get_srcSystem()
mtype = m.get_type()
if mtype in ['HEARTBEAT', 'HIGH_LATENCY2'] and m.type != mavutil.mavlink.MAV_TYPE_GCS:
compid = m.get_srcComponent()
if sysid not in self.vehicle_list:
self.vehicle_list.add(sysid)
if (sysid, compid) not in self.mpstate.vehicle_link_map[master.linknum]:
self.mpstate.vehicle_link_map[master.linknum].add((sysid, compid))
print("Detected vehicle {0}:{1} on link {2}".format(sysid, compid, master.linknum))
# see if it is handled by a specialised sysid connection
if sysid in self.mpstate.sysid_outputs:
self.mpstate.sysid_outputs[sysid].write(m.get_msgbuf())
if mtype == "GLOBAL_POSITION_INT":
for modname in 'map', 'asterix', 'NMEA', 'NMEA2':
mod = self.module(modname)
if mod is not None:
mod.set_secondary_vehicle_position(m)
return
if getattr(m, '_timestamp', None) is None:
master.post_message(m)
self.status.counters['MasterIn'][master.linknum] += 1
if mtype == 'GLOBAL_POSITION_INT':
# send GLOBAL_POSITION_INT to 2nd GCS for 2nd vehicle display
for sysid in self.mpstate.sysid_outputs:
self.mpstate.sysid_outputs[sysid].write(m.get_msgbuf())
if self.mpstate.settings.fwdpos:
for link in self.mpstate.mav_master:
if link != master:
link.write(m.get_msgbuf())
# and log them
if mtype not in dataPackets and self.mpstate.logqueue:
# put link number in bottom 2 bits, so we can analyse packet
# delay in saved logs
usec = self.get_usec()
usec = (usec & ~3) | master.linknum
self.mpstate.logqueue.put(bytearray(struct.pack('>Q', usec) + m.get_msgbuf()))
# keep the last message of each type around
self.status.msgs[mtype] = m
instance_field = getattr(m, '_instance_field', None)
if mtype not in self.status.msg_count:
self.status.msg_count[mtype] = 0
self.status.msg_count[mtype] += 1
if instance_field is not None:
instance_value = getattr(m, instance_field, None)
if instance_value is not None:
mtype_instance = "%s[%s]" % (mtype, instance_value)
self.status.msgs[mtype_instance] = m
if mtype_instance not in self.status.msg_count:
self.status.msg_count[mtype_instance] = 0
self.status.msg_count[mtype_instance] += 1
if getattr(m, 'time_boot_ms', None) is not None and self.message_is_from_primary_vehicle(m):
# update link_delayed attribute
self.handle_msec_timestamp(m, master)
if mtype in activityPackets:
if master.linkerror:
master.linkerror = False
self.say("link %s OK" % (self.link_label(master)))
self.status.last_message = time.time()
master.last_message = self.status.last_message
if master.link_delayed and self.mpstate.settings.checkdelay:
# don't process delayed packets that cause double reporting
if mtype in delayedPackets:
return
self.master_msg_handling(m, master)
# don't pass along bad data
if mtype != 'BAD_DATA':
# pass messages along to listeners, except for REQUEST_DATA_STREAM, which
# would lead a conflict in stream rate setting between mavproxy and the other
# GCS
if self.mpstate.settings.mavfwd_rate or mtype != 'REQUEST_DATA_STREAM':
if mtype not in self.no_fwd_types:
for r in self.mpstate.mav_outputs:
r.write(m.get_msgbuf())
sysid = m.get_srcSystem()
target_sysid = self.target_system
# pass to modules
for (mod, pm) in self.mpstate.modules:
if not hasattr(mod, 'mavlink_packet'):
continue
# Do not send other-system-or-component heartbeat packets to non-multi-vehicle modules
if not self.message_is_from_primary_vehicle(m) and not mod.multi_vehicle and mtype == 'HEARTBEAT':
continue
# sysid 51/'3' is used by SiK radio for the injected RADIO/RADIO_STATUS mavlink frames.
# In order to be able to pass these to e.g. the graph module, which is not multi-vehicle,
# special handling is needed, so that the module gets both RADIO_STATUS and (single) target
# vehicle information.
if not (sysid == 51 and mtype in radioStatusPackets):
if not mod.multi_vehicle and sysid != target_sysid:
# only pass packets not from our target to modules that
# have marked themselves as being multi-vehicle capable
continue
try:
mod.mavlink_packet(m)
except Exception as msg:
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(msg)
def cmd_vehicle(self, args):
'''handle vehicle commands'''
if len(args) < 1:
print("Usage: vehicle SYSID[:COMPID]")
return
a = args[0].split(':')
self.mpstate.settings.target_system = int(a[0])
if len(a) > 1:
self.mpstate.settings.target_component = int(a[1])
# change default link based on most recent HEARTBEAT
best_link = 0
best_timestamp = 0
for i in range(len(self.mpstate.mav_master)):
m = self.mpstate.mav_master[i]
m.target_system = self.mpstate.settings.target_system
m.target_component = self.mpstate.settings.target_component
if 'HEARTBEAT' in m.messages:
stamp = m.messages['HEARTBEAT']._timestamp
# src_system = m.messages['HEARTBEAT'].get_srcSystem()
if stamp > best_timestamp:
best_link = i
best_timestamp = stamp
m.link_delayed = False
self.mpstate.settings.link = best_link + 1
print("Set vehicle %s (link %u)" % (args[0], best_link+1))
class TimeSyncRequest():
'''send and receive TIMESYNC mavlink messages, printing results'''
def __init__(self, master, max_attempts=1, console=None):
self.attempts_remaining = max_attempts
self.last_sent_ns = 0
self.sent_on_timestamps = []
self.mav = master
self.max_lifetime = 20 # seconds
self.response_received = False
self.console = console
def age_limit_exceeded(self):
'''true if this object should be reaped'''
if len(self.sent_on_timestamps) == 0:
return False
return int(time.time() * 1e9) - self.sent_on_timestamps[0] > self.max_lifetime*1e9
def update(self):
'''send timesync requests at intervals'''
now_ns = int(time.time() * 1e9)
if now_ns - self.last_sent_ns < 1e9: # ping at 1s intervals
return
if self.attempts_remaining == 0:
return
self.attempts_remaining -= 1
self.last_sent_ns = now_ns
# encode outbound link in bottom 4 bits
now_ns = now_ns & ~ 0b1111
now_ns = now_ns | self.mav.linknum
self.sent_on_timestamps.append(now_ns)
self.mav.mav.timesync_send(0, now_ns)
def handle_TIMESYNC(self, m, master):
'''handle TIMESYNC message m received on link master'''
if m.ts1 not in self.sent_on_timestamps:
# we didn't send this one
return
now_ns = time.time() * 1e9
out_link = m.ts1 & 0b1111 # out link encoded in bottom four bits
if self.console is not None:
self.console.writeln(f"ping response: {(now_ns-m.ts1)*1e-6:.3f}ms from={m.get_srcSystem()}/{m.get_srcComponent()} in-link={master.linknum} out-link={out_link}") # noqa
def cmd_ping(self, args):
'''create TimeSyncRequest objects to ping on each link'''
for m in self.mpstate.mav_master:
request = LinkModule.TimeSyncRequest(m, console=self.console)
self.outstanding_timesyncs.append(request)
|
class LinkModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def idle_task(self):
'''called on idle'''
pass
def complete_serial_ports(self, text):
'''return list of serial ports'''
pass
def complete_hl(self, text):
'''return list of hl options'''
pass
def complete_dl(self, text):
'''return list of datarate_logging options'''
pass
def complete_links(self, text):
'''return list of links'''
pass
def cmd_link(self, args):
'''handle link commands'''
pass
def cmd_dl(self, args):
'''Toggle datarate logging'''
pass
def cmd_hl(self, args):
'''Toggle high latency mode'''
pass
def show_link(self):
'''show link information'''
pass
def reset_link_stats(self):
'''reset link statistics'''
pass
def cmd_alllinks(self, args):
'''send command on all links'''
pass
def cmd_link_list(self):
'''list links'''
pass
def parse_link_attributes(self, some_json):
'''return a dict based on some_json (empty if json invalid)'''
pass
def parse_link_descriptor(self, descriptor):
'''parse e.g. 'udpin:127.0.0.1:9877:{"foo":"bar"}' into
python structure ("udpin:127.0.0.1:9877", {"foo":"bar"})'''
pass
def apply_link_attributes(self, conn, optional_attributes):
pass
def link_add(self, descriptor, force_connected=False, retries=3):
'''add new link'''
pass
def cmd_link_add(self, args):
'''add new link'''
pass
def link_attributes(self, link, attributes):
pass
def cmd_link_attributes(self, args):
'''change optional link attributes'''
pass
def cmd_link_ports(self):
'''show available ports'''
pass
def find_link(self, device):
'''find a device based on number, name or label'''
pass
def cmd_link_remove(self, args):
'''remove an link'''
pass
def get_usec(self):
'''time since 1970 in microseconds'''
pass
def dump_message_verbose(self, m):
'''return verbose dump of m. Wraps the pymavlink routine which
inconveniently takes a filehandle'''
pass
def check_watched_message(self, m, direction_string):
'''if we are watching a message, print it out'''
pass
def master_send_callback(self, m, master):
'''called on sending a message'''
pass
def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
pass
def colors_for_severity(self, severity):
pass
def report_altitude(self, altitude):
'''possibly report a new altitude'''
pass
def emit_accumulated_statustext(self, key, id, pending):
pass
def heartbeat_is_from_autopilot(self, m):
'''returns true if m is a HEARTBEAT (or HIGH_LATENCY2) message and
looks like it is from an actual autopilot rather than from e.g. a
mavlink-connected camera'''
pass
def master_msg_handling(self, m, master):
'''link message handling for an upstream link'''
pass
class PendingText(object):
def __init__(self, mpstate):
pass
def add_chunk(self, m):
pass
def complete_serial_ports(self, text):
pass
def accumulated_statustext(self):
pass
def handle_TIMESYNC(self, m, master):
'''handle received TIMESYNC message m from link master'''
pass
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
pass
def master_callback(self, m, master):
'''process mavlink message m on master, sending any messages to recipients'''
pass
def cmd_vehicle(self, args):
'''handle vehicle commands'''
pass
class TimeSyncRequest():
'''send and receive TIMESYNC mavlink messages, printing results'''
def __init__(self, mpstate):
pass
def age_limit_exceeded(self):
'''true if this object should be reaped'''
pass
def update(self):
'''send timesync requests at intervals'''
pass
def handle_TIMESYNC(self, m, master):
'''handle TIMESYNC message m received on link master'''
pass
def cmd_ping(self, args):
'''create TimeSyncRequest objects to ping on each link'''
pass
| 49 | 37 | 23 | 1 | 19 | 3 | 5 | 0.17 | 1 | 17 | 6 | 0 | 38 | 13 | 38 | 76 | 1,096 | 110 | 875 | 208 | 824 | 150 | 705 | 201 | 654 | 62 | 2 | 6 | 249 |
7,028 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/__init__.py
|
MAVProxy.modules.mavproxy_magical.MagicalModule
|
class MagicalModule(mp_module.MPModule):
def __init__(self, mpstate):
super(MagicalModule, self).__init__(mpstate, 'magical')
self.add_command(
'magical_ui',
self.cmd_magical_ui,
'open the GUI for compass calibration',
)
self.mpstate = mpstate
self.parent_pipe, self.child_pipe = multiproc.Pipe()
self.ui_process = None
self.progress_msgs = {}
self.report_msgs = {}
self.attitude_msg = None
self.raw_imu_msg = None
self.running = False
self.last_ui_msgs = {}
def start_ui(self):
if self.ui_is_active():
return
self.ui_process = multiproc.Process(target=self.ui_task)
self.update_ui()
self.ui_process.start()
def stop_ui(self):
if not self.ui_is_active():
return
self.parent_pipe.send(dict(name='close'))
self.ui_process.join(2)
if self.ui_process.is_alive():
print("magical: UI process timed out, killing it", file=sys.stderr)
self.kill_ui()
def kill_ui(self):
self.ui_process.terminate()
self.parent_pipe, self.child_pipe = multiproc.Pipe()
def ui_task(self):
mp_util.child_close_fds()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.mavproxy_magical.magical_ui import MagicalFrame
app = wx.App(False)
app.frame = MagicalFrame(self.child_pipe)
app.frame.Show()
app.MainLoop()
def process_ui_commands(self):
while self.parent_pipe.poll():
cmd = self.parent_pipe.recv()
if cmd == 'start':
self.mpstate.functions.process_stdin('magcal start')
elif cmd == 'cancel':
self.mpstate.functions.process_stdin('magcal cancel')
def ui_is_active(self):
return self.ui_process is not None and self.ui_process.is_alive()
def idle_task(self):
self.process_ui_commands()
if self.ui_is_active():
self.update_ui()
elif self.last_ui_msgs:
self.last_ui_msgs = {}
def cmd_magical_ui(self, args):
self.start_ui()
def mavlink_packet(self, m):
t = m.get_type()
if t == 'MAG_CAL_PROGRESS':
self.progress_msgs[m.compass_id] = m
if m.compass_id in self.report_msgs:
del self.report_msgs[m.compass_id]
if 'report' in self.last_ui_msgs:
del self.last_ui_msgs['report']
self.running = True
elif t == 'MAG_CAL_REPORT':
self.report_msgs[m.compass_id] = m
if self.report_msgs and len(self.report_msgs) == len(self.progress_msgs):
self.running = False
elif t == 'ATTITUDE':
self.attitude_msg = m
elif t == 'RAW_IMU':
self.raw_imu_msg = m
elif t == 'COMMAND_ACK':
if m.command == mavutil.mavlink.MAV_CMD_DO_CANCEL_MAG_CAL:
self.running = False
def unload(self):
self.stop_ui()
def send_ui_msg(self, m):
send = False
if m['name'] not in self.last_ui_msgs:
send = True
else:
last = self.last_ui_msgs[m['name']]
if m['name'] == 'report':
if len(m['messages']) != len(last['messages']):
send = True
else:
for a, b in zip(m['messages'], last['messages']):
if a.compass_id != b.compass_id:
send = True
break
else:
send = m != last
if not send:
return
self.parent_pipe.send(m)
self.last_ui_msgs[m['name']] = m
def update_ui(self):
self.send_ui_msg(dict(
name='ui_is_active',
value=self.ui_is_active(),
))
if self.progress_msgs:
pct = min(p.completion_pct for p in self.progress_msgs.values())
masks = [~0] * 10
for p in self.progress_msgs.values():
for i in range(10):
masks[i] &= p.completion_mask[i]
visible = [bool(m & 1 << j) for m in masks for j in range(8)]
self.send_ui_msg(dict(
name='progress_update',
pct=pct,
sections=visible,
))
if self.report_msgs and len(self.report_msgs) == len(self.progress_msgs):
keys = sorted(self.progress_msgs.keys())
self.send_ui_msg(dict(
name='report',
messages=[self.report_msgs[k] for k in keys],
))
if self.attitude_msg:
self.send_ui_msg(dict(
name='attitude',
roll=self.attitude_msg.roll,
pitch=self.attitude_msg.pitch,
yaw=self.attitude_msg.yaw,
timestamp=self.attitude_msg.time_boot_ms,
))
if self.raw_imu_msg:
self.send_ui_msg(dict(
name='mag',
x=self.raw_imu_msg.xmag,
y=self.raw_imu_msg.ymag,
z=self.raw_imu_msg.zmag,
))
self.send_ui_msg(dict(
name='running',
value=self.running,
))
|
class MagicalModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def start_ui(self):
pass
def stop_ui(self):
pass
def kill_ui(self):
pass
def ui_task(self):
pass
def process_ui_commands(self):
pass
def ui_is_active(self):
pass
def idle_task(self):
pass
def cmd_magical_ui(self, args):
pass
def mavlink_packet(self, m):
pass
def unload(self):
pass
def send_ui_msg(self, m):
pass
def update_ui(self):
pass
| 14 | 0 | 12 | 1 | 11 | 0 | 3 | 0 | 1 | 6 | 1 | 0 | 13 | 10 | 13 | 51 | 171 | 27 | 144 | 37 | 127 | 0 | 107 | 37 | 90 | 10 | 2 | 5 | 42 |
7,029 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/glrenderer.py
|
MAVProxy.modules.mavproxy_magical.glrenderer.Renderer
|
class Renderer(object):
'''
Base class for rendering 3D opengl objects in Magical UI. It preforms
common routines for the renderers used. The method render() should perform
the rendering routine. The default implementation only does basic setup and
can be called from the subclass.
'''
def __init__(self, background):
glClearColor(*background)
self.program = opengl.Program()
self.program.compile_and_link()
self.program.use_light(opengl.Light(
position=Vector3(-2.0, 0.0, -1.0),
ambient=Vector3(0.8, 0.8, 0.8),
diffuse=Vector3(0.5, 0.5, 0.5),
specular=Vector3(0.25, 0.25, 0.25),
att_linear=0.000,
att_quad=0.000,
))
self.camera = opengl.Camera()
# Adjust camera to show NED coordinates properly
self.camera.base = (
Vector3( 0, 1, 0),
Vector3( 0, 0,-1),
Vector3(-1, 0, 0),
)
self.camera.position = Vector3(-100.0, 0, 0)
near = -self.camera.position.x - 1.0
far = near + 2.0
self.projection = opengl.Orthographic(near=near, far=far)
self.program.use_projection(self.projection)
def set_viewport(self, viewport):
glViewport(*viewport)
def render(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.program.use_camera(self.camera)
|
class Renderer(object):
'''
Base class for rendering 3D opengl objects in Magical UI. It preforms
common routines for the renderers used. The method render() should perform
the rendering routine. The default implementation only does basic setup and
can be called from the subclass.
'''
def __init__(self, background):
pass
def set_viewport(self, viewport):
pass
def render(self):
pass
| 4 | 1 | 11 | 1 | 9 | 0 | 1 | 0.24 | 1 | 4 | 4 | 2 | 3 | 3 | 3 | 3 | 42 | 6 | 29 | 9 | 25 | 7 | 18 | 9 | 14 | 1 | 1 | 0 | 3 |
7,030 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
|
MAVProxy.modules.mavproxy_magical.magical_ui.Button
|
class Button(wx.PyControl):
def __init__(self, *k, **kw):
if 'style' not in kw:
kw['style'] = wx.BORDER_NONE
super(Button, self).__init__(*k, **kw)
self.border_radius = 0
self.border_width = 0
self.border_color = None
self.padding = wx.Size(0, 0)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
def OnLeftUp(self, evt):
command_evt = wx.CommandEvent(wx.EVT_BUTTON.typeId, self.GetId())
command_evt.SetEventObject(self)
self.GetEventHandler().AddPendingEvent(command_evt);
def GetBorderRadius(self):
return self.border_radius
def SetBorderRadius(self, radius):
self.border_radius = radius
def GetBorderWidth(self):
return self.border_width
def SetBorderWidth(self, width):
self.border_width = width
def GetBorderColor(self):
if not self.border_color:
return self.GetBackgroundColour()
return self.border_color
def SetBorderColor(self, color):
self.border_color = color
def GetPadding(self):
return self.padding
def SetPadding(self, size):
self.padding = size
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
self.Draw(dc)
def Draw(self, dc):
width, height = self.GetClientSize()
if not width or not height:
return
gcdc = wx.GCDC(dc)
gcdc.SetPen(wx.NullPen)
bg = self.GetParent().GetBackgroundColour()
gcdc.SetBackground(wx.Brush(bg, wx.SOLID))
gcdc.Clear()
border_radius = self.GetBorderRadius()
border = self.GetBorderWidth()
if border:
gcdc.SetBrush(wx.Brush(self.GetBorderColor()))
gcdc.DrawRoundedRectangle(0, 0, width, height, border_radius)
w, h = width - 2 * border, height - 2 * border
border_radius -= border
gcdc.SetBrush(wx.Brush(self.GetBackgroundColour()))
gcdc.DrawRoundedRectangle(border, border, w, h, border_radius)
dc.SetFont(self.GetFont())
label = self.GetLabel()
w, h = dc.GetTextExtent(label)
x, y = (width - w) / 2, (height - h) / 2
dc.DrawText(label, x, y)
def DoGetBestSize(self):
dc = wx.ClientDC(self)
dc.SetFont(self.GetFont())
w, h = dc.GetTextExtent(self.GetLabel())
pw, ph = self.GetPadding()
w, h = w + pw, h + ph
border = self.GetBorderWidth()
w, h = w + 2 * border, h + 2 * border
return wx.Size(w, h)
|
class Button(wx.PyControl):
def __init__(self, *k, **kw):
pass
def OnLeftUp(self, evt):
pass
def GetBorderRadius(self):
pass
def SetBorderRadius(self, radius):
pass
def GetBorderWidth(self):
pass
def SetBorderWidth(self, width):
pass
def GetBorderColor(self):
pass
def SetBorderColor(self, color):
pass
def GetPadding(self):
pass
def SetPadding(self, size):
pass
def OnPaint(self, evt):
pass
def Draw(self, dc):
pass
def DoGetBestSize(self):
pass
| 14 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 13 | 4 | 13 | 13 | 92 | 23 | 69 | 32 | 55 | 0 | 69 | 32 | 55 | 3 | 1 | 1 | 17 |
7,031 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
|
MAVProxy.modules.mavproxy_magical.magical_ui.CountdownText
|
class CountdownText(wx.PyWindow):
def __init__(self, *k, **kw):
super(CountdownText, self).__init__(*k, **kw)
self.value = 0
self.border_color = COMMON_FOREGROUND
self.Bind(wx.EVT_PAINT, self.OnPaint)
def ShouldInheritColours(self):
return True
def GetBorderColor(self):
return self.border_color
def SetBorderColor(self, color):
self.border_color = color
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
self.Draw(dc)
def Draw(self, dc):
width, height = self.GetClientSize()
if not width or not height:
return
gcdc = wx.GCDC(dc)
bg = self.GetParent().GetBackgroundColour()
gcdc.SetBackground(wx.Brush(bg, wx.SOLID))
gcdc.Clear()
x, y = width / 2, height / 2
radius = min(x, y)
border = int(radius / 20)
gcdc.SetPen(wx.Pen(self.GetBorderColor(), border))
gcdc.SetBrush(wx.Brush(bg, wx.SOLID))
gcdc.DrawCircle(x, y, radius - border)
# Set font size 70% of the diameter
v = str(self.value)
s = max(dc.GetTextExtent(v))
scale = 2 * radius * .7 / s
font = self.GetFont()
font.SetPointSize(round(font.GetPointSize() * scale))
dc.SetFont(font)
w, h = dc.GetTextExtent(v)
x, y = (width - w) / 2, (height - h) / 2
dc.DrawText(v, x, y)
def SetValue(self, value):
self.value = value
self.Refresh()
|
class CountdownText(wx.PyWindow):
def __init__(self, *k, **kw):
pass
def ShouldInheritColours(self):
pass
def GetBorderColor(self):
pass
def SetBorderColor(self, color):
pass
def OnPaint(self, evt):
pass
def Draw(self, dc):
pass
def SetValue(self, value):
pass
| 8 | 0 | 7 | 1 | 6 | 0 | 1 | 0.02 | 1 | 3 | 0 | 0 | 7 | 2 | 7 | 7 | 55 | 13 | 41 | 22 | 33 | 1 | 41 | 22 | 33 | 2 | 1 | 1 | 8 |
7,032 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
|
MAVProxy.modules.mavproxy_magical.magical_ui.InstructionText
|
class InstructionText(wx.PyWindow):
def __init__(self, *k, **kw):
super(InstructionText, self).__init__(*k, **kw)
self.text = ''
self.min_lines = 1
self.Bind(wx.EVT_PAINT, self.OnPaint)
def ShouldInheritColours(self):
return True
def SetText(self, text):
self.text = text
self.Refresh()
def SetMinLines(self, lines):
self.min_lines = lines
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
self.Draw(dc)
def Draw(self, dc):
width, height = self.GetClientSize()
if not width or not height:
return
bg = self.GetParent().GetBackgroundColour()
dc.SetBackground(wx.Brush(bg, wx.SOLID))
dc.Clear()
dc.SetFont(self.GetFont())
text = wordwrap(self.text, width, dc)
lines = text.splitlines()
_, h = dc.GetTextExtent(text)
y = (height - h) / 2
for line in lines:
w, h = dc.GetTextExtent(line)
x = (width - w) / 2
dc.DrawText(line, x, y)
y += h
def DoGetBestSize(self):
_, height = self.GetClientSize()
dc = wx.ClientDC(self)
dc.SetFont(self.GetFont())
_, h = dc.GetTextExtent('\n'.join([' '] * self.min_lines))
return -1, max(h, height)
|
class InstructionText(wx.PyWindow):
def __init__(self, *k, **kw):
pass
def ShouldInheritColours(self):
pass
def SetText(self, text):
pass
def SetMinLines(self, lines):
pass
def OnPaint(self, evt):
pass
def Draw(self, dc):
pass
def DoGetBestSize(self):
pass
| 8 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 7 | 2 | 7 | 7 | 49 | 10 | 39 | 23 | 31 | 0 | 39 | 23 | 31 | 3 | 1 | 1 | 9 |
7,033 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/camera_projection.py
|
MAVProxy.modules.lib.camera_projection.CameraProjection
|
class CameraProjection:
def __init__(self, C, elevation_model=None, terrain_source="SRTM3"):
self.C = C
self.elevation_model = elevation_model
if elevation_model is None:
self.elevation_model = mp_elevation.ElevationModel(database=terrain_source)
def pixel_position_flat(self, xpos, ypos, height_agl, roll_deg, pitch_deg, yaw_deg):
'''
find the NED offset on the ground in meters of a pixel in a ground image
given height above the ground in meters, and pitch/roll/yaw in degrees, the
lens and image parameters
The xpos,ypos is from the top-left of the image
The height_agl is in meters above ground level. Flat earth below camera is assumed
The yaw is from grid north. Positive yaw is clockwise
The roll is from horiznotal. Positive roll is down on the right
The pitch is from horiznotal. Positive pitch is up in the front, -90 is straight down
return result is a tuple, with meters north, east and down of current GPS position
'''
xfer = uavxfer()
xfer.setCameraMatrix(self.C.K)
xfer.setCameraOrientation( 0.0, 0.0, pi/2 )
xfer.setFlatEarth(0);
xfer.setPlatformPose(0, 0, -height_agl, math.radians(roll_deg), math.radians(pitch_deg+90), math.radians(yaw_deg))
# compute the undistorted points for the ideal camera matrix
src = numpy.zeros((1,1,2), numpy.float32)
src[0,0] = (xpos, ypos)
R = eye(3)
K = self.C.K
D = self.C.D
dst = cv2.undistortPoints(src, K, D, R, K)
x = dst[0,0][0]
y = dst[0,0][1]
# negative scale means camera pointing above horizon
# large scale means a long way away also unreliable
(pos_w, scale) = xfer.imageToWorld(x, y)
if scale < 0:
return None
ret = Vector3(pos_w[0], pos_w[1], height_agl)
return ret
def get_posned(self, x, y, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''
get a Vector3() NED from the camera position to project onto the ground
return pos NED from camera as Vector3 or None
'''
# get height of terrain below camera
theight = self.elevation_model.GetElevation(clat, clon)
if calt_amsl <= theight:
return None
# project with flat earth
pos_ned = self.pixel_position_flat(x, y, calt_amsl-theight, roll_deg, pitch_deg, yaw_deg)
if pos_ned is None or pos_ned.z <= 0:
return None
# iterate to make more accurate, accounting for difference in terrain height at this point
latlon = mp_util.gps_offset(clat, clon, pos_ned.y, pos_ned.x)
for i in range(3):
ground_alt = self.elevation_model.GetElevation(latlon[0], latlon[1])
if ground_alt is None:
return None
sr = pos_ned.length()
if sr <= 1:
return None
posd2 = calt_amsl - ground_alt
sin_pitch = pos_ned.z / sr
# adjust for height at this point
sr2 = sr - (pos_ned.z - posd2) / sin_pitch
#print("SR: ", pos_ned.z, posd2, sr, sr2)
pos_ned = pos_ned * (sr2 / sr)
latlon = mp_util.gps_offset(clat, clon, pos_ned.y, pos_ned.x)
if latlon is None:
return None
return pos_ned
def get_latlonalt_for_pixel(self, x, y, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''
get lat,lon of projected pixel from camera.
x,y are pixel coordinates, 0,0 is top-left corner
return is (lat,lon,alt) tuple or None
'''
pos_ned = self.get_posned(x, y, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg)
if pos_ned is None or pos_ned.z <= 0:
return None
latlon = mp_util.gps_offset(clat, clon, pos_ned.y, pos_ned.x)
if latlon is None:
return None
return (latlon[0], latlon[1], calt_amsl-pos_ned.z)
def get_slantrange(self, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''
get slant range to ground for a pixel in the middle of the camera view
return is slant range in meters or None
'''
pos_ned = self.get_posned(self.C.xresolution//2, self.C.yresolution//2, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg)
if pos_ned is None:
return None
return pos_ned.length()
def get_projection(self, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''return a list of (lat,lon) tuples drawing the camera view on the terrain'''
ret = []
xres = self.C.xresolution
yres = self.C.yresolution
for (x,y) in [(0,0), (xres, 0), (xres, yres), (0,yres)]:
y0 = 0
while True:
latlonalt = self.get_latlonalt_for_pixel(x,y+y0,clat,clon,calt_amsl,roll_deg,pitch_deg,yaw_deg)
if latlonalt is not None:
break
# chop off the top 10 pixels and try again
y0 += 10
if y0 >= self.C.yresolution:
# give up
return None
ret.append((latlonalt[0],latlonalt[1]))
ret.append(ret[0])
return ret
|
class CameraProjection:
def __init__(self, C, elevation_model=None, terrain_source="SRTM3"):
pass
def pixel_position_flat(self, xpos, ypos, height_agl, roll_deg, pitch_deg, yaw_deg):
'''
find the NED offset on the ground in meters of a pixel in a ground image
given height above the ground in meters, and pitch/roll/yaw in degrees, the
lens and image parameters
The xpos,ypos is from the top-left of the image
The height_agl is in meters above ground level. Flat earth below camera is assumed
The yaw is from grid north. Positive yaw is clockwise
The roll is from horiznotal. Positive roll is down on the right
The pitch is from horiznotal. Positive pitch is up in the front, -90 is straight down
return result is a tuple, with meters north, east and down of current GPS position
'''
pass
def get_posned(self, x, y, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''
get a Vector3() NED from the camera position to project onto the ground
return pos NED from camera as Vector3 or None
'''
pass
def get_latlonalt_for_pixel(self, x, y, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''
get lat,lon of projected pixel from camera.
x,y are pixel coordinates, 0,0 is top-left corner
return is (lat,lon,alt) tuple or None
'''
pass
def get_slantrange(self, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''
get slant range to ground for a pixel in the middle of the camera view
return is slant range in meters or None
'''
pass
def get_projection(self, clat, clon, calt_amsl, roll_deg, pitch_deg, yaw_deg):
'''return a list of (lat,lon) tuples drawing the camera view on the terrain'''
pass
| 7 | 5 | 21 | 2 | 13 | 6 | 4 | 0.45 | 0 | 3 | 2 | 0 | 6 | 2 | 6 | 6 | 129 | 17 | 77 | 37 | 70 | 35 | 77 | 37 | 70 | 7 | 0 | 3 | 21 |
7,034 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/camera_projection.py
|
MAVProxy.modules.lib.camera_projection.CameraParams
|
class CameraParams:
'''
object representing camera parameters. Can be initialised from basic parameters for idealised lens or use fromfile() to loa
from a calibration file
'''
def __init__(self, lens=None, sensorwidth=None, xresolution=None, yresolution=None, K=None, D=None, FOV=None):
if xresolution is None:
raise ValueError("xresolution required")
if yresolution is None:
raise ValueError("yresolution required")
if lens is None and FOV is not None:
# FOV = 2 arctan(xres/(2f))
if sensorwidth is None:
# default to 5mm sensor width for FOV calculation
sensorwidth=5.0 # mm
# FOV = 2 arctan( sensorwidth/(2f))
lens = 0.5 * sensorwidth / math.tan(math.radians(FOV)*0.5)
if lens is None:
raise ValueError("Lens required")
if sensorwidth is None:
raise ValueError("sensorwidth required")
self.version = 0
self.sensorwidth = sensorwidth
self.lens = lens
self.K = K
self.D = D
self.set_resolution(xresolution, yresolution)
self.FOV = FOV
if FOV is None:
self.FOV = math.degrees(2*math.atan(sensorwidth/(2*lens)))
def set_resolution(self, xresolution, yresolution):
'''set camera resolution'''
self.xresolution = xresolution
self.yresolution = yresolution
# compute focal length in pixels
f_p = xresolution * self.lens / self.sensorwidth
if self.K is None:
self.K = array([[f_p, 0.0, xresolution/2],[0.0, f_p, yresolution/2], [0.0,0.0,1.0]])
if self.D is None:
self.D = array([[0.0, 0.0, 0.0, 0.0, 0.0]])
def __repr__(self):
return json.dumps(self.todict(),indent=2)
def setParams(self, K, D):
self.K = array(K)
self.D = array(D)
def todict(self):
data = {}
data['version'] = self.version
data['lens'] = self.lens
data['sensorwidth'] = self.sensorwidth
data['xresolution'] = self.xresolution
data['yresolution'] = self.yresolution
if self.K is not None:
data['K'] = self.K.tolist()
print("Set K to " + str(self.K))
print("Set K to " + str(data['K']))
if self.D is not None:
data['D'] = self.D.tolist()
return data
@staticmethod
def fromdict(data):
if data['version'] != 0:
raise Exception('version %d of camera params unsupported' % (self.version))
try:
K = array(data['K'])
D = array(data['D'])
except KeyError:
K = None
D = None
ret = CameraParams(lens=data['lens'],
sensorwidth=data['sensorwidth'],
xresolution=data['xresolution'],
yresolution=data['yresolution'],
K=K,
D=D)
ret.version = data['version']
return ret;
@staticmethod
def fromstring(strung):
dic = json.loads(str(strung))
return CameraParams.fromdict(dic)
def save(self, filename):
f = open(filename,"w")
# dump json form
f.write(str(self)+"\n")
f.close()
@staticmethod
def fromfile(filename):
f = open(filename,"r")
# dump json form
d = f.read(65535)
f.close()
return CameraParams.fromstring(d)
|
class CameraParams:
'''
object representing camera parameters. Can be initialised from basic parameters for idealised lens or use fromfile() to loa
from a calibration file
'''
def __init__(self, lens=None, sensorwidth=None, xresolution=None, yresolution=None, K=None, D=None, FOV=None):
pass
def set_resolution(self, xresolution, yresolution):
'''set camera resolution'''
pass
def __repr__(self):
pass
def setParams(self, K, D):
pass
def todict(self):
pass
@staticmethod
def fromdict(data):
pass
@staticmethod
def fromstring(strung):
pass
def save(self, filename):
pass
@staticmethod
def fromfile(filename):
pass
| 13 | 2 | 10 | 0 | 9 | 1 | 2 | 0.15 | 0 | 4 | 0 | 0 | 6 | 8 | 9 | 9 | 103 | 10 | 82 | 30 | 69 | 12 | 74 | 27 | 64 | 8 | 0 | 2 | 22 |
7,035 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/wxversion.py
|
MAVProxy.modules.lib.MacOS.wxversion._wxPackageInfo
|
class _wxPackageInfo(object):
def __init__(self, pathname, stripFirst=False):
self.pathname = pathname
base = os.path.basename(pathname)
segments = base.split('-')
if stripFirst:
segments = segments[1:]
self.version = tuple([int(x) for x in segments[0].split('.')])
self.options = segments[1:]
def Score(self, other, optionsRequired):
score = 0
# whatever number of version components given in other must
# match exactly
minlen = min(len(self.version), len(other.version))
if self.version[:minlen] != other.version[:minlen]:
return 0
score += 1
# check for matching options, if optionsRequired then the
# options are not optional ;-)
for opt in other.options:
if opt in self.options:
score += 1
elif optionsRequired:
return 0
return score
def CheckOptions(self, other, optionsRequired):
# if options are not required then this always succeeds
if not optionsRequired:
return True
# otherwise, if we have any option not present in other, then
# the match fails.
for opt in self.options:
if opt not in other.options:
return False
return True
def __lt__(self, other):
return self.version < other.version or \
(self.version == other.version and self.options < other.options)
def __le__(self, other):
return self.version <= other.version or \
(self.version == other.version and self.options <= other.options)
def __gt__(self, other):
return self.version > other.version or \
(self.version == other.version and self.options > other.options)
def __ge__(self, other):
return self.version >= other.version or \
(self.version == other.version and self.options >= other.options)
def __eq__(self, other):
return self.version == other.version and self.options == other.options
|
class _wxPackageInfo(object):
def __init__(self, pathname, stripFirst=False):
pass
def Score(self, other, optionsRequired):
pass
def CheckOptions(self, other, optionsRequired):
pass
def __lt__(self, other):
pass
def __le__(self, other):
pass
def __gt__(self, other):
pass
def __ge__(self, other):
pass
def __eq__(self, other):
pass
| 9 | 0 | 6 | 0 | 5 | 1 | 2 | 0.17 | 1 | 2 | 0 | 0 | 8 | 3 | 8 | 8 | 61 | 12 | 42 | 18 | 33 | 7 | 37 | 18 | 28 | 5 | 1 | 2 | 16 |
7,036 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/wxversion.py
|
MAVProxy.modules.lib.MacOS.wxversion.AlreadyImportedError
|
class AlreadyImportedError(VersionError):
pass
|
class AlreadyImportedError(VersionError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
7,037 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wxagg.py
|
MAVProxy.modules.lib.MacOS.backend_wxagg.FigureFrameWxAgg
|
class FigureFrameWxAgg(FigureFrameWx):
def get_canvas(self, fig):
return FigureCanvasWxAgg(self, -1, fig)
def _get_toolbar(self, statbar):
if matplotlib.rcParams['toolbar']=='classic':
toolbar = NavigationToolbar2Wx(self.canvas, True)
elif matplotlib.rcParams['toolbar']=='toolbar2':
toolbar = NavigationToolbar2WxAgg(self.canvas)
toolbar.set_status_bar(statbar)
else:
toolbar = None
return toolbar
|
class FigureFrameWxAgg(FigureFrameWx):
def get_canvas(self, fig):
pass
def _get_toolbar(self, statbar):
pass
| 3 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 2 | 13 | 1 | 12 | 4 | 9 | 0 | 10 | 4 | 7 | 3 | 1 | 1 | 4 |
7,038 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.fake_stderr
|
class fake_stderr:
"""Wx does strange things with stderr, as it makes the assumption that there
is probably no console. This redirects stderr to the console, since we know
that there is one!"""
def write(self, msg):
print("Stderr: %s\n\r" % msg)
|
class fake_stderr:
'''Wx does strange things with stderr, as it makes the assumption that there
is probably no console. This redirects stderr to the console, since we know
that there is one!'''
def write(self, msg):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 6 | 0 | 3 | 2 | 1 | 3 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
7,039 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.TimerWx
|
class TimerWx(TimerBase):
'''
Subclass of :class:`backend_bases.TimerBase` that uses WxTimer events.
Attributes:
* interval: The time between timer events in milliseconds. Default
is 1000 ms.
* single_shot: Boolean flag indicating whether this timer should
operate as single shot (run once and then stop). Defaults to False.
* callbacks: Stores list of (func, args) tuples that will be called
upon timer events. This list can be manipulated directly, or the
functions add_callback and remove_callback can be used.
'''
def __init__(self, parent, *args, **kwargs):
TimerBase.__init__(self, *args, **kwargs)
# Create a new timer and connect the timer event to our handler.
# For WX, the events have to use a widget for binding.
self.parent = parent
self._timer = wx.Timer(self.parent, wx.NewId())
self.parent.Bind(wx.EVT_TIMER, self._on_timer, self._timer)
# Unbinding causes Wx to stop for some reason. Disabling for now.
# def __del__(self):
# TimerBase.__del__(self)
# self.parent.Bind(wx.EVT_TIMER, None, self._timer)
def _timer_start(self):
self._timer.Start(self._interval, self._single)
def _timer_stop(self):
self._timer.Stop()
def _timer_set_interval(self):
self._timer_start()
def _timer_set_single_shot(self):
self._timer.start()
def _on_timer(self, *args):
TimerBase._on_timer(self)
|
class TimerWx(TimerBase):
'''
Subclass of :class:`backend_bases.TimerBase` that uses WxTimer events.
Attributes:
* interval: The time between timer events in milliseconds. Default
is 1000 ms.
* single_shot: Boolean flag indicating whether this timer should
operate as single shot (run once and then stop). Defaults to False.
* callbacks: Stores list of (func, args) tuples that will be called
upon timer events. This list can be manipulated directly, or the
functions add_callback and remove_callback can be used.
'''
def __init__(self, parent, *args, **kwargs):
pass
def _timer_start(self):
pass
def _timer_stop(self):
pass
def _timer_set_interval(self):
pass
def _timer_set_single_shot(self):
pass
def _on_timer(self, *args):
pass
| 7 | 1 | 3 | 0 | 3 | 0 | 1 | 1.06 | 1 | 0 | 0 | 0 | 6 | 2 | 6 | 6 | 41 | 8 | 16 | 9 | 9 | 17 | 16 | 9 | 9 | 1 | 1 | 0 | 6 |
7,040 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.SubplotToolWX
|
class SubplotToolWX(wx.Frame):
def __init__(self, targetfig):
wx.Frame.__init__(self, None, -1, "Configure subplots")
toolfig = Figure((6,3))
canvas = FigureCanvasWx(self, -1, toolfig)
# Create a figure manager to manage things
figmgr = FigureManager(canvas, 1, self)
# Now put all into a sizer
sizer = wx.BoxSizer(wx.VERTICAL)
# This way of adding to sizer allows resizing
sizer.Add(canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
self.SetSizer(sizer)
self.Fit()
tool = SubplotTool(targetfig, toolfig)
|
class SubplotToolWX(wx.Frame):
def __init__(self, targetfig):
pass
| 2 | 0 | 16 | 3 | 10 | 3 | 1 | 0.27 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 17 | 3 | 11 | 7 | 9 | 3 | 11 | 7 | 9 | 1 | 1 | 0 | 1 |
7,041 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
|
MAVProxy.modules.lib.MacOS.backend_wx.StatusBarWx
|
class StatusBarWx(wx.StatusBar):
"""
A status bar is added to _FigureFrame to allow measurements and the
previously selected scroll function to be displayed as a user
convenience.
"""
def __init__(self, parent):
wx.StatusBar.__init__(self, parent, -1)
self.SetFieldsCount(2)
self.SetStatusText("None", 1)
#self.SetStatusText("Measurement: None", 2)
#self.Reposition()
def set_function(self, string):
self.SetStatusText("%s" % string, 1)
|
class StatusBarWx(wx.StatusBar):
'''
A status bar is added to _FigureFrame to allow measurements and the
previously selected scroll function to be displayed as a user
convenience.
'''
def __init__(self, parent):
pass
def set_function(self, string):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 15 | 1 | 7 | 3 | 4 | 7 | 7 | 3 | 4 | 1 | 1 | 0 | 2 |
7,042 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_log.py
|
MAVProxy.modules.mavproxy_log.LogModule
|
class LogModule(mp_module.MPModule):
def __init__(self, mpstate):
super(LogModule, self).__init__(mpstate, "log", "log transfer")
self.add_command('log', self.cmd_log, "log file handling", ['<download|status|erase|resume|cancel|list>'])
self.reset()
def reset(self):
self.download_set = set()
self.download_file = None
self.download_lognum = None
self.download_filename = None
self.download_start = None
self.download_last_timestamp = None
self.download_ofs = 0
self.retries = 0
self.entries = {}
self.download_queue = []
self.last_status = time.time()
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'LOG_ENTRY':
self.handle_log_entry(m)
elif m.get_type() == 'LOG_DATA':
self.handle_log_data(m)
def handle_log_entry(self, m):
'''handling incoming log entry'''
if m.time_utc == 0:
tstring = ''
else:
tstring = time.ctime(m.time_utc)
if m.num_logs == 0:
print("No logs")
return
self.entries[m.id] = m
print("Log %u numLogs %u lastLog %u size %u %s" % (m.id, m.num_logs, m.last_log_num, m.size, tstring))
def handle_log_data(self, m):
'''handling incoming log data'''
if self.download_file is None:
return
# lose some data
# import random
# if random.uniform(0,1) < 0.05:
# print('dropping ', str(m))
# return
if m.ofs != self.download_ofs:
self.download_file.seek(m.ofs)
self.download_ofs = m.ofs
if m.count != 0:
s = bytearray(m.data[:m.count])
self.download_file.write(s)
self.download_set.add(m.ofs // 90)
self.download_ofs += m.count
self.download_last_timestamp = time.time()
if m.count == 0 or (m.count < 90 and len(self.download_set) == 1 + (m.ofs // 90)):
dt = time.time() - self.download_start
self.download_file.close()
size = os.path.getsize(self.download_filename)
speed = size / (1000.0 * dt)
status = "Finished downloading %s (%u bytes %u seconds, %.1f kbyte/sec %u retries)" % (self.download_filename,
size,
dt, speed,
self.retries)
self.console.set_status('LogDownload',status, row=4)
print(status)
self.download_file = None
self.download_filename = None
self.download_set = set()
self.master.mav.log_request_end_send(self.target_system,
self.target_component)
if len(self.download_queue):
self.log_download_next()
self.update_status()
def handle_log_data_missing(self):
'''handling missing incoming log data'''
if len(self.download_set) == 0:
return
highest = max(self.download_set)
diff = set(range(highest)).difference(self.download_set)
if len(diff) == 0:
self.master.mav.log_request_data_send(self.target_system,
self.target_component,
self.download_lognum, (1 + highest) * 90, 0xffffffff)
self.retries += 1
else:
num_requests = 0
while num_requests < 20:
start = min(diff)
diff.remove(start)
end = start
while end + 1 in diff:
end += 1
diff.remove(end)
self.master.mav.log_request_data_send(self.target_system,
self.target_component,
self.download_lognum, start * 90, (end + 1 - start) * 90)
num_requests += 1
self.retries += 1
if len(diff) == 0:
break
def log_status(self, console=False):
'''show download status'''
if self.download_filename is None:
print("No download")
return
dt = time.time() - self.download_start
speed = os.path.getsize(self.download_filename) / (1000.0 * dt)
m = self.entries.get(self.download_lognum, None)
file_size = os.path.getsize(self.download_filename)
if m is None:
size = 0
pct = 0
elif m.size == 0:
size = 0
pct = 100
else:
size = m.size
pct = (100.0*file_size)/size
highest = 0
if len(self.download_set):
highest = max(self.download_set)
diff = set(range(highest)).difference(self.download_set)
status = "Downloading %s - %u/%u bytes %.1f%% %.1f kbyte/s (%u retries %u missing)" % (self.download_filename,
os.path.getsize(self.download_filename),
size,
pct,
speed,
self.retries,
len(diff))
if console:
self.console.set_status('LogDownload', status, row=4)
else:
print(status)
def log_download_next(self):
if len(self.download_queue) == 0:
return
latest = self.download_queue.pop()
filename = self.default_log_filename(latest)
if os.path.isfile(filename) and os.path.getsize(filename) == self.entries.get(latest).to_dict()["size"]:
print("Skipping existing %s" % (filename))
self.log_download_next()
else:
self.log_download(latest, filename)
def log_download_all(self):
if len(self.entries.keys()) == 0:
print("Please use log list first")
return
self.download_queue = sorted(self.entries, key=lambda id: self.entries[id].time_utc)
self.log_download_next()
def log_download_range(self, first, last):
self.download_queue = sorted(list(range(first,last+1)),reverse=True)
print(self.download_queue)
self.log_download_next()
def log_download_from(self,fromnum = 0):
if len(self.entries.keys()) == 0:
print("Please use log list first")
return
self.download_queue = sorted(self.entries, key=lambda id: self.entries[id].time_utc)
self.download_queue = self.download_queue[fromnum:len(self.download_queue)]
self.log_download_next()
def log_download(self, log_num, filename):
'''download a log file'''
print("Downloading log %u as %s" % (log_num, filename))
self.download_lognum = log_num
self.download_file = open(filename, "wb")
self.master.mav.log_request_data_send(self.target_system,
self.target_component,
log_num, 0, 0xFFFFFFFF)
self.download_filename = filename
self.download_set = set()
self.download_start = time.time()
self.download_last_timestamp = time.time()
self.download_ofs = 0
self.retries = 0
def default_log_filename(self, log_num):
return "log%u.bin" % log_num
def cmd_log(self, args):
'''log commands'''
usage = "usage: log <list|download|erase|resume|status|cancel>"
if len(args) < 1:
print(usage)
return
if args[0] == "status":
self.log_status()
elif args[0] == "list":
print("Requesting log list")
self.download_set = set()
self.master.mav.log_request_list_send(self.target_system,
self.target_component,
0, 0xffff)
elif args[0] == "erase":
self.master.mav.log_erase_send(self.target_system,
self.target_component)
elif args[0] == "resume":
self.master.mav.log_request_end_send(self.target_system,
self.target_component)
elif args[0] == "cancel":
if self.download_file is not None:
self.download_file.close()
self.reset()
elif args[0] == "download":
if len(args) < 2:
print("usage: log download all | log download <lognumber> <filename> | log download from <lognumber>|log download range FIRST LAST")
return
if args[1] == 'all':
self.log_download_all()
return
if args[1] == 'from':
if len(args) < 2:
args[2] == 0
self.log_download_from(int(args[2]))
return
if args[1] == 'range':
if len(args) < 2:
print("Usage: log download range FIRST LAST")
return
self.log_download_range(int(args[2]), int(args[3]))
return
if args[1] == 'latest':
if len(self.entries.keys()) == 0:
print("Please use log list first")
return
log_num = sorted(self.entries, key=lambda id: self.entries[id].time_utc)[-1]
else:
log_num = int(args[1])
if len(args) > 2:
filename = args[2]
else:
filename = self.default_log_filename(log_num)
self.log_download(log_num, filename)
else:
print(usage)
def update_status(self):
'''update log download status in console'''
now = time.time()
if self.download_file is not None and now - self.last_status > 0.5:
self.last_status = now
self.log_status(True)
def idle_task(self):
'''handle missing log data'''
if self.download_last_timestamp is not None and time.time() - self.download_last_timestamp > 0.7:
self.download_last_timestamp = time.time()
self.handle_log_data_missing()
self.update_status()
|
class LogModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def reset(self):
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def handle_log_entry(self, m):
'''handling incoming log entry'''
pass
def handle_log_data(self, m):
'''handling incoming log data'''
pass
def handle_log_data_missing(self):
'''handling missing incoming log data'''
pass
def log_status(self, console=False):
'''show download status'''
pass
def log_download_next(self):
pass
def log_download_all(self):
pass
def log_download_range(self, first, last):
pass
def log_download_from(self,fromnum = 0):
pass
def log_download_next(self):
'''download a log file'''
pass
def default_log_filename(self, log_num):
pass
def cmd_log(self, args):
'''log commands'''
pass
def update_status(self):
'''update log download status in console'''
pass
def idle_task(self):
'''handle missing log data'''
pass
| 17 | 9 | 15 | 0 | 14 | 1 | 4 | 0.06 | 1 | 6 | 0 | 0 | 16 | 11 | 16 | 54 | 265 | 23 | 228 | 54 | 211 | 14 | 193 | 54 | 176 | 18 | 2 | 3 | 58 |
7,043 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
|
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipCircle
|
class SlipCircle(SlipObject):
'''a circle to display on the map'''
def __init__(self, key, layer, latlon, radius, color, linewidth, arrow = False, popup_menu=None, start_angle=None, end_angle=None, rotation=None, add_radii=False):
SlipObject.__init__(self, key, layer, popup_menu=popup_menu)
self.latlon = latlon
if radius < 0:
self.reverse = True
else:
self.reverse = False
self.radius = abs(float(radius))
self.color = color
self.linewidth = linewidth
self.arrow = arrow
self.start_angle = start_angle
self.end_angle = end_angle
self.rotation = rotation
self.add_radii = add_radii
def draw(self, img, pixmapper, bounds):
if self.hidden:
return
center_px = pixmapper(self.latlon)
# figure out pixels per meter
ref_pt = (self.latlon[0] + 1.0, self.latlon[1])
dis = mp_util.gps_distance(self.latlon[0], self.latlon[1], ref_pt[0], ref_pt[1])
ref_px = pixmapper(ref_pt)
dis_px = math.sqrt(float(center_px[1] - ref_px[1]) ** 2.0)
pixels_per_meter = dis_px / dis
radius_px = int(self.radius * pixels_per_meter)
if self.start_angle is not None:
axes = (radius_px, radius_px)
cv2.ellipse(img, center_px, axes, self.rotation, self.start_angle, self.end_angle, self.color, self.linewidth)
if self.add_radii:
rimpoint1 = (center_px[0] + int(radius_px * math.cos(math.radians(self.rotation+self.start_angle))),
center_px[1] + int(radius_px * math.sin(math.radians(self.rotation+self.start_angle))))
rimpoint2 = (center_px[0] + int(radius_px * math.cos(math.radians(self.rotation+self.end_angle))),
center_px[1] + int(radius_px * math.sin(math.radians(self.rotation+self.end_angle))))
cv2.line(img, center_px, rimpoint1, self.color, self.linewidth)
cv2.line(img, center_px, rimpoint2, self.color, self.linewidth)
else:
cv2.circle(img, center_px, radius_px, self.color, self.linewidth)
if self.arrow:
SlipArrow(self.key, self.layer, (center_px[0]-radius_px, center_px[1]),
self.color, self.linewidth, 0, reverse = self.reverse).draw(img)
SlipArrow(self.key, self.layer, (center_px[0]+radius_px, center_px[1]),
self.color, self.linewidth, math.pi, reverse = self.reverse).draw(img)
# stash some values for determining closest click location
self.radius_px = radius_px
self.center_px = center_px
def bounds(self):
'''return bounding box'''
if self.hidden:
return None
return (self.latlon[0], self.latlon[1], 0, 0)
def clicked(self, px, py):
'''check if a click on px,py should be considered a click
on the object. Return None if definitely not a click,
otherwise return the distance of the click, smaller being nearer
'''
radius_px = getattr(self, "radius_px", None)
if radius_px is None:
return
dx = self.center_px[0] - px
dy = self.center_px[1] - py
ret = abs(math.sqrt(dx*dx+dy*dy) - radius_px)
if ret > 10: # threshold of within 10 pixels for a click to count
return None
return ret
|
class SlipCircle(SlipObject):
'''a circle to display on the map'''
def __init__(self, key, layer, latlon, radius, color, linewidth, arrow = False, popup_menu=None, start_angle=None, end_angle=None, rotation=None, add_radii=False):
pass
def draw(self, img, pixmapper, bounds):
pass
def bounds(self):
'''return bounding box'''
pass
def clicked(self, px, py):
'''check if a click on px,py should be considered a click
on the object. Return None if definitely not a click,
otherwise return the distance of the click, smaller being nearer
'''
pass
| 5 | 3 | 17 | 0 | 15 | 2 | 3 | 0.15 | 1 | 3 | 1 | 0 | 4 | 14 | 4 | 13 | 71 | 4 | 59 | 32 | 54 | 9 | 53 | 31 | 48 | 5 | 1 | 2 | 12 |
7,044 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
|
MAVProxy.modules.lib.mp_image.MPImageVideo
|
class MPImageVideo:
'''request getting image feed from video file'''
def __init__(self, filename):
self.filename = filename
|
class MPImageVideo:
'''request getting image feed from video file'''
def __init__(self, filename):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 3 | 3 | 1 | 1 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
7,045 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_instructor.py
|
MAVProxy.modules.lib.mp_instructor.InstructorFrame
|
class InstructorFrame(wx.Frame):
""" The main frame of the console"""
def __init__(self, gui_pipe, state, title):
self.state = state
self.gui_pipe = gui_pipe
wx.Frame.__init__(self, None, title=title, size=(500, 650), style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
self.panel = wx.Panel(self)
self.nb = wx.Choicebook(self.panel, wx.ID_ANY)
# create the tabs
self.createWidgets()
# assign events to the buttons on the tabs
self.createActions()
# add in the pipe from MAVProxy
self.timer = wx.Timer(self)
# self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
# self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.Bind(wx.EVT_TIMER, lambda evt, notebook=self.nb: self.on_timer(evt, notebook), self.timer)
self.timer.Start(100)
# finally, put the notebook in a sizer for the panel to manage
# the layout
sizer = wx.BoxSizer()
sizer.Add(self.nb, 1, wx.EXPAND)
self.panel.SetSizer(sizer)
self.Show(True)
self.pending = []
# create controls on form - labels, buttons, etc
def createWidgets(self):
# create the panels for the tabs
PanelCommon = wx.Panel(self.nb)
boxCommon = wx.BoxSizer(wx.VERTICAL)
PanelCommon.SetAutoLayout(True)
PanelCommon.SetSizer(boxCommon)
PanelCommon.Layout()
PanelPlane = wx.Panel(self.nb)
boxPlane = wx.BoxSizer(wx.VERTICAL)
PanelPlane.SetAutoLayout(True)
PanelPlane.SetSizer(boxPlane)
PanelPlane.Layout()
PanelCopter = wx.Panel(self.nb)
boxCopter = wx.BoxSizer(wx.VERTICAL)
PanelCopter.SetAutoLayout(True)
PanelCopter.SetSizer(boxCopter)
PanelCopter.Layout()
# add the data to the individual tabs
'Common failures'
self.Dis_GNSS_Fix_Checkbox = wx.CheckBox(PanelCommon, wx.ID_ANY, "Disable GNSS FIX")
boxCommon.Add(self.Dis_GNSS_Fix_Checkbox)
boxCommon.Add(wx.StaticLine(PanelCommon, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10)
boxCommon.Add(wx.StaticText(PanelCommon, wx.ID_ANY, 'Voltage drop rate mv/s:', wx.DefaultPosition, wx.DefaultSize, style=wx.ALIGN_RIGHT))
self.VoltageSlider = wx.Slider(PanelCommon, wx.ID_ANY, 100, 10, 200, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxCommon.Add(self.VoltageSlider)
self.Voltage_Drop_Checkbox = wx.CheckBox(PanelCommon, wx.ID_ANY, "Voltage dropping")
boxCommon.Add(self.Voltage_Drop_Checkbox)
boxCommon.Add(wx.StaticLine(PanelCommon, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10)
self.FailsafeButton = wx.Button(PanelCommon, wx.ID_ANY, "Trigger FailSafe")
boxCommon.Add(self.FailsafeButton)
boxCommon.Add(wx.StaticLine(PanelCommon, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10)
self.GCS_Comm_Loss_Checkbox = wx.CheckBox(PanelCommon, wx.ID_ANY, "GCS Comm loss")
# disCheckbox.Enable(False)
boxCommon.Add(self.GCS_Comm_Loss_Checkbox)
boxCommon.Add(wx.StaticLine(PanelCommon, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10)
boxCommon.Add(wx.StaticText(PanelCommon, wx.ID_ANY, 'Wind Direction:', wx.DefaultPosition, wx.DefaultSize,style=wx.ALIGN_RIGHT))
self.Wind_Dir_Slider = wx.Slider(PanelCommon, wx.ID_ANY, 0, 0, 359, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxCommon.Add(self.Wind_Dir_Slider)
boxCommon.Add(wx.StaticText(PanelCommon, wx.ID_ANY, 'Wind Velocity (m/s):', wx.DefaultPosition, wx.DefaultSize,style=wx.ALIGN_RIGHT))
self.Wind_Vel_Slider = wx.Slider(PanelCommon, wx.ID_ANY, 0, 0, 50, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxCommon.Add(self.Wind_Vel_Slider)
boxCommon.Add(wx.StaticText(PanelCommon, wx.ID_ANY, 'Turbulence:', wx.DefaultPosition, wx.DefaultSize,
style=wx.ALIGN_RIGHT))
self.Wind_Turb_Slider = wx.Slider(PanelCommon, wx.ID_ANY, 0, 0, 10, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxCommon.Add(self.Wind_Turb_Slider)
'Plane specific failures'
self.Pitot_Fail_Low_Checkbox = wx.CheckBox(PanelPlane, wx.ID_ANY, "Pitot stuck at no speed")
boxPlane.Add(self.Pitot_Fail_Low_Checkbox)
self.Pitot_Fail_High_Checkbox = wx.CheckBox(PanelPlane, wx.ID_ANY, "Pitot stuck at high speed")
boxPlane.Add(self.Pitot_Fail_High_Checkbox)
self.Arspd_Offset_Slider = wx.Slider(PanelPlane, wx.ID_ANY, 2013, 1500, 2500, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxPlane.Add(self.Arspd_Offset_Slider)
boxPlane.Add(wx.StaticLine(PanelPlane, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10)
boxPlane.Add(wx.StaticText(PanelPlane, wx.ID_ANY, 'Thrust reduction:', wx.DefaultPosition, wx.DefaultSize,
style=wx.ALIGN_RIGHT))
self.Plane_Thrust_Slider = wx.Slider(PanelPlane, wx.ID_ANY, 0, 0, 1000, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxPlane.Add(self.Plane_Thrust_Slider)
boxPlane.Add(wx.StaticText(PanelPlane, wx.ID_ANY, 'Thrust reduction + current increase:', wx.DefaultPosition, wx.DefaultSize,
style=wx.ALIGN_RIGHT))
self.Plane_Thrust_Curr_Slider = wx.Slider(PanelPlane, wx.ID_ANY, 0, 0, 1000, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxPlane.Add(self.Plane_Thrust_Curr_Slider)
'Copter specific failures'
boxCopter.Add(wx.StaticText(PanelCopter, wx.ID_ANY, 'Thrust reduction:', wx.DefaultPosition, wx.DefaultSize, style=wx.ALIGN_RIGHT))
self.Copter_Thrust_Slider = wx.Slider(PanelCopter, wx.ID_ANY, 0, 0, 400, wx.DefaultPosition, (250, -1),
wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
boxCopter.Add(self.Copter_Thrust_Slider)
boxCopter.Add(wx.StaticLine(PanelCopter, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 10)
self.CopterResetButton = wx.Button(PanelCopter, wx.ID_ANY, "Reset Parameters")
boxCopter.Add(self.CopterResetButton)
# and add in the tabs
self.nb.AddPage(PanelCommon, "Common (Copter/Plane) Failures")
self.nb.AddPage(PanelPlane, "Plane specific Failures")
self.nb.AddPage(PanelCopter, "Copter specific Failures")
# Create the actions for the buttons
def createActions(self):
# Common tab:
self.Bind(wx.EVT_CHECKBOX, self.dis_gnss, self.Dis_GNSS_Fix_Checkbox)
#self.Bind(wx.EVT_CHECKBOX, self.sendevent("Voltage", 20), self.Voltage_Drop_Checkbox) # WHY trigged once?
self.Bind(wx.EVT_CHECKBOX, self.volt_drop, self.Voltage_Drop_Checkbox)
self.Bind(wx.EVT_CHECKBOX, self.gcs_comm_loss, self.GCS_Comm_Loss_Checkbox)
self.Bind(wx.EVT_SCROLL_CHANGED, self.volt_drop_rate, self.VoltageSlider)
self.Bind(wx.EVT_BUTTON, self.setmode, self.FailsafeButton)
self.Bind(wx.EVT_SCROLL_CHANGED, self.wind_dir, self.Wind_Dir_Slider)
self.Bind(wx.EVT_SCROLL_CHANGED, self.wind_vel, self.Wind_Vel_Slider)
self.Bind(wx.EVT_SCROLL_CHANGED, self.wind_turbulence, self.Wind_Turb_Slider)
# Plane tab:
self.Bind(wx.EVT_CHECKBOX, self.pitot_fail_low, self.Pitot_Fail_Low_Checkbox)
self.Bind(wx.EVT_CHECKBOX, self.pitot_fail_high, self.Pitot_Fail_High_Checkbox)
self.Bind(wx.EVT_SCROLL_CHANGED, self.arspd_offset, self.Arspd_Offset_Slider)
self.Bind(wx.EVT_SCROLL_CHANGED, self.plane_thrust_loss, self.Plane_Thrust_Slider)
self.Bind(wx.EVT_SCROLL_CHANGED, self.plane_thrust_loss_curr, self.Plane_Thrust_Curr_Slider)
# Copter tab:
self.Bind(wx.EVT_SCROLL_CHANGED, self.copter_thrust_loss, self.Copter_Thrust_Slider)
self.Bind(wx.EVT_BUTTON, self.copter_reset, self.CopterResetButton)
# Common actions
def dis_gnss(self, event):
self.gui_pipe.send(["dis_gnss", self.Dis_GNSS_Fix_Checkbox.Value])
def volt_drop_rate(self, event):
self.gui_pipe.send(["volt_drop_rate", self.VoltageSlider.Value / 1000])
def volt_drop(self, event):
self.gui_pipe.send(["volt_drop", self.Voltage_Drop_Checkbox.Value])
def gcs_comm_loss(self, event):
self.gui_pipe.send(["gcs_comm_loss", self.GCS_Comm_Loss_Checkbox.Value])
def setmode(self, event):
self.gui_pipe.send(["setmode", 10])
def on_gnss_Button_ok(self, event):
self.gui_pipe.send("ok")
def wind_dir(self, event):
self.gui_pipe.send(["wind_dir", self.Wind_Dir_Slider.Value])
def wind_vel(self, event):
self.gui_pipe.send(["wind_vel", self.Wind_Vel_Slider.Value])
def wind_turbulence(self, event):
self.gui_pipe.send(["wind_turbulence", self.Wind_Turb_Slider.Value])
# Plane actions
def pitot_fail_low(self, event):
self.gui_pipe.send(["pitot_fail_low", self.Pitot_Fail_Low_Checkbox.Value])
def pitot_fail_high(self, event):
self.gui_pipe.send(["pitot_fail_high", self.Pitot_Fail_High_Checkbox.Value])
def arspd_offset(self, event):
self.gui_pipe.send(["arspd_offset", self.Arspd_Offset_Slider.Value])
def plane_thrust_loss(self, event):
self.gui_pipe.send(["plane_thrust_loss", self.Plane_Thrust_Slider.Value])
def plane_thrust_loss_curr(self, event):
self.gui_pipe.send(["plane_thrust_loss_curr", self.Plane_Thrust_Curr_Slider.Value])
# Copter actions
def copter_thrust_loss(self, event):
self.gui_pipe.send(["copter_thrust_loss", self.Copter_Thrust_Slider.Value])
def copter_reset (self, event):
self.gui_pipe.send(["copter_reset", 0])
def sendevent(self, event, text, value=0):
self.gui_pipe.send([text, value])
#do a final check of the current panel and move to the next
def on_Button( self, event):
win = (event.GetEventObject()).GetParent()
for widget in win.GetChildren():
if type(widget) is wx.CheckBox and widget.IsChecked() == 0:
dlg = wx.MessageDialog(win, "Not all items checked", "Error", wx.OK | wx.ICON_WARNING)
dlg.ShowModal()
dlg.Destroy()
return
# all checked, go to next panel.
win.GetParent().AdvanceSelection()
# Receive messages from MAVProxy module and process them
def on_timer(self, event, notebook):
state = self.state
win = notebook.GetPage(notebook.GetSelection())
if state.close_event.wait(0.001):
self.timer.Stop()
self.Destroy()
return
while state.gui_pipe.poll():
obj = state.gui_pipe.recv()
if isinstance(obj, CheckboxItemState):
# go through each item in the current tab and (un)check as needed
# print(obj.name + ", " + str(obj.state))
for widget in win.GetChildren():
if type(widget) is wx.CheckBox and widget.GetLabel() == obj.name:
widget.SetValue(obj.state)
|
class InstructorFrame(wx.Frame):
''' The main frame of the console'''
def __init__(self, gui_pipe, state, title):
pass
def createWidgets(self):
pass
def createActions(self):
pass
def dis_gnss(self, event):
pass
def volt_drop_rate(self, event):
pass
def volt_drop_rate(self, event):
pass
def gcs_comm_loss(self, event):
pass
def setmode(self, event):
pass
def on_gnss_Button_ok(self, event):
pass
def wind_dir(self, event):
pass
def wind_vel(self, event):
pass
def wind_turbulence(self, event):
pass
def pitot_fail_low(self, event):
pass
def pitot_fail_high(self, event):
pass
def arspd_offset(self, event):
pass
def plane_thrust_loss(self, event):
pass
def plane_thrust_loss_curr(self, event):
pass
def copter_thrust_loss(self, event):
pass
def copter_reset (self, event):
pass
def sendevent(self, event, text, value=0):
pass
def on_Button( self, event):
pass
def on_timer(self, event, notebook):
pass
| 23 | 1 | 10 | 2 | 7 | 1 | 1 | 0.18 | 1 | 2 | 1 | 0 | 22 | 21 | 22 | 22 | 266 | 75 | 162 | 58 | 139 | 29 | 151 | 58 | 128 | 6 | 1 | 4 | 29 |
7,046 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wavefront.py
|
MAVProxy.modules.lib.wavefront.ObjParser
|
class ObjParser(Parser):
def reset(self):
self.ignored_directives = set()
self.current_mtl = Mtl()
self.mtl_map = {}
def new_target(self):
return Obj()
def parse_line(self, line, obj):
def parse_vertex_data_ref(v):
if not v:
return 0
try:
v = int(v)
except ValueError:
raise Exception("vertex data references must be integers")
if not v:
raise Exception("vertex data references can not be zero")
return v
split = line.split()
directive = split[0]
args = split[1:]
n = len(args)
if directive == 'v':
if n == 3:
x, y, z = args
w = 1.0
elif n == 4:
x, y, z, w = args
else:
raise Exception("wrong number of arguments for directive v")
try:
obj.vertices.append((float(x), float(y), float(z), float(w)))
except ValueError:
raise Exception("arguments for directive v must be floating point numbers")
elif directive == 'vn':
if n == 3:
x, y, z = args
else:
raise Exception("wrong number of arguments for directive vn")
try:
obj.normals.append((float(x), float(y), float(z)))
except ValueError:
raise Exception("arguments for directive vn must be floating point numbers")
elif directive == 'f':
if n < 3:
raise Exception("directive f requires at least 3 vertices")
vertex_data = []
for s in args:
s = s.split('/')
if len(s) != 3:
raise Exception("invalid number of references")
v, t, n = s
v = parse_vertex_data_ref(v)
t = parse_vertex_data_ref(t)
n = parse_vertex_data_ref(n)
# TODO: address illegal statements like "f 1//1 2/2/2"
vertex_data.append((v, t, n))
obj.faces.append((vertex_data, self.current_mtl))
elif directive == 'mtllib':
if n < 1:
raise Exception("wrong number of arguments for directive mtllib")
d = os.path.dirname(self.filename)
for filename in args:
parser = MtlParser(filename=os.path.join(d, filename))
l = parser.parse()
self.deps += parser.deps
for mtl in l:
if mtl.name in self.mtl_map:
continue
self.mtl_map[mtl.name] = mtl
elif directive == 'usemtl':
if n != 1:
raise Exception("wrong number of arguments for directive usemtl")
name = args[0]
if name not in self.mtl_map:
raise Exception("material %s not found" % name)
if name not in obj.materials:
obj.materials[name] = self.mtl_map[name]
self.current_mtl = obj.materials[name]
else:
self.ignored_directives.add(directive)
|
class ObjParser(Parser):
def reset(self):
pass
def new_target(self):
pass
def parse_line(self, line, obj):
pass
def parse_vertex_data_ref(v):
pass
| 5 | 0 | 23 | 0 | 22 | 0 | 7 | 0.01 | 1 | 8 | 3 | 0 | 3 | 3 | 3 | 10 | 84 | 3 | 80 | 23 | 75 | 1 | 72 | 23 | 67 | 21 | 2 | 4 | 27 |
7,047 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wavefront.py
|
MAVProxy.modules.lib.wavefront.Obj
|
class Obj:
def __init__(self):
self.vertices = []
self.normals = []
self.faces = []
self.materials = {}
|
class Obj:
def __init__(self):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 4 | 1 | 1 | 6 | 0 | 6 | 6 | 4 | 0 | 6 | 6 | 4 | 1 | 0 | 0 | 1 |
7,048 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_DGPS.py
|
MAVProxy.modules.mavproxy_DGPS.DGPSModule
|
class DGPSModule(mp_module.MPModule):
def __init__(self, mpstate):
super(DGPSModule, self).__init__(mpstate, "DGPS", "DGPS injection support for SBP/RTCP/UBC")
self.portnum = 13320
self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.port.bind(("127.0.0.1", self.portnum))
mavutil.set_close_on_exec(self.port.fileno())
self.port.setblocking(0)
self.inject_seq_nr = 0
print("DGPS: Listening for RTCM packets on UDP://%s:%s" % ("127.0.0.1", self.portnum))
def send_rtcm_msg(self, data):
msglen = 180;
if (len(data) > msglen * 4):
print("DGPS: Message too large", len(data))
return
# How many messages will we send?
msgs = 0
if (len(data) % msglen == 0):
msgs = len(data) // msglen
else:
msgs = (len(data) // msglen) + 1
for a in range(0, msgs):
flags = 0
# Set the fragment flag if we're sending more than 1 packet.
if (msgs) > 1:
flags = 1
# Set the ID of this fragment
flags |= (a & 0x3) << 1
# Set an overall sequence number
flags |= (self.inject_seq_nr & 0x1f) << 3
amount = min(len(data) - a * msglen, msglen)
datachunk = data[a*msglen : a*msglen + amount]
self.master.mav.gps_rtcm_data_send(
flags,
len(datachunk),
bytearray(datachunk.ljust(180, b'\0')))
# Send a terminal 0-length message if we sent 2 or 3 exactly-full messages.
if (msgs < 4) and (len(data) % msglen == 0) and (len(data) > msglen):
flags = 1 | (msgs & 0x3) << 1 | (self.inject_seq_nr & 0x1f) << 3
self.master.mav.gps_rtcm_data_send(
flags,
0,
bytearray("".ljust(180, '\0')))
self.inject_seq_nr += 1
def idle_task(self):
'''called in idle time'''
try:
data = self.port.recv(1024) # Attempt to read up to 1024 bytes.
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return
raise
try:
self.send_rtcm_msg(data)
except Exception as e:
print("DGPS: GPS Inject Failed:", e)
|
class DGPSModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def send_rtcm_msg(self, data):
pass
def idle_task(self):
'''called in idle time'''
pass
| 4 | 1 | 23 | 4 | 17 | 2 | 4 | 0.14 | 1 | 5 | 0 | 0 | 3 | 3 | 3 | 41 | 74 | 17 | 51 | 15 | 47 | 7 | 44 | 14 | 40 | 6 | 2 | 2 | 11 |
7,049 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wavefront.py
|
MAVProxy.modules.lib.wavefront.MtlParser
|
class MtlParser(Parser):
def reset(self):
self.current_mtl = None
self.ignored_directives = set()
def new_target(self):
return []
def parse_line(self, line, mtl_list):
def rgb():
try:
if n == 1:
r = float(args[0])
g = r
b = r
elif n == 3:
r, g, b = float(args[0]), float(args[1]), float(args[2])
else:
raise Exception("wrong number of arguments for directive %s" % directive)
except ValueError:
raise Exception("arguments for directive %s must be floating point numbers" % directive)
else:
return r, g, b
def ignore_unsupported_color_statement():
if n > 0 and args[0] in ('spectral', 'xyz'):
self.ignored_directives.add('%s %s' % (directive, arg[0]))
return True
return False
split = line.split()
directive = split[0]
args = split[1:]
n = len(args)
if directive == 'newmtl':
if n != 1:
raise Exception("wrong number of arguments to directive newmtl")
self.current_mtl = Mtl()
self.current_mtl.name = args[0]
mtl_list.append(self.current_mtl)
else:
if not self.current_mtl:
raise Exception("create a new material with newmtl before any other statement")
if directive == 'Ka':
if ignore_unsupported_color_statement():
return
self.current_mtl.Ka = rgb()
elif directive == 'Kd':
if ignore_unsupported_color_statement():
return
self.current_mtl.Kd = rgb()
elif directive == 'Ks':
if ignore_unsupported_color_statement():
return
self.current_mtl.Ks = rgb()
elif directive == 'Ns':
if n != 1:
raise Exception("wrong number of arguments for directive Ns")
try:
self.current_mtl.Ns = float(args[0])
except ValueError:
raise Exception("argument for directive Ns must be a floating point number")
else:
self.ignored_directives.add(directive)
|
class MtlParser(Parser):
def reset(self):
pass
def new_target(self):
pass
def parse_line(self, line, mtl_list):
pass
def rgb():
pass
def ignore_unsupported_color_statement():
pass
| 6 | 0 | 16 | 1 | 16 | 0 | 4 | 0 | 1 | 5 | 1 | 0 | 3 | 2 | 3 | 10 | 65 | 5 | 60 | 15 | 54 | 0 | 53 | 15 | 47 | 13 | 2 | 2 | 21 |
7,050 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wavefront.py
|
MAVProxy.modules.lib.wavefront.Mtl
|
class Mtl:
def __init__(self):
self.name = None
self.Ka = 1.0, 1.0, 1.0
self.Kd = 1.0, 1.0, 1.0
self.Ks = 1.0, 1.0, 1.0
self.Ns = 1.0
|
class Mtl:
def __init__(self):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 5 | 1 | 1 | 7 | 0 | 7 | 7 | 5 | 0 | 7 | 7 | 5 | 1 | 0 | 0 | 1 |
7,051 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/textconsole.py
|
MAVProxy.modules.lib.textconsole.SimpleConsole
|
class SimpleConsole():
'''
a message console for MAVProxy
'''
def __init__(self):
pass
def write(self, text, fg='black', bg='white'):
'''write to the console'''
if isinstance(text, str):
sys.stdout.write(text)
else:
sys.stdout.write(str(text))
sys.stdout.flush()
def writeln(self, text, fg='black', bg='white'):
'''write to the console with linefeed'''
if not isinstance(text, str):
text = str(text)
self.write(text + '\n', fg=fg, bg=bg)
def set_status(self, name, text='', row=0, fg='black', bg='white'):
'''set a status value'''
pass
def error(self, text, fg='red', bg='white'):
self.writeln(text, fg=fg, bg=bg)
def close(self):
pass
def is_alive(self):
'''check if we are alive'''
return True
def set_menu(self, menu, callback):
pass
|
class SimpleConsole():
'''
a message console for MAVProxy
'''
def __init__(self):
pass
def write(self, text, fg='black', bg='white'):
'''write to the console'''
pass
def writeln(self, text, fg='black', bg='white'):
'''write to the console with linefeed'''
pass
def set_status(self, name, text='', row=0, fg='black', bg='white'):
'''set a status value'''
pass
def error(self, text, fg='red', bg='white'):
pass
def close(self):
pass
def is_alive(self):
'''check if we are alive'''
pass
def set_menu(self, menu, callback):
pass
| 9 | 5 | 3 | 0 | 3 | 1 | 1 | 0.3 | 0 | 1 | 0 | 1 | 8 | 0 | 8 | 8 | 37 | 7 | 23 | 9 | 14 | 7 | 22 | 9 | 13 | 2 | 0 | 1 | 10 |
7,052 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.parseHTMLDirectoryListing
|
class parseHTMLDirectoryListing(HTMLParser):
def __init__(self):
#print("parseHTMLDirectoryListing.__init__")
HTMLParser.__init__(self)
self.title="Undefined"
self.isDirListing = False
self.dirList=[]
self.inTitle = False
self.inHyperLink = False
self.currAttrs=""
self.currHref=""
def handle_starttag(self, tag, attrs):
#print("Encountered the beginning of a %s tag" % tag)
if tag=="title":
self.inTitle = True
if tag == "a":
self.inHyperLink = True
self.currAttrs=attrs
for attr in attrs:
if attr[0]=='href':
self.currHref = attr[1]
def handle_endtag(self, tag):
#print("Encountered the end of a %s tag" % tag)
if tag=="title":
self.inTitle = False
if tag == "a":
# This is to avoid us adding the parent directory to the list.
if self.currHref!="":
self.dirList.append(self.currHref)
self.currAttrs=""
self.currHref=""
self.inHyperLink = False
def handle_data(self,data):
if self.inTitle:
self.title = data
'''print("title=%s" % data)'''
if "Index of" in self.title:
#print("it is an index!!!!")
self.isDirListing = True
if self.inHyperLink:
# We do not include parent directory in listing.
if "Parent Directory" in data:
self.currHref=""
def getDirListing(self):
return self.dirList
|
class parseHTMLDirectoryListing(HTMLParser):
def __init__(self):
pass
def handle_starttag(self, tag, attrs):
pass
def handle_endtag(self, tag):
pass
def handle_data(self,data):
pass
def getDirListing(self):
pass
| 6 | 0 | 9 | 0 | 7 | 1 | 3 | 0.18 | 1 | 0 | 0 | 0 | 5 | 7 | 5 | 5 | 51 | 6 | 38 | 14 | 32 | 7 | 38 | 14 | 32 | 5 | 1 | 3 | 16 |
7,053 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.WrongTileError
|
class WrongTileError(Exception):
"""Raised when the value of a pixel outside the tile area is requested."""
def __init__(self, tile_lat, tile_lon, req_lat, req_lon):
Exception.__init__(self)
self.tile_lat = tile_lat
self.tile_lon = tile_lon
self.req_lat = req_lat
self.req_lon = req_lon
def __str__(self):
return "SRTM tile for %d, %d does not contain data for %d, %d!" % (
self.tile_lat, self.tile_lon, self.req_lat, self.req_lon)
|
class WrongTileError(Exception):
'''Raised when the value of a pixel outside the tile area is requested.'''
def __init__(self, tile_lat, tile_lon, req_lat, req_lon):
pass
def __str__(self):
pass
| 3 | 1 | 5 | 0 | 5 | 0 | 1 | 0.1 | 1 | 0 | 0 | 0 | 2 | 4 | 2 | 12 | 12 | 1 | 10 | 7 | 7 | 1 | 9 | 7 | 6 | 1 | 3 | 0 | 2 |
7,054 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.SRTMTile
|
class SRTMTile:
"""Base class for all SRTM tiles.
Each SRTM tile is size x size pixels big and contains
data for the area from (lat, lon) to (lat+1, lon+1) inclusive.
This means there is a 1 pixel overlap between tiles. This makes it
easier for as to interpolate the value, because for every point we
only have to look at a single tile.
"""
def __init__(self, f, lat, lon):
try:
zipf = zipfile.ZipFile(f, 'r')
except Exception:
raise InvalidTileError(lat, lon)
names = zipf.namelist()
if len(names) != 1:
raise InvalidTileError(lat, lon)
data = zipf.read(names[0])
self.size = int(math.sqrt(len(data)/2)) # 2 bytes per sample
# Currently only SRTM1/3 is supported
if self.size not in (1201, 3601):
raise InvalidTileError(lat, lon)
self.data = array.array('h', data)
self.data.byteswap()
if len(self.data) != self.size * self.size:
raise InvalidTileError(lat, lon)
self.lat = lat
self.lon = lon
@staticmethod
def _avg(value1, value2, weight):
"""Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned.
"""
if value1 is None:
return value2
if value2 is None:
return value1
return value2 * weight + value1 * (1 - weight)
def calcOffset(self, x, y):
"""Calculate offset into data array. Only uses to test correctness
of the formula."""
# Datalayout
# X = longitude
# Y = latitude
# Sample for size 1201x1201
# ( 0/1200) ( 1/1200) ... (1199/1200) (1200/1200)
# ( 0/1199) ( 1/1199) ... (1199/1199) (1200/1199)
# ... ... ... ...
# ( 0/ 1) ( 1/ 1) ... (1199/ 1) (1200/ 1)
# ( 0/ 0) ( 1/ 0) ... (1199/ 0) (1200/ 0)
# Some offsets:
# (0/1200) 0
# (1200/1200) 1200
# (0/1199) 1201
# (1200/1199) 2401
# (0/0) 1201*1200
# (1200/0) 1201*1201-1
return x + self.size * (self.size - y - 1)
def getPixelValue(self, x, y):
"""Get the value of a pixel from the data, handling voids in the
SRTM data."""
assert x < self.size, "x: %d<%d" % (x, self.size)
assert y < self.size, "y: %d<%d" % (y, self.size)
# Same as calcOffset, inlined for performance reasons
offset = x + self.size * (self.size - y - 1)
#print(offset)
value = self.data[offset]
if value == -32768:
return -1 # -32768 is a special value for areas with no data
return value
def getAltitudeFromLatLon(self, lat, lon):
"""Get the altitude of a lat lon pair, using the four neighbouring
pixels for interpolation.
"""
# print("-----\nFromLatLon", lon, lat)
lat -= self.lat
lon -= self.lon
# print("lon, lat", lon, lat)
if lat < 0.0 or lat >= 1.0 or lon < 0.0 or lon >= 1.0:
raise WrongTileError(self.lat, self.lon, self.lat+lat, self.lon+lon)
x = lon * (self.size - 1)
y = lat * (self.size - 1)
# print("x,y", x, y)
x_int = int(x)
x_frac = x - int(x)
y_int = int(y)
y_frac = y - int(y)
# print("frac", x_int, x_frac, y_int, y_frac)
value00 = self.getPixelValue(x_int, y_int)
value10 = self.getPixelValue(x_int+1, y_int)
value01 = self.getPixelValue(x_int, y_int+1)
value11 = self.getPixelValue(x_int+1, y_int+1)
value1 = self._avg(value00, value10, x_frac)
value2 = self._avg(value01, value11, x_frac)
value = self._avg(value1, value2, y_frac)
# print("%4d %4d | %4d\n%4d %4d | %4d\n-------------\n%4d" % (
# value00, value10, value1, value01, value11, value2, value))
return value
|
class SRTMTile:
'''Base class for all SRTM tiles.
Each SRTM tile is size x size pixels big and contains
data for the area from (lat, lon) to (lat+1, lon+1) inclusive.
This means there is a 1 pixel overlap between tiles. This makes it
easier for as to interpolate the value, because for every point we
only have to look at a single tile.
'''
def __init__(self, f, lat, lon):
pass
@staticmethod
def _avg(value1, value2, weight):
'''Returns the weighted average of two values and handles the case where
one value is None. If both values are None, None is returned.
'''
pass
def calcOffset(self, x, y):
'''Calculate offset into data array. Only uses to test correctness
of the formula.'''
pass
def getPixelValue(self, x, y):
'''Get the value of a pixel from the data, handling voids in the
SRTM data.'''
pass
def getAltitudeFromLatLon(self, lat, lon):
'''Get the altitude of a lat lon pair, using the four neighbouring
pixels for interpolation.
'''
pass
| 7 | 5 | 18 | 0 | 11 | 7 | 3 | 0.8 | 0 | 6 | 2 | 1 | 4 | 4 | 5 | 5 | 102 | 5 | 55 | 29 | 48 | 44 | 54 | 28 | 48 | 5 | 0 | 1 | 13 |
7,055 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.SRTMOceanTile
|
class SRTMOceanTile(SRTMTile):
'''a tile for areas of zero altitude'''
def __init__(self, lat, lon):
self.lat = lat
self.lon = lon
def getAltitudeFromLatLon(self, lat, lon):
return 0
|
class SRTMOceanTile(SRTMTile):
'''a tile for areas of zero altitude'''
def __init__(self, lat, lon):
pass
def getAltitudeFromLatLon(self, lat, lon):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.17 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 7 | 8 | 1 | 6 | 5 | 3 | 1 | 6 | 5 | 3 | 1 | 1 | 0 | 2 |
7,056 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.SRTMDownloader
|
class SRTMDownloader():
"""Automatically download SRTM tiles."""
def __init__(self, server="terrain.ardupilot.org",
directory="SRTM3",
cachedir=None,
offline=0,
debug=False,
use_http=False):
if cachedir is None:
try:
cachedir = os.path.join(os.environ['HOME'], '.tilecache', directory)
except Exception:
if 'LOCALAPPDATA' in os.environ:
cachedir = os.path.join(os.environ['LOCALAPPDATA'], '.tilecache', directory)
else:
import tempfile
cachedir = os.path.join(tempfile.gettempdir(), 'MAVProxy', directory)
# User migration to new folder struct (SRTM -> SRTM3)
if directory == "SRTM3" and not os.path.exists(cachedir) and os.path.exists(cachedir[:-1]):
print("Migrating old SRTM folder")
os.rename(cachedir[:-1], cachedir)
self.debug = debug
self.offline = offline
self.offlinemessageshown = 0
if self.offline == 1 and self.debug:
print("Map Module in Offline mode")
self.first_failure = False
self.server = server
self.directory = "/" + directory +"/"
self.cachedir = cachedir
if self.debug:
print("SRTMDownloader - server=%s, directory=%s." % (self.server, self.directory))
if not os.path.exists(cachedir):
mp_util.mkdir_p(cachedir)
self.filelist = {}
self.filename_regex = re.compile(
r"([NS])(\d{2})([EW])(\d{3})\.hgt\.zip")
self.filelist_file = os.path.join(self.cachedir, "filelist_python")
self.min_filelist_len = 14500
self.use_http = use_http
def loadFileList(self):
"""Load a previously created file list or create a new one if none is
available."""
try:
data = open(self.filelist_file, 'rb')
except IOError:
'''print("No SRTM cached file list. Creating new one!")'''
if self.offline == 0:
self.createFileList()
return
try:
self.filelist = pickle.load(data)
data.close()
if len(self.filelist) < self.min_filelist_len:
self.filelist = {}
if self.offline == 0:
self.createFileList()
except:
'''print("Unknown error loading cached SRTM file list. Creating new one!")'''
if self.offline == 0:
self.createFileList()
def createFileList(self):
"""SRTM data is split into different directories, get a list of all of
them and create a dictionary for easy lookup."""
global childFileListDownload
global filelistDownloadActive
mypid = os.getpid()
if mypid not in childFileListDownload or not childFileListDownload[mypid].is_alive():
childFileListDownload[mypid] = multiproc.Process(target=self.createFileListHTTP)
filelistDownloadActive = 1
childFileListDownload[mypid].start()
filelistDownloadActive = 0
def getURIWithRedirect(self, url):
'''fetch a URL with redirect handling'''
tries = 0
while tries < 5:
if self.use_http:
conn = httplib.HTTPConnection(self.server)
else:
conn = httplib.HTTPSConnection(self.server)
conn.request("GET", url)
r1 = conn.getresponse()
if r1.status in [301, 302, 303, 307]:
location = r1.getheader('Location')
if self.debug:
print("redirect from %s to %s" % (url, location))
url = location
conn.close()
tries += 1
continue
data = r1.read()
conn.close()
if sys.version_info.major < 3:
return data
else:
encoding = r1.headers.get_content_charset()
if encoding is not None:
return data.decode(encoding)
elif ".zip" in url or ".hgt" in url:
return data
else:
return data.decode('utf-8')
return None
def createFileListHTTP(self):
"""Create a list of the available SRTM files on the server using
HTTP file transfer protocol (rather than ftp).
30may2010 GJ ORIGINAL VERSION
"""
mp_util.child_close_fds()
if self.debug:
print("Connecting to %s" % self.server, self.directory)
try:
data = self.getURIWithRedirect(self.directory)
except Exception:
return
parser = parseHTMLDirectoryListing()
parser.feed(data)
continents = parser.getDirListing()
# Flat structure
if any(".hgt.zip" in mystring for mystring in continents):
files = continents
for filename in files:
if ".hgt.zip" in filename:
self.filelist[self.parseFilename(filename)] = ("/", filename)
else:
# tiles in subfolders
if self.debug:
print('continents: ', continents)
for continent in continents:
if not continent[0].isalpha() or continent.startswith('README'):
continue
if self.debug:
print("Downloading file list for: ", continent)
url = "%s%s" % (self.directory,continent)
if self.debug:
print("fetching %s" % url)
try:
data = self.getURIWithRedirect(url)
except Exception as ex:
print("Failed to download %s : %s" % (url, ex))
continue
parser = parseHTMLDirectoryListing()
parser.feed(data)
files = parser.getDirListing()
for filename in files:
self.filelist[self.parseFilename(filename)] = (
continent, filename)
'''print(self.filelist)'''
# Add meta info
self.filelist["server"] = self.server
self.filelist["directory"] = self.directory
tmpname = self.filelist_file + ".tmp"
with open(tmpname , 'wb') as output:
pickle.dump(self.filelist, output)
output.close()
try:
os.unlink(self.filelist_file)
except Exception:
pass
try:
os.rename(tmpname, self.filelist_file)
except Exception:
pass
if self.debug:
print("created file list with %u entries" % len(self.filelist))
def parseFilename(self, filename):
"""Get lat/lon values from filename."""
match = self.filename_regex.match(filename)
if match is None:
# TODO?: Raise exception?
'''print("Filename", filename, "unrecognized!")'''
return None
lat = int(match.group(2))
lon = int(match.group(4))
if match.group(1) == "S":
lat = -lat
if match.group(3) == "W":
lon = -lon
return lat, lon
def getTile(self, lat, lon):
"""Get a SRTM tile object. This function can return either an SRTM1 or
SRTM3 object depending on what is available, however currently it
only returns SRTM3 objects."""
global childFileListDownload
global filelistDownloadActive
mypid = os.getpid()
if mypid in childFileListDownload and childFileListDownload[mypid].is_alive():
if self.debug:
print("still getting file list")
return 0
elif not os.path.isfile(self.filelist_file) and filelistDownloadActive == 0:
self.createFileList()
return 0
elif not self.filelist:
if self.debug:
print("Filelist download complete, loading data ", self.filelist_file)
data = open(self.filelist_file, 'rb')
self.filelist = pickle.load(data)
data.close()
try:
continent, filename = self.filelist[(int(lat), int(lon))]
except KeyError:
if len(self.filelist) > self.min_filelist_len:
# we appear to have a full filelist - this must be ocean
return SRTMOceanTile(int(lat), int(lon))
return 0
global childTileDownload
mypid = os.getpid()
if not os.path.exists(os.path.join(self.cachedir, filename)):
if not mypid in childTileDownload or not childTileDownload[mypid].is_alive():
try:
childTileDownload[mypid] = multiproc.Process(target=self.downloadTile, args=(str(continent), str(filename)))
childTileDownload[mypid].start()
except Exception as ex:
if mypid in childTileDownload:
childTileDownload.pop(mypid)
return 0
'''print("Getting Tile")'''
return 0
elif mypid in childTileDownload and childTileDownload[mypid].is_alive():
'''print("Still Getting Tile")'''
return 0
# TODO: Currently we create a new tile object each time.
# Caching is required for improved performance.
try:
return SRTMTile(os.path.join(self.cachedir, filename), int(lat), int(lon))
except InvalidTileError:
return 0
def downloadTile(self, continent, filename):
#Use HTTP
mp_util.child_close_fds()
if self.offline == 1:
return
filepath = "%s%s%s" % \
(self.directory,continent,filename)
try:
data = self.getURIWithRedirect(filepath)
if data:
self.ftpfile = open(os.path.join(self.cachedir, filename), 'wb')
self.ftpfile.write(data)
self.ftpfile.close()
self.ftpfile = None
except Exception as e:
if not self.first_failure:
print("SRTM Download failed %s on server %s" % (filepath, self.server))
self.first_failure = True
pass
|
class SRTMDownloader():
'''Automatically download SRTM tiles.'''
def __init__(self, server="terrain.ardupilot.org",
directory="SRTM3",
cachedir=None,
offline=0,
debug=False,
use_http=False):
pass
def loadFileList(self):
'''Load a previously created file list or create a new one if none is
available.'''
pass
def createFileList(self):
'''SRTM data is split into different directories, get a list of all of
them and create a dictionary for easy lookup.'''
pass
def getURIWithRedirect(self, url):
'''fetch a URL with redirect handling'''
pass
def createFileListHTTP(self):
'''Create a list of the available SRTM files on the server using
HTTP file transfer protocol (rather than ftp).
30may2010 GJ ORIGINAL VERSION
'''
pass
def parseFilename(self, filename):
'''Get lat/lon values from filename.'''
pass
def getTile(self, lat, lon):
'''Get a SRTM tile object. This function can return either an SRTM1 or
SRTM3 object depending on what is available, however currently it
only returns SRTM3 objects.'''
pass
def downloadTile(self, continent, filename):
pass
| 9 | 7 | 32 | 1 | 27 | 4 | 8 | 0.13 | 0 | 8 | 4 | 0 | 8 | 13 | 8 | 8 | 263 | 16 | 218 | 61 | 198 | 29 | 201 | 52 | 186 | 16 | 0 | 4 | 64 |
7,057 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.NoSuchTileError
|
class NoSuchTileError(Exception):
"""Raised when there is no tile for a region."""
def __init__(self, lat, lon):
Exception.__init__(self)
self.lat = lat
self.lon = lon
def __str__(self):
return "No SRTM tile for %d, %d available!" % (self.lat, self.lon)
|
class NoSuchTileError(Exception):
'''Raised when there is no tile for a region.'''
def __init__(self, lat, lon):
pass
def __str__(self):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.14 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 12 | 9 | 1 | 7 | 5 | 4 | 1 | 7 | 5 | 4 | 1 | 3 | 0 | 2 |
7,058 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/srtm.py
|
MAVProxy.modules.lib.srtm.InvalidTileError
|
class InvalidTileError(Exception):
"""Raised when the SRTM tile file contains invalid data."""
def __init__(self, lat, lon):
Exception.__init__(self)
self.lat = lat
self.lon = lon
def __str__(self):
return "SRTM tile for %d, %d is invalid!" % (self.lat, self.lon)
|
class InvalidTileError(Exception):
'''Raised when the SRTM tile file contains invalid data.'''
def __init__(self, lat, lon):
pass
def __str__(self):
pass
| 3 | 1 | 3 | 0 | 3 | 0 | 1 | 0.14 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 12 | 9 | 1 | 7 | 5 | 4 | 1 | 7 | 5 | 4 | 1 | 3 | 0 | 2 |
7,059 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/rtcm3.py
|
MAVProxy.modules.lib.rtcm3.RTCM3
|
class RTCM3:
def __init__(self, debug=False):
self.crc_table = None
self.debug = debug
self.reset()
def get_packet(self):
'''return bytearray of last parsed packet'''
return self.parsed_pkt
def get_packet_ID(self):
'''get get of packet, or None'''
if self.parsed_pkt is None or len(self.parsed_pkt) < 8:
return None
id, = struct.unpack('>H', self.parsed_pkt[3:5])
id >>= 4
return id
def reset(self):
'''reset state'''
self.pkt = bytearray()
self.pkt_len = 0
self.parsed_pkt = None
def parse(self):
'''parse packet'''
parity = self.pkt[-3:]
crc1 = parity[0] << 16 | parity[1] << 8 | parity[2]
crc2 = self.crc24(self.pkt[:-3])
if crc1 != crc2:
if self.debug:
print("crc fail len=%u" % len(self.pkt))
# look for preamble
idx = self.pkt[1:].find(bytearray([RTCMv3_PREAMBLE]))
if idx >= 0:
self.pkt = self.pkt[1+idx:]
if len(self.pkt) >= 3:
self.pkt_len, = struct.unpack('>H', self.pkt[1:3])
self.pkt_len &= 0x3ff
else:
self.pkt_len = 0
else:
self.reset()
return False
# got a good packet
self.parsed_pkt = self.pkt
self.pkt = bytearray()
self.pkt_len = 0
return True
def read(self, byte):
'''read in one byte, return true if a full packet is available'''
#import random
#if random.uniform(0,1000) < 1:
# return False
byte = ord(byte)
if len(self.pkt) == 0 and byte != RTCMv3_PREAMBLE:
# discard
return False
self.pkt.append(byte)
if self.pkt_len == 0 and len(self.pkt) >= 3:
self.pkt_len, = struct.unpack('>H', self.pkt[1:3])
self.pkt_len &= 0x3ff
if self.pkt_len == 0:
self.reset()
return False
if self.pkt_len > 0 and len(self.pkt) >= 3 + self.pkt_len + 3:
remainder = self.pkt[6+self.pkt_len:]
self.pkt = self.pkt[:6+self.pkt_len]
# got header, packet body and parity
ret = self.parse()
self.pkt.extend(remainder)
return ret
# need more bytes
return False
def crc24(self, bytes):
'''calculate 24 bit crc'''
if self.crc_table is None:
# initialise table
self.crc_table = [0] * 256
for i in range(256):
self.crc_table[i] = i<<16
for j in range(8):
self.crc_table[i] <<= 1
if (self.crc_table[i] & 0x1000000):
self.crc_table[i] ^= POLYCRC24
crc = 0
for b in bytes:
crc = ((crc<<8)&0xFFFFFF) ^ self.crc_table[(crc>>16) ^ b]
return crc
|
class RTCM3:
def __init__(self, debug=False):
pass
def get_packet(self):
'''return bytearray of last parsed packet'''
pass
def get_packet_ID(self):
'''get get of packet, or None'''
pass
def reset(self):
'''reset state'''
pass
def parse(self):
'''parse packet'''
pass
def read(self, byte):
'''read in one byte, return true if a full packet is available'''
pass
def crc24(self, bytes):
'''calculate 24 bit crc'''
pass
| 8 | 6 | 13 | 1 | 10 | 2 | 3 | 0.21 | 0 | 2 | 0 | 0 | 7 | 5 | 7 | 7 | 97 | 12 | 70 | 23 | 62 | 15 | 68 | 23 | 60 | 6 | 0 | 4 | 21 |
7,060 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/rline.py
|
MAVProxy.modules.lib.rline.rline
|
class rline(object):
'''async readline abstraction'''
def __init__(self, prompt, mpstate):
global rline_mpstate
self.prompt = prompt
rline_mpstate = mpstate
# other modules can add their own completion functions
mpstate.completion_functions = {
'(FILENAME)' : complete_filename,
'(PARAMETER)' : complete_parameter,
'(VARIABLE)' : complete_variable,
'(MESSAGETYPE)' : complete_messagetype,
'(SETTING)' : rline_mpstate.settings.completion,
'(COMMAND)' : complete_command,
'(ALIAS)' : complete_alias,
'(AVAILMODULES)' : complete_modules,
'(LOADEDMODULES)' : complete_loadedmodules
}
if platform.system() == 'Windows' and sys.version_info >= (3, 0):
# Create key bindings registry with a custom binding for the Tab key that
# displays completions like GNU readline.
self.session = PromptSession()
mpstate.completor = MAVPromptCompleter()
def set_prompt(self, prompt):
if prompt != self.prompt:
self.prompt = prompt
if platform.system() != 'Windows' or sys.version_info < (3, 0):
sys.stdout.write(prompt)
self.redisplay()
def add_history(self, line):
'''add a line to the history'''
if platform.system() == 'Windows' and sys.version_info >= (3, 0):
self.session.history.append_string(line)
else:
readline.add_history(line)
self.redisplay()
def redisplay(self):
'''redisplay prompt'''
try:
redisplay()
except Exception as ex:
pass
def get_prompt(self):
'''return the current prompt'''
return self.prompt
def input(self):
''' get user input'''
ret = ""
if platform.system() == 'Windows' and sys.version_info >= (3, 0):
global rline_mpstate
with patch_stdout():
return self.session.prompt(self.get_prompt,completer=rline_mpstate.completor, complete_while_typing=False, complete_style=CompleteStyle.READLINE_LIKE, refresh_interval=0.5)
else:
return input(self.get_prompt())
|
class rline(object):
'''async readline abstraction'''
def __init__(self, prompt, mpstate):
pass
def set_prompt(self, prompt):
pass
def add_history(self, line):
'''add a line to the history'''
pass
def redisplay(self):
'''redisplay prompt'''
pass
def get_prompt(self):
'''return the current prompt'''
pass
def input(self):
''' get user input'''
pass
| 7 | 5 | 9 | 0 | 8 | 1 | 2 | 0.17 | 1 | 4 | 1 | 0 | 6 | 2 | 6 | 6 | 61 | 7 | 46 | 13 | 37 | 8 | 34 | 12 | 25 | 3 | 1 | 2 | 12 |
7,061 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/param_help.py
|
MAVProxy.modules.lib.param_help.ParamHelp
|
class ParamHelp:
def __init__(self):
self.xml_filepath = None
self.vehicle_name = None
self.last_pair = (None,None)
self.last_htree = None
def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['Rover', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker', 'Blimp', 'Heli']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml.gz' % vehicle
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
files.append((url, path))
try:
child = multiproc.Process(target=mp_util.download_files, args=(files,))
child.start()
except Exception as e:
print(e)
def param_use_xml_filepath(self, filepath):
self.xml_filepath = filepath
def param_help_tree(self, verbose=False):
'''return a "help tree", a map between a parameter and its metadata. May return None if help is not available'''
if self.last_pair == (self.xml_filepath, self.vehicle_name):
return self.last_htree
if self.xml_filepath is not None:
if verbose:
print("param: using xml_filepath=%s" % self.xml_filepath)
path = self.xml_filepath
else:
if self.vehicle_name is None:
if verbose:
print("Unknown vehicle type")
return None
path = mp_util.dot_mavproxy("%s.xml" % self.vehicle_name)
if not os.path.exists(path):
if self.vehicle_name == 'APMrover2':
path = mp_util.dot_mavproxy("%s.xml" % "Rover")
if not os.path.exists(path):
if verbose:
print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name)
return None
if not os.path.exists(path):
if verbose:
print("Param XML (%s) does not exist" % path)
return None
xml = open(path,'rb').read()
from lxml import objectify
objectify.enable_recursive_str()
tree = objectify.fromstring(xml)
htree = {}
for p in tree.vehicles.parameters.param:
n = p.get('name').split(':')[1]
htree[n] = p
for lib in tree.libraries.parameters:
for p in lib.param:
n = p.get('name')
htree[n] = p
self.last_htree = htree
self.last_pair = (self.xml_filepath, self.vehicle_name)
return htree
def param_set_xml_filepath(self, args):
self.xml_filepath = args[0]
def param_apropos(self, args):
'''search parameter help for a keyword, list those parameters'''
if len(args) == 0:
print("Usage: param apropos keyword")
return
htree = self.param_help_tree(True)
if htree is None:
return
contains = {}
for keyword in args:
keyword = keyword.lower()
for param in htree.keys():
if str(htree[param]).lower().find(keyword) != -1:
contains[param] = True
for param in contains.keys():
print("%s" % (param,))
def get_Values_from_help(self, help):
children = help.getchildren()
for c in children:
if str(c).startswith("values"):
return c.getchildren()
return []
def get_bitmask_from_help(self, help):
# check for presence of "bitmask" subtree, use it by preference:
children = help.getchildren()
for c in children:
if str(c).startswith("bitmask"):
ret = {}
for entry in c.getchildren():
ret[int(entry.get('code'))] = str(entry)
return ret
# "bitmask" subtree not present, split the traditional
# "Bitmask" field ourselves:
if not hasattr(help, 'field'):
return None
field = help.field
if not hasattr(field, 'attrib'):
return None
if field.attrib.get('name',None) != 'Bitmask':
return None
a = str(field).split(',')
ret = {}
for v in a:
a2 = v.split(':')
if len(a2) == 2:
ret[a2[0]] = a2[1]
return ret
def param_info(self, param, value):
'''return info string for a param value'''
htree = self.param_help_tree()
if htree is None:
return
param = param.upper()
if not param in htree:
return None
help = htree[param]
remaining_bits = int(value)
try:
bitmask = self.get_bitmask_from_help(help)
if bitmask is not None:
v = []
for k in bitmask.keys():
if int(value) & (1<<int(k)):
v.append(bitmask[k])
remaining_bits &= ~(1<<int(k))
for i in range(31):
if remaining_bits & (1<<i):
v.append("Uknownbit%u" % i)
return '|'.join(v)
except Exception as e:
print(e)
pass
try:
values = self.get_Values_from_help(help)
for v in values:
if int(v.get('code')) == int(value):
return v
except Exception as e:
pass
return None
def param_help(self, args):
'''show help on a parameter'''
if len(args) == 0:
print("Usage: param help PARAMETER_NAME")
return
htree = self.param_help_tree(True)
if htree is None:
return
for h in args:
h = h.upper()
if h in htree:
help = htree[h]
print("%s: %s\n" % (h, help.get('humanName')))
print(help.get('documentation'))
try:
print("\n")
for f in help.field:
if f.get('name') == 'Bitmask':
# handled specially below
continue
print("%s : %s" % (f.get('name'), str(f)))
except Exception as e:
pass
try:
values = self.get_Values_from_help(help)
if len(values):
print("\nValues: ")
for v in values:
print("\t%3u : %s" % (int(v.get('code')), str(v)))
except Exception as e:
print("Caught exception %s" % repr(e))
pass
try:
# note this is a dictionary:
values = self.get_bitmask_from_help(help)
if values is not None and len(values):
print("\nBitmask: ")
for (n, v) in values.items():
print(f"\t{int(n):3d} : {v}")
except Exception as e:
print("Caught exception %s" % repr(e))
pass
else:
print("Parameter '%s' not found in documentation" % h)
def param_check(self, params, args):
'''Check through parameters for obvious misconfigurations'''
problems_found = False
htree = self.param_help_tree(True)
if htree is None:
return
for param in params.keys():
if param.startswith("SIM_"):
# no documentation for these ATM
continue
value = params[param]
# print("%s: %s" % (param, str(value)))
try:
help = htree[param]
except KeyError:
print("%s: not found in documentation" % (param,))
problems_found = True
continue
# we'll ignore the Values field if there's a bitmask field
# involved as they're usually just examples.
has_bitmask = False
for f in getattr(help, "field", []):
if f.get('name') == "Bitmask":
has_bitmask = True
break
if not has_bitmask:
values = self.get_Values_from_help(help)
if len(values) == 0:
# no prescribed values list
continue
value_values = [float(x.get("code")) for x in values]
if value not in value_values:
print("%s: value %f not in Values (%s)" %
(param, value, str(value_values)))
problems_found = True
if problems_found:
print("Remember to `param download` before trusting the checking! Also, remember that parameter documentation is for *master*!")
|
class ParamHelp:
def __init__(self):
pass
def param_help_download(self):
'''download XML files for parameters'''
pass
def param_use_xml_filepath(self, filepath):
pass
def param_help_tree(self, verbose=False):
'''return a "help tree", a map between a parameter and its metadata. May return None if help is not available'''
pass
def param_set_xml_filepath(self, args):
pass
def param_apropos(self, args):
'''search parameter help for a keyword, list those parameters'''
pass
def get_Values_from_help(self, help):
pass
def get_bitmask_from_help(self, help):
pass
def param_info(self, param, value):
'''return info string for a param value'''
pass
def param_help_download(self):
'''show help on a parameter'''
pass
def param_check(self, params, args):
'''Check through parameters for obvious misconfigurations'''
pass
| 12 | 6 | 21 | 1 | 19 | 1 | 7 | 0.08 | 0 | 6 | 0 | 0 | 11 | 4 | 11 | 11 | 240 | 17 | 207 | 70 | 194 | 16 | 204 | 67 | 191 | 15 | 0 | 5 | 77 |
7,062 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/param_ftp.py
|
MAVProxy.modules.lib.param_ftp.ParamData
|
class ParamData(object):
def __init__(self):
# params as (name, value, ptype)
self.params = []
# defaults as (name, value, ptype)
self.defaults = None
def add_param(self, name, value, ptype):
self.params.append((name,value,ptype))
def add_default(self, name, value, ptype):
if self.defaults is None:
self.defaults = []
self.defaults.append((name,value,ptype))
|
class ParamData(object):
def __init__(self):
pass
def add_param(self, name, value, ptype):
pass
def add_default(self, name, value, ptype):
pass
| 4 | 0 | 4 | 0 | 3 | 1 | 1 | 0.2 | 1 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 14 | 2 | 10 | 6 | 6 | 2 | 10 | 6 | 6 | 2 | 1 | 1 | 4 |
7,063 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/optparse_gui/__init__.py
|
MAVProxy.modules.lib.optparse_gui.UserCancelledError
|
class UserCancelledError( Exception ):
pass
|
class UserCancelledError( Exception ):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
7,064 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/optparse_gui/__init__.py
|
MAVProxy.modules.lib.optparse_gui.OptionParser
|
class OptionParser( optparse.OptionParser ):
SUPER = optparse.OptionParser
def __init__( self, *args, **kwargs ):
if 'option_class' not in kwargs:
kwargs['option_class'] = Option
self.SUPER.__init__( self, *args, **kwargs )
def parse_args( self, args = None, values = None ):
'''
multiprocessing wrapper around _parse_args
'''
q = multiproc.Queue()
p = multiproc.Process(target=self._parse_args, args=(q, args, values))
p.start()
ret = q.get()
p.join()
return ret
def _parse_args( self, q, args, values):
'''
This is the heart of it all - overrides optparse.OptionParser.parse_args
@param arg is irrelevant and thus ignored,
it is here only for interface compatibility
'''
if wx.GetApp() is None:
self.app = wx.App( False )
# preprocess command line arguments and set to defaults
option_values, args = self.SUPER.parse_args(self, args, values)
for option in self.option_list:
if option.dest and hasattr(option_values, option.dest):
default = getattr(option_values, option.dest)
if default is not None:
option.default = default
dlg = OptparseDialog( option_parser = self, title=self.get_description() )
if args:
dlg.args_ctrl.Value = ' '.join(args)
dlg_result = dlg.ShowModal()
if wx.ID_OK != dlg_result:
raise UserCancelledError( 'User has canceled' )
if values is None:
values = self.get_default_values()
option_values, args = dlg.getOptionsAndArgs()
for option, value in option_values.iteritems():
if ( 'store_true' == option.action ) and ( value is False ):
setattr( values, option.dest, False )
continue
if ( 'store_false' == option.action ) and ( value is True ):
setattr( values, option.dest, False )
continue
if option.takes_value() is False:
value = None
option.process( option, value, values, self )
q.put((values, args))
def error( self, msg ):
wx.MessageDialog( None, msg, 'Error!', wx.ICON_ERROR ).ShowModal()
return self.SUPER.error( self, msg )
|
class OptionParser( optparse.OptionParser ):
def __init__( self, *args, **kwargs ):
pass
def parse_args( self, args = None, values = None ):
'''
multiprocessing wrapper around _parse_args
'''
pass
def _parse_args( self, q, args, values):
'''
This is the heart of it all - overrides optparse.OptionParser.parse_args
@param arg is irrelevant and thus ignored,
it is here only for interface compatibility
'''
pass
def error( self, msg ):
pass
| 5 | 2 | 16 | 3 | 11 | 2 | 4 | 0.2 | 1 | 3 | 3 | 0 | 4 | 1 | 4 | 57 | 68 | 14 | 45 | 16 | 40 | 9 | 45 | 16 | 40 | 12 | 2 | 3 | 16 |
7,065 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/optparse_gui/__init__.py
|
MAVProxy.modules.lib.optparse_gui.Option
|
class Option (optparse.Option):
SUPER = optparse.Option
TYPES = SUPER.TYPES + ('file', 'directory')
|
class Option (optparse.Option):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 18 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
7,066 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/opengl.py
|
MAVProxy.modules.lib.opengl.WavefrontObject
|
class WavefrontObject(Object):
def __init__(self, obj):
vertices, normals, indices, material_sequence = WavefrontObject.calc_arrays(obj)
super(WavefrontObject, self).__init__(
vertices=vertices,
normals=normals,
indices=indices,
material=None,
)
self.material_sequence = material_sequence
def draw(self, program):
self.before_draw(program)
if self.material_sequence:
for j in range(len(self.material_sequence) - 1):
i, m = self.material_sequence[j]
next_i, _ = self.material_sequence[j + 1]
program.use_material(m)
glDrawElements(GL_TRIANGLES, next_i - i, GL_UNSIGNED_INT, c_void_p(sizeof(c_uint) * i));
i, m = self.material_sequence[-1]
program.use_material(m)
glDrawElements(GL_TRIANGLES, self.num_indices - i, GL_UNSIGNED_INT, c_void_p(sizeof(c_uint) * i));
self.after_draw(program)
@staticmethod
def calc_arrays(obj):
vertices = []
normals = []
indices = []
# stores tuples with the material and the starting index for the
# elements vertices
material_sequence = []
# mapped with vertex index and normal index
indices_dict = {}
current_mtl = None
material_map = {}
def mtl_to_material(mtl):
if mtl.name not in material_map:
m = Material(
ambient=Vector3(*mtl.Ka),
diffuse=Vector3(*mtl.Kd),
specular=Vector3(*mtl.Ks),
specular_exponent=mtl.Ns,
)
material_map[mtl.name] = m
return material_map[mtl.name]
def index(i, j):
if (i, j) not in indices_dict:
indices_dict[(i, j)] = len(vertices)
vertices.append(obj.vertices[i - 1][:3])
normals.append(obj.normals[j - 1])
return indices_dict[(i, j)]
for f in obj.faces:
vertex_data, mtl = f
if not current_mtl or mtl.name != current_mtl.name:
current_mtl = mtl
material_sequence.append((len(indices), mtl_to_material(mtl)))
i0 = index(vertex_data[0][0], vertex_data[0][2])
ia = index(vertex_data[1][0], vertex_data[1][2])
for i in range(2, len(vertex_data)):
ib = index(vertex_data[i][0], vertex_data[i][2])
indices.append(i0)
indices.append(ia)
indices.append(ib)
ia = ib
return vertices, normals, indices, material_sequence
|
class WavefrontObject(Object):
def __init__(self, obj):
pass
def draw(self, program):
pass
@staticmethod
def calc_arrays(obj):
pass
def mtl_to_material(mtl):
pass
def index(i, j):
pass
| 7 | 0 | 17 | 2 | 15 | 1 | 2 | 0.05 | 1 | 3 | 1 | 0 | 2 | 1 | 3 | 11 | 75 | 11 | 61 | 26 | 54 | 3 | 50 | 25 | 44 | 4 | 2 | 2 | 12 |
7,067 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_GPSInject.py
|
MAVProxy.modules.mavproxy_GPSInject.GPSInjectModule
|
class GPSInjectModule(mp_module.MPModule):
def __init__(self, mpstate):
super(GPSInjectModule, self).__init__(mpstate, "gpsinject", "gpsinject", public=False)
self.gpsinject_settings = mp_settings.MPSettings(
[('source', str, OFFLINE_MBX),
('send_rate_kps', float, 2.0),
('repeat', int, 2),
('gps_mask', int, 0)])
self.add_command('gpsinject', self.cmd_gpsinject, 'GPSInject control',
["<status|start|stop>",
"set (GPSINJECTSETTING)"])
self.add_completion_function('(GPSINJECTSETTING)',
self.gpsinject_settings.completion)
self.buf = None
self.sent_bytes = 0
self.sent_count = 0
self.started = False
self.start_pending = False
self.last_send = None
def idle_task(self):
'''called on idle'''
if not self.started and not self.start_pending:
return
if self.buf is None:
source = self.gpsinject_settings.source
if source.startswith("http"):
req = urllib.request.urlopen(self.gpsinject_settings.source)
if req is not None:
self.buf = req.read()
elif os.path.isfile(self.gpsinject_settings.source):
self.buf = open(self.gpsinject_settings.source,'rb').read()
if self.buf is None:
print("GPSInject: Bad source %s" % source)
self.started = False
self.start_pending = False
return
print("GPSInject: retrieved %u bytes" % len(self.buf))
if self.start_pending:
GPS_RAW_INT = self.master.messages.get("GPS_RAW_INT", None)
GPS2_RAW = self.master.messages.get("GPS2_RAW", None)
if GPS_RAW_INT is None and GPS2_RAW is None:
return
have_gps = False
have_gps = (GPS_RAW_INT is not None and GPS_RAW_INT.fix_type >= 1) or (GPS2_RAW is not None and GPS2_RAW.fix_type >= 1)
if have_gps:
self.started = True
if not self.started:
return
max_send = 110
now = time.time()
sec_per_byte = 1.0/(1024.0*self.gpsinject_settings.send_rate_kps)
if self.last_send is not None and now - self.last_send < max_send*sec_per_byte:
return
if self.last_send is None:
cansend = max_send
else:
cansend = int((now - self.last_send) / sec_per_byte)
self.last_send = now
while cansend > 0:
n = min(max_send, len(self.buf) - self.sent_bytes)
n = min(n, cansend)
msg = self.buf[self.sent_bytes:self.sent_bytes+n]
self.master.mav.gps_inject_data_send(
self.target_system,
self.target_component,
len(msg),
bytearray(msg.ljust(max_send, bytes([0]))))
self.sent_bytes += n
if self.sent_bytes == len(self.buf):
self.sent_bytes = 0
self.sent_count += 1
if self.sent_count == self.gpsinject_settings.repeat:
print("GPSInject: done")
self.started = False
self.start_pending = False
break
cansend -= n
def cmd_gpsinject(self, args):
'''GPSInject command handling'''
if len(args) <= 0:
print("Usage: gpsinject <start|stop|status|set>")
return
if args[0] == "start":
self.buf = None
self.sent_bytes = 0
self.sent_count = 0
self.started = False
self.start_pending = True
self.last_send = None
if args[0] == "stop":
self.start_pending = False
self.started = False
elif args[0] == "status":
self.gpsinject_status()
elif args[0] == "set":
self.gpsinject_settings.command(args[1:])
def gpsinject_status(self):
'''show GPS inject status'''
now = time.time()
if not self.started:
print("GPSInject: Not started")
return
if self.buf is None:
print("GPSInject: download pending")
return
if self.start_pending:
print("GPSInject: start pending GPS")
return
print("GPSInject: sent %u/%u bytes, repeat=%u" % (self.sent_bytes, len(self.buf), self.sent_count))
|
class GPSInjectModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def idle_task(self):
'''called on idle'''
pass
def cmd_gpsinject(self, args):
'''GPSInject command handling'''
pass
def gpsinject_status(self):
'''show GPS inject status'''
pass
| 5 | 3 | 28 | 1 | 26 | 1 | 7 | 0.03 | 1 | 7 | 1 | 0 | 4 | 7 | 4 | 42 | 117 | 8 | 106 | 24 | 101 | 3 | 91 | 24 | 86 | 16 | 2 | 3 | 27 |
7,068 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_GPSInput.py
|
MAVProxy.modules.mavproxy_GPSInput.GPSInputModule
|
class GPSInputModule(mp_module.MPModule):
IGNORE_FLAG_ALL = (mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_ALT |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_HDOP |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_VDOP |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_VEL_HORIZ |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_VEL_VERT |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_SPEED_ACCURACY |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_HORIZONTAL_ACCURACY |
mavutil.mavlink.GPS_INPUT_IGNORE_FLAG_VERTICAL_ACCURACY)
def __init__(self, mpstate):
super(GPSInputModule, self).__init__(mpstate, "GPSInput", "GPS_INPUT message support")
self.add_command('GPSInput.port', self.cmd_port, 'Port selection', ['<25100>'])
self.data = {
'time_usec' : 0, # (uint64_t) Timestamp (micros since boot or Unix epoch)
'gps_id' : 0, # (uint8_t) ID of the GPS for multiple GPS inputs
'ignore_flags' : self.IGNORE_FLAG_ALL, # (uint16_t) Flags indicating which fields to ignore (see GPS_INPUT_IGNORE_FLAGS enum). All other fields must be provided.
'time_week_ms' : 0, # (uint32_t) GPS time (milliseconds from start of GPS week)
'time_week' : 0, # (uint16_t) GPS week number
'fix_type' : 0, # (uint8_t) 0-1: no fix, 2: 2D fix, 3: 3D fix. 4: 3D with DGPS. 5: 3D with RTK
'lat' : 0, # (int32_t) Latitude (WGS84), in degrees * 1E7
'lon' : 0, # (int32_t) Longitude (WGS84), in degrees * 1E7
'alt' : 0, # (float) Altitude (AMSL, not WGS84), in m (positive for up)
'hdop' : 0, # (float) GPS HDOP horizontal dilution of position in m
'vdop' : 0, # (float) GPS VDOP vertical dilution of position in m
'vn' : 0, # (float) GPS velocity in m/s in NORTH direction in earth-fixed NED frame
've' : 0, # (float) GPS velocity in m/s in EAST direction in earth-fixed NED frame
'vd' : 0, # (float) GPS velocity in m/s in DOWN direction in earth-fixed NED frame
'speed_accuracy' : 0, # (float) GPS speed accuracy in m/s
'horiz_accuracy' : 0, # (float) GPS horizontal accuracy in m
'vert_accuracy' : 0, # (float) GPS vertical accuracy in m
'satellites_visible' : 0 # (uint8_t) Number of satellites visible.
}
self.BUFFER_SIZE = 4096
self.ip="127.0.0.1"
self.portnum = 25100
self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.port.bind((self.ip, self.portnum))
self.port.setblocking(0)
mavutil.set_close_on_exec(self.port.fileno())
print("Listening for GPS Input packets on UDP://%s:%s" % (self.ip, self.portnum))
def idle_task(self):
'''called in idle time'''
try:
datagram = self.port.recvfrom(self.BUFFER_SIZE)
data = json.loads(datagram[0])
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return
raise
for key in data.keys():
self.data[key] = data[key]
try:
self.master.mav.gps_input_send(
self.data['time_usec'],
self.data['gps_id'],
self.data['ignore_flags'],
self.data['time_week_ms'],
self.data['time_week'],
self.data['fix_type'],
self.data['lat'],
self.data['lon'],
self.data['alt'],
self.data['hdop'],
self.data['vdop'],
self.data['vn'],
self.data['ve'],
self.data['vd'],
self.data['speed_accuracy'],
self.data['horiz_accuracy'],
self.data['vert_accuracy'],
self.data['satellites_visible'])
except Exception as e:
print("GPS Input Failed:", e)
def cmd_port(self, args):
'handle port selection'
if len(args) != 1:
print("Usage: port <number>")
return
self.port.close()
self.portnum = int(args[0])
self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.port.bind((self.ip, self.portnum))
self.port.setblocking(0)
mavutil.set_close_on_exec(self.port.fileno())
print("Listening for GPS INPUT packets on UDP://%s:%s" % (self.ip, self.portnum))
|
class GPSInputModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def idle_task(self):
'''called in idle time'''
pass
def cmd_port(self, args):
'''handle port selection'''
pass
| 4 | 2 | 28 | 2 | 25 | 7 | 3 | 0.24 | 1 | 4 | 0 | 0 | 3 | 5 | 3 | 41 | 100 | 13 | 85 | 14 | 81 | 20 | 41 | 13 | 37 | 5 | 2 | 2 | 8 |
7,069 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_HIL.py
|
MAVProxy.modules.mavproxy_HIL.HILModule
|
class HILModule(mp_module.MPModule):
def __init__(self, mpstate):
super(HILModule, self).__init__(mpstate, "HIL", "HIL simulation")
self.last_sim_send_time = time.time()
self.last_apm_send_time = time.time()
self.rc_channels_scaled = mavutil.mavlink.MAVLink_rc_channels_scaled_message(0, 0, 0, 0, -10000, 0, 0, 0, 0, 0, 0)
self.hil_state_msg = None
sim_in_address = ('127.0.0.1', 5501)
sim_out_address = ('127.0.0.1', 5502)
self.sim_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sim_in.bind(sim_in_address)
self.sim_in.setblocking(0)
self.sim_out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sim_out.connect(sim_out_address)
self.sim_out.setblocking(0)
# HIL needs very fast idle loop calls
if self.settings.select_timeout > 0.001:
self.settings.select_timeout = 0.001
def unload(self):
'''unload module'''
self.sim_in.close()
self.sim_out.close()
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'RC_CHANNELS_SCALED':
self.rc_channels_scaled = m
def idle_task(self):
'''called from main loop'''
self.check_sim_in()
self.check_sim_out()
self.check_apm_out()
def check_sim_in(self):
'''check for FDM packets from runsim'''
try:
pkt = self.sim_in.recv(17*8 + 4)
except socket.error as e:
if not e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
raise
return
if len(pkt) != 17*8 + 4:
# wrong size, discard it
print("wrong size %u" % len(pkt))
return
(latitude, longitude, altitude, heading, v_north, v_east, v_down,
ax, ay, az,
phidot, thetadot, psidot,
roll, pitch, yaw,
vcas, check) = struct.unpack('<17dI', pkt)
(p, q, r) = self.convert_body_frame(radians(roll), radians(pitch), radians(phidot), radians(thetadot), radians(psidot))
try:
self.hil_state_msg = self.master.mav.hil_state_encode(int(time.time()*1e6),
radians(roll),
radians(pitch),
radians(yaw),
p,
q,
r,
int(latitude*1.0e7),
int(longitude*1.0e7),
int(altitude*1.0e3),
int(v_north*100),
int(v_east*100),
0,
int(ax*1000/9.81),
int(ay*1000/9.81),
int(az*1000/9.81))
except Exception:
return
def check_sim_out(self):
'''check if we should send new servos to flightgear'''
now = time.time()
if now - self.last_sim_send_time < 0.02 or self.rc_channels_scaled is None:
return
self.last_sim_send_time = now
servos = []
for ch in range(1,9):
servos.append(self.scale_channel(ch, getattr(self.rc_channels_scaled, 'chan%u_scaled' % ch)))
servos.extend([0,0,0, 0,0,0])
buf = struct.pack('<14H', *servos)
try:
self.sim_out.send(buf)
except socket.error as e:
if not e.errno in [ errno.ECONNREFUSED ]:
raise
return
def check_apm_out(self):
'''check if we should send new data to the APM'''
now = time.time()
if now - self.last_apm_send_time < 0.02:
return
self.last_apm_send_time = now
if self.hil_state_msg is not None:
self.master.mav.send(self.hil_state_msg)
def convert_body_frame(self, phi, theta, phiDot, thetaDot, psiDot):
'''convert a set of roll rates from earth frame to body frame'''
p = phiDot - psiDot*math.sin(theta)
q = math.cos(phi)*thetaDot + math.sin(phi)*psiDot*math.cos(theta)
r = math.cos(phi)*psiDot*math.cos(theta) - math.sin(phi)*thetaDot
return (p, q, r)
def scale_channel(self, ch, value):
'''scale a channel to 1000/1500/2000'''
v = value/10000.0
if v < -1:
v = -1
elif v > 1:
v = 1
if ch == 3 and self.mpstate.vehicle_type != 'rover':
if v < 0:
v = 0
return int(1000 + v*1000)
return int(1500 + v*500)
|
class HILModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def unload(self):
'''unload module'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def idle_task(self):
'''called from main loop'''
pass
def check_sim_in(self):
'''check for FDM packets from runsim'''
pass
def check_sim_out(self):
'''check if we should send new servos to flightgear'''
pass
def check_apm_out(self):
'''check if we should send new data to the APM'''
pass
def convert_body_frame(self, phi, theta, phiDot, thetaDot, psiDot):
'''convert a set of roll rates from earth frame to body frame'''
pass
def scale_channel(self, ch, value):
'''scale a channel to 1000/1500/2000'''
pass
| 10 | 8 | 13 | 1 | 11 | 1 | 3 | 0.1 | 1 | 5 | 0 | 0 | 9 | 6 | 9 | 47 | 128 | 17 | 101 | 36 | 91 | 10 | 81 | 30 | 71 | 5 | 2 | 2 | 25 |
7,070 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_OpenDroneID.py
|
MAVProxy.modules.mavproxy_OpenDroneID.OpenDroneIDModule
|
class OpenDroneIDModule(mp_module.MPModule):
def __init__(self, mpstate):
super(OpenDroneIDModule, self).__init__(mpstate, "OpenDroneID", "OpenDroneID Support", public = True)
self.add_command('opendroneid', self.cmd_opendroneid, "opendroneid control",
["<status>", "set (OPENDRONEIDSETTING)", "vehicle set (OPENDRONEIDVEHICLESETTING)"])
from MAVProxy.modules.lib.mp_settings import MPSetting
self.OpenDroneID_settings = mp_settings.MPSettings([
MPSetting("rate_hz", float, 0.1),
MPSetting("location_rate_hz", float, 1.0),
# BASIC_ID
MPSetting("UAS_ID_type", int, 0, choice=[("None",0), ("SerialNumber",1), ("CAA", 2), ("UTM_ASSIGNED", 3), ("SessionID", 4)]),
MPSetting("UAS_ID", str, ""),
MPSetting("UA_type", int, 0, choice=[("None",0), ("Aeroplane",1), ("HeliOrMulti",2),
("GyroPlane",3), ("HybridLift",4), ("Ornithopter",5),
("Glider",6), ("Kite",7), ("FreeBalloon",8), ("CaptiveBalloon",9),
("Airship", 10), ("Parachute",11), ("Rocket",12),
("TetheredPowered", 13), ("GroundObstacle", 14)]),
# SELF_ID
MPSetting("description_type", int, 0, choice=[("Text",0), ("Emergency",1), ("ExtendedStatus", 2)]),
MPSetting("description", str, ""),
# SYSTEM
MPSetting("area_count", int, 1),
MPSetting("area_radius", int, 0),
MPSetting("area_ceiling", int, -1000),
MPSetting("area_floor", int, -1000),
MPSetting("category_eu", int, 0, choice=[("Undeclared",0), ("Open",1), ("Specific",2), ("Certified",3)]),
MPSetting("class_eu", int, 0),
MPSetting("classification_type", int, 0, choice=[("Undeclared",0),("EU",1)]),
# OPERATOR_ID
MPSetting("operator_location_type", int, 0, choice=[("Takeoff",0),("LiveGNSS",1),("Fixed",2)]),
MPSetting("operator_id_type", int, 0),
MPSetting("operator_id", str, ""),
])
self.OpenDroneID_vehicle_settings = mp_settings.MPSettings([
MPSetting("UAS_ID", str, ""),
MPSetting("lock_id", int, 0),
])
self.add_completion_function('(OPENDRONEIDSETTING)',
self.OpenDroneID_settings.completion)
self.add_completion_function('(OPENDRONEIDVEHICLESETTING)',
self.OpenDroneID_vehicle_settings.completion)
self.last_send_s = time.time()
self.last_loc_send_s = time.time()
self.next_msg = 0
self.operator_latitude = 0
self.operator_longitude = 0
self.operator_altitude_geo = 0
def cmd_opendroneid(self, args):
'''opendroneid command parser'''
usage = "usage: opendroneid <vehicle> <set>"
if len(args) == 0:
print(usage)
return
if args[0] == "vehicle":
if args[1] == "set":
self.OpenDroneID_vehicle_settings.command(args[2:])
return
else:
print(usage)
if args[0] == "set":
self.OpenDroneID_settings.command(args[1:])
else:
print(usage)
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def send_basic_id(self):
'''send BASIC_ID'''
self.master.mav.open_drone_id_basic_id_send(
self.target_system,
self.target_component,
self.id_or_mac(),
self.OpenDroneID_settings.UAS_ID_type,
self.OpenDroneID_settings.UA_type,
self.to_bytes(self.OpenDroneID_settings.UAS_ID, 20))
def send_system(self):
'''send SYSTEM'''
if self.mpstate.position is not None:
pos = self.mpstate.position
if pos.latitude is not None:
self.operator_latitude = pos.latitude
self.operator_longitude = pos.longitude
if pos.altitude is not None:
self.operator_altitude_geo = pos.altitude
self.master.mav.open_drone_id_system_send(
self.target_system,
self.target_component,
self.id_or_mac(),
self.OpenDroneID_settings.operator_location_type,
self.OpenDroneID_settings.classification_type,
int(self.operator_latitude*1.0e7),
int(self.operator_longitude*1.0e7),
self.OpenDroneID_settings.area_count,
self.OpenDroneID_settings.area_radius,
self.OpenDroneID_settings.area_ceiling,
self.OpenDroneID_settings.area_floor,
self.OpenDroneID_settings.category_eu,
self.OpenDroneID_settings.class_eu,
self.operator_altitude_geo,
self.timestamp_2019())
def send_system_update(self):
'''send SYSTEM_UPDATE'''
if self.mpstate.position is not None:
pos = self.mpstate.position
if pos.latitude is not None:
self.operator_latitude = pos.latitude
self.operator_longitude = pos.longitude
if pos.altitude is not None:
self.operator_altitude_geo = pos.altitude
self.master.mav.open_drone_id_system_update_send(
self.target_system,
self.target_component,
int(self.operator_latitude*1.0e7),
int(self.operator_longitude*1.0e7),
self.operator_altitude_geo,
self.timestamp_2019())
def send_self_id(self):
'''send SELF_ID'''
self.master.mav.open_drone_id_self_id_send(
self.target_system,
self.target_component,
self.id_or_mac(),
self.OpenDroneID_settings.description_type,
self.to_string(self.OpenDroneID_settings.description, 23))
def send_operator_id(self):
'''send OPERATOR_ID'''
self.master.mav.open_drone_id_operator_id_send(
self.target_system,
self.target_component,
self.id_or_mac(),
self.OpenDroneID_settings.operator_id_type,
self.to_string(self.OpenDroneID_settings.operator_id, 20))
def to_string(self, s, maxlen):
return s.encode("utf-8")
def to_bytes(self, s, maxlen):
b = bytearray(s.encode("utf-8"))
b = b[:maxlen]
if len(b) < maxlen:
b.extend(bytearray([0]*(maxlen-len(b))))
return b
def id_or_mac(self):
return self.to_bytes("", 20)
def timestamp_2019(self):
jan_1_2019_s = 1546261200
return int(time.time() - jan_1_2019_s)
def idle_task(self):
'''called on idle'''
now = time.time()
if len(self.OpenDroneID_vehicle_settings.UAS_ID) != 0:
# convert to bytes
UAS_ID_Bytes = self.to_bytes(self.OpenDroneID_vehicle_settings.UAS_ID, 16)
uas_id_len = self.param_set("DID_ID_LEN", len(self.OpenDroneID_vehicle_settings.UAS_ID))
if self.get_mav_param("DID_ID_LEN") != uas_id_len:
self.param_set("DID_ID_LEN", len(self.OpenDroneID_vehicle_settings.UAS_ID))
for i in range(8):
if self.get_mav_param("DID_ID{}".format(i)) != (UAS_ID_Bytes[2*i] | (UAS_ID_Bytes[2*i+1] << 8)):
print("DID_ID{}".format(i), " {:x}{:x}".format(UAS_ID_Bytes[i+1] , UAS_ID_Bytes[i]))
self.param_set("DID_ID{}".format(i), UAS_ID_Bytes[2*i] | (UAS_ID_Bytes[2*i+1] << 8))
if now - self.last_loc_send_s > 1.0/self.OpenDroneID_settings.location_rate_hz:
self.last_loc_send_s = now
self.send_system_update()
if now - self.last_send_s > (1.0/self.OpenDroneID_settings.rate_hz)/4:
self.last_send_s = now
if self.next_msg == 0:
self.send_basic_id()
elif self.next_msg == 1:
self.send_system()
elif self.next_msg == 2:
self.send_self_id()
elif self.next_msg == 3:
self.send_operator_id()
self.next_msg = (self.next_msg + 1) % 4
|
class OpenDroneIDModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def cmd_opendroneid(self, args):
'''opendroneid command parser'''
pass
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
pass
def send_basic_id(self):
'''send BASIC_ID'''
pass
def send_system(self):
'''send SYSTEM'''
pass
def send_system_update(self):
'''send SYSTEM_UPDATE'''
pass
def send_self_id(self):
'''send SELF_ID'''
pass
def send_operator_id(self):
'''send OPERATOR_ID'''
pass
def to_string(self, s, maxlen):
pass
def to_bytes(self, s, maxlen):
pass
def id_or_mac(self):
pass
def timestamp_2019(self):
pass
def idle_task(self):
'''called on idle'''
pass
| 14 | 8 | 13 | 0 | 12 | 1 | 3 | 0.08 | 1 | 8 | 2 | 0 | 13 | 8 | 13 | 51 | 188 | 16 | 159 | 32 | 144 | 13 | 89 | 32 | 74 | 11 | 2 | 3 | 34 |
7,071 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SIYI/__init__.py
|
MAVProxy.modules.mavproxy_SIYI.DF_logger
|
class DF_logger:
'''write to a DF format log'''
def __init__(self, filename):
self.outf = open(filename,'wb')
self.outf.write(bytes([0]))
self.outf.flush()
self.mlog = DFReader.DFReader_binary(filename)
self.outf.seek(0)
self.formats = {}
self.last_flush = time.time()
def write(self, name, fmt, fields, *args):
if not name in self.formats:
self.formats[name] = self.mlog.add_format(DFReader.DFFormat(0, name, 0, fmt, fields))
self.outf.write(self.mlog.make_format_msgbuf(self.formats[name]))
nfields = len(fields.split(','))
if nfields <= 14:
self.outf.write(self.mlog.make_msgbuf(self.formats[name], args))
now = time.time()
if now - self.last_flush > 5:
self.last_flush = now
self.outf.flush()
|
class DF_logger:
'''write to a DF format log'''
def __init__(self, filename):
pass
def write(self, name, fmt, fields, *args):
pass
| 3 | 1 | 10 | 0 | 10 | 0 | 3 | 0.05 | 0 | 1 | 0 | 0 | 2 | 4 | 2 | 2 | 22 | 1 | 20 | 9 | 17 | 1 | 20 | 9 | 17 | 4 | 0 | 1 | 5 |
7,072 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SIYI/__init__.py
|
MAVProxy.modules.mavproxy_SIYI.PI_controller
|
class PI_controller:
'''simple PI controller'''
def __init__(self, settings, Pgain, Igain, IMAX):
self.Pgain = Pgain
self.Igain = Igain
self.IMAX = IMAX
self.I = 0.0
self.settings = settings
self.last_t = time.time()
def run(self, err, ff_rate):
now = time.time()
dt = now - self.last_t
if now - self.last_t > 1.0:
self.reset_I()
dt = 0
self.last_t = now
P = self.settings.get(self.Pgain) * self.settings.gain_mul
I = self.settings.get(self.Igain) * self.settings.gain_mul
IMAX = self.settings.get(self.IMAX)
max_rate = self.settings.max_rate
out = P*err
saturated = err > 0 and (out + self.I) >= max_rate
saturated |= err < 0 and (out + self.I) <= -max_rate
if not saturated:
self.I += I*err*dt
self.I = mp_util.constrain(self.I, -IMAX, IMAX)
ret = out + self.I + ff_rate
return mp_util.constrain(ret, -max_rate, max_rate)
def reset_I(self):
self.I = 0
|
class PI_controller:
'''simple PI controller'''
def __init__(self, settings, Pgain, Igain, IMAX):
pass
def run(self, err, ff_rate):
pass
def reset_I(self):
pass
| 4 | 1 | 10 | 0 | 9 | 0 | 2 | 0.03 | 0 | 0 | 0 | 0 | 3 | 6 | 3 | 3 | 33 | 3 | 29 | 19 | 25 | 1 | 29 | 19 | 25 | 3 | 0 | 1 | 5 |
7,073 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SIYI/__init__.py
|
MAVProxy.modules.mavproxy_SIYI.SIYIModule
|
class SIYIModule(mp_module.MPModule):
def __init__(self, mpstate):
super(SIYIModule, self).__init__(mpstate, "SIYI", "SIYI camera support")
self.add_command('siyi', self.cmd_siyi, "SIYI camera control",
["<rates|connect|autofocus|zoom|yaw|pitch|center|getconfig|angle|photo|recording|lock|follow|fpv|settarget|notarget|thermal|rgbview|tempsnap|get_thermal_mode|thermal_gain|get_thermal_gain|settime>",
"<therm_getenv|therm_set_distance|therm_set_emissivity|therm_set_humidity|therm_set_airtemp|therm_set_reftemp|therm_getswitch|therm_setswitch>",
"<therm_getthresholds|therm_getthreshswitch|therm_setthresholds|therm_setthreshswitch>",
"set (SIYISETTING)",
"imode <1|2|3|4|5|6|7|8|wide|zoom|split>",
"palette <WhiteHot|Sepia|Ironbow|Rainbow|Night|Aurora|RedHot|Jungle|Medical|BlackHot|GloryHot>",
"thermal_mode <0|1>",
])
# filter_dist is distance in metres
self.siyi_settings = mp_settings.MPSettings([("port", int, 37260),
('ip', str, "192.168.144.25"),
('yaw_rate', float, 10),
('pitch_rate', float, 10),
('rates_hz', float, 5),
('gain_mul', float, 1.0),
('yaw_gain_P', float, 1),
('yaw_gain_I', float, 1),
('yaw_gain_IMAX', float, 5),
('pitch_gain_P', float, 1),
('pitch_gain_I', float, 1),
('pitch_gain_IMAX', float, 5),
('mount_pitch', float, 0),
('mount_yaw', float, 0),
('lag', float, 0),
('target_rate', float, 10),
('telem_rate', float, 4),
('att_send_hz', float, 10),
('mode_hz', float, 0),
('temp_hz', float, 5),
('rtsp_rgb', str, 'rtsp://192.168.144.25:8554/video1'),
('rtsp_thermal', str, 'rtsp://192.168.144.25:8554/video2'),
#('rtsp_rgb', str, 'rtsp://127.0.0.1:8554/video1'),
#('rtsp_thermal', str, 'rtsp://127.0.0.1:8554/video2'),
('fps_thermal', int, 20),
('fps_rgb', int, 20),
('logfile', str, 'SIYI_log.bin'),
('thermal_fov', float, 24.2),
('zoom_fov', float, 62.0),
('wide_fov', float, 88.0),
('use_lidar', int, 0),
('use_encoders', int, 0),
('max_rate', float, 30.0),
('track_size_pct', float, 5.0),
('threshold_temp', int, 50),
('threshold_min', int, 240),
('los_correction', int, 0),
('att_control', int, 0),
('therm_cap_rate', float, 0),
('show_horizon', int, 0),
('autoflag_temp', float, 120),
('autoflag_enable', bool, False),
('autoflag_dist', float, 30),
('autoflag_history', float, 50),
('autoflag_slices', int, 4),
('track_ROI', int, 1),
('fetch_timeout', float, 2.0),
MPSetting('thresh_climit', int, 50, range=(10,50)),
MPSetting('thresh_volt', int, 80, range=(20,80)),
MPSetting('thresh_ang', int, 4000, range=(30,4000)),
MPSetting('thresh_climit_dis', int, 20, range=(10,50)),
MPSetting('thresh_volt_dis', int, 40, range=(20,80)),
MPSetting('thresh_ang_dis', int, 40, range=(30,4000)),
('force_strong_gimballing', bool, False),
('stow_on_landing', bool, True),
('stow_heuristics_enabled', bool, True),
('stow_heuristics_minalt', float, 20.0), # metres above terrain
('stow_heuristics_maxhorvel', float, 2.0), # metres/second
])
self.add_completion_function('(SIYISETTING)',
self.siyi_settings.completion)
self.sock = None
self.yaw_rate = None
self.pitch_rate = None
self.sequence = 0
self.last_req_send = time.time()
self.last_version_send = time.time()
self.have_version = False
self.console.set_status('SIYI', 'SIYI - -', row=6)
self.console.set_status('TEMP', 'TEMP -/-', row=6)
self.yaw_end = None
self.pitch_end = None
self.rf_dist = 0
self.attitude = (0,0,0,0,0,0)
self.encoders = (0,0,0)
self.voltages = None
self.tmax = -1
self.tmin = -1
self.spot_temp = -1
self.tmax_x = None
self.tmax_y = None
self.tmin_x = None
self.tmin_y = None
self.last_temp_t = None
self.last_att_t = time.time()
self.att_dt_lpf = 1.0
self.last_rf_t = None
self.last_enc_t = None
self.last_enc_recv_t = time.time()
self.last_volt_t = None
self.last_mode_t = time.time()
self.last_thresh_t = None
self.last_thresh_send_t = None
self.GLOBAL_POSITION_INT = None
self.ATTITUDE = None
self.target_pos = None
self.last_map_ROI = None
self.icon = self.mpstate.map.icon('camera-small-red.png')
self.click_icon = self.mpstate.map.icon('flag.png')
self.last_target_send = time.time()
self.last_rate_display = time.time()
self.yaw_controller = PI_controller(self.siyi_settings, 'yaw_gain_P', 'yaw_gain_I', 'yaw_gain_IMAX')
self.pitch_controller = PI_controller(self.siyi_settings, 'pitch_gain_P', 'pitch_gain_I', 'pitch_gain_IMAX')
self.logf = DF_logger(os.path.join(self.logdir, self.siyi_settings.logfile))
self.start_time = time.time()
self.last_att_send_t = time.time()
self.last_temp_t = time.time()
self.thermal_view = None
self.rawthermal_view = None
self.rgb_view = None
self.last_zoom = 1.0
self.rgb_lens = "wide"
self.bad_crc = 0
self.control_mode = -1
self.last_SIEA = time.time()
self.last_therm_cap = time.time()
self.thermal_capture_count = 0
self.last_therm_mode = time.time()
self.named_float_seq = 0
self.recv_thread = Thread(target=self.receive_thread, name='SIYI_Receive')
self.recv_thread.daemon = True
self.recv_thread.start()
self.have_horizon_lines = False
self.thermal_param = None
self.last_armed = False
self.getconfig_pending = False
self.last_getconfig = time.time()
self.click_mode = "Flag"
# support for stowing the camera when we start to land:
self.extended_sys_state_received_time = 0
self.extended_sys_state_request_time = 0
self.extended_sys_state_warn_time = 0 # last time we warned about not being able to auto-stow
self.last_landed_state = None
# support retracting camera based on heuristics:
self.landing_heuristics = {
"armed": True,
"last_warning_ms": 0,
"current_terrain_alt": 0,
}
if mp_util.has_wxpython:
menu = MPMenuSubMenu('SIYI',
items=[
MPMenuItem('Center', 'Center', '# siyi center '),
MPMenuItem('ModeFollow', 'ModeFollow', '# siyi follow '),
MPMenuItem('ModeLock', 'ModeLock', '# siyi lock '),
MPMenuItem('ModeFPV', 'ModeFPV', '# siyi fpv '),
MPMenuItem('GetConfig', 'GetConfig', '# siyi getconfig '),
MPMenuItem('TakePhoto', 'TakePhoto', '# siyi photo '),
MPMenuItem('AutoFocus', 'AutoFocus', '# siyi autofocus '),
MPMenuItem('ImageSplit', 'ImageSplit', '# siyi imode split '),
MPMenuItem('ImageWide', 'ImageWide', '# siyi imode wide '),
MPMenuItem('ImageZoom', 'ImageZoom', '# siyi imode zoom '),
MPMenuItem('Recording', 'Recording', '# siyi recording '),
MPMenuItem('ClearTarget', 'ClearTarget', '# siyi notarget '),
MPMenuItem('ThermalView', 'Thermalview', '# siyi thermal '),
MPMenuItem('RawThermalView', 'RawThermalview', '# siyi rawthermal '),
MPMenuItem('RGBView', 'RGBview', '# siyi rgbview '),
MPMenuItem('ResetAttitude', 'ResetAttitude', '# siyi resetattitude '),
MPMenuSubMenu('Zoom',
items=[MPMenuItem('Zoom%u'%z, 'Zoom%u'%z, '# siyi zoom %u ' % z) for z in range(1,11)]),
MPMenuSubMenu('ThermalGain',
items=[MPMenuItem('HighGain', 'HighGain', '# siyi thermal_gain 1'),
MPMenuItem('LowGain', 'LowGain', '# siyi thermal_gain 0')]),
MPMenuSubMenu('Threshold',
items=[MPMenuItem('Threshold%u'%z, 'Threshold%u'%z, '# siyi set threshold_temp %u ' % z) for z in range(20,115,5)])])
map = self.module('map')
if map is not None:
map.add_menu(menu)
console = self.module('console')
if console is not None:
console.add_menu(menu)
def micros64(self):
return int((time.time()-self.start_time)*1.0e6)
def millis32(self):
return int((time.time()-self.start_time)*1.0e3)
def cmd_siyi(self, args):
'''siyi command parser'''
usage = "usage: siyi <set|rates>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
self.siyi_settings.command(args[1:])
elif args[0] == "connect":
self.cmd_connect()
elif args[0] == "rates":
self.cmd_rates(args[1:])
elif args[0] == "yaw":
self.cmd_yaw(args[1:])
elif args[0] == "pitch":
self.cmd_pitch(args[1:])
elif args[0] == "imode":
self.cmd_imode(args[1:])
elif args[0] == "autofocus":
self.send_packet_fmt(AUTO_FOCUS, "<B", 1)
elif args[0] == "center":
self.send_packet_fmt(CENTER, "<B", 1)
self.clear_target()
elif args[0] == "zoom":
self.cmd_zoom(args[1:])
elif args[0] == "getconfig":
self.send_packet(ACQUIRE_GIMBAL_CONFIG_INFO, None)
self.getconfig_pending = False
elif args[0] == "angle":
self.cmd_angle(args[1:])
elif args[0] == "photo":
self.send_packet_fmt(PHOTO, "<B", 0)
elif args[0] == "tempsnap":
self.send_packet_fmt(GET_TEMP_FRAME, None)
elif args[0] == "thermal_mode":
self.send_packet_fmt(SET_THERMAL_MODE, "<B", int(args[1]))
elif args[0] == "get_thermal_mode":
self.send_packet_fmt(GET_THERMAL_MODE, None)
elif args[0] == "get_thermal_gain":
self.send_packet_fmt(GET_THERMAL_GAIN, None)
elif args[0] == "thermal_gain":
self.send_packet_fmt(SET_THERMAL_GAIN, "<B", int(args[1]))
elif args[0] == "recording":
self.send_packet_fmt(PHOTO, "<B", 2)
self.send_packet(FUNCTION_FEEDBACK_INFO, None)
print("Toggled recording")
elif args[0] == "resetattitude":
self.send_packet(RESET_ATTITUDE, None)
elif args[0] == "lock":
self.send_packet_fmt(PHOTO, "<B", 3)
elif args[0] == "follow":
self.send_packet_fmt(PHOTO, "<B", 4)
self.clear_target()
elif args[0] == "fpv":
self.send_packet_fmt(PHOTO, "<B", 5)
self.clear_target()
elif args[0] == "settarget":
self.cmd_settarget(args[1:])
elif args[0] == "notarget":
self.clear_target()
elif args[0] == "palette":
self.cmd_palette(args[1:])
elif args[0] == "thermal":
self.cmd_thermal()
elif args[0] == "rawthermal":
self.cmd_rawthermal()
elif args[0] == "rgbview":
self.cmd_rgbview()
elif args[0] == "therm_getenv":
self.send_packet_fmt(GET_THERMAL_PARAM, None)
elif args[0] == "therm_set_distance":
self.therm_set_distance(float(args[1]))
elif args[0] == "therm_set_humidity":
self.therm_set_humidity(float(args[1]))
elif args[0] == "therm_set_emissivity":
self.therm_set_emissivity(float(args[1]))
elif args[0] == "therm_set_airtemp":
self.therm_set_airtemp(float(args[1]))
elif args[0] == "therm_set_reftemp":
self.therm_set_reftemp(float(args[1]))
elif args[0] == "therm_getswitch":
self.send_packet_fmt(GET_THERMAL_ENVSWITCH, None)
elif args[0] == "therm_setswitch":
self.send_packet_fmt(SET_THERMAL_ENVSWITCH, "<B", int(args[1]))
elif args[0] == "therm_getthreshswitch":
self.send_packet_fmt(GET_THERMAL_THRESH_STATE, None)
elif args[0] == "therm_setthreshswitch":
self.send_packet_fmt(SET_THERMAL_THRESH_STATE, "<B", int(args[1]))
elif args[0] == "therm_getthresholds":
self.send_packet_fmt(GET_THERMAL_THRESH, None)
elif args[0] == "therm_setthresholds":
self.therm_set_thresholds(args[1:])
elif args[0] == "settime":
self.cmd_settime()
else:
print(usage)
def cmd_connect(self):
'''connect to the camera'''
self.sock = None
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.connect((self.siyi_settings.ip, self.siyi_settings.port))
sock.setblocking(True)
self.sock = sock
print("Connected to SIYI")
def cmd_rates(self, args):
'''update rates'''
if len(args) < 2:
print("Usage: siyi rates PAN_RATE PITCH_RATE")
return
self.clear_target()
self.yaw_rate = float(args[0])
self.pitch_rate = float(args[1])
def cmd_yaw(self, args):
'''update yaw'''
if len(args) < 1:
print("Usage: siyi yaw ANGLE")
return
angle = float(args[0])
self.yaw_rate = self.siyi_settings.yaw_rate
self.yaw_end = time.time() + abs(angle)/self.yaw_rate
if angle < 0:
self.yaw_rate = -self.yaw_rate
def cmd_pitch(self, args):
'''update pitch'''
if len(args) < 1:
print("Usage: siyi pitch ANGLE")
return
angle = float(args[0])
self.pitch_rate = self.siyi_settings.pitch_rate
self.pitch_end = time.time() + abs(angle)/self.pitch_rate
if angle < 0:
self.pitch_rate = -self.pitch_rate
def cmd_imode(self, args):
'''update image mode'''
if len(args) < 1:
print("Usage: siyi imode MODENUM")
return
imode_map = { "wide" : 5, "zoom" : 3, "split" : 2 }
self.rgb_lens = args[0]
mode = imode_map.get(self.rgb_lens,None)
if mode is None:
mode = int(args[0])
self.send_packet_fmt(SET_IMAGE_TYPE, "<B", mode)
print("Lens: %s" % args[0])
def cmd_palette(self, args):
'''update thermal palette'''
if len(args) < 1:
print("Usage: siyi palette PALETTENUM")
return
pal_map = { "WhiteHot" : 0, "Sepia" : 2, "Ironbow" : 3, "Rainbow" : 4,
"Night" : 5, "Aurora" : 6, "RedHot" : 7, "Jungle" : 8 , "Medical" : 9,
"BlackHot" : 10, "GloryHot" : 11}
pal = pal_map.get(args[0],None)
if pal is None:
pal = int(args[0])
self.send_packet_fmt(SET_THERMAL_PALETTE, "<B", pal)
def cmd_settime(self):
'''set camera time'''
t_us = int(time.time()*1.0e6)
self.send_packet_fmt(SET_TIME, "<Q", t_us)
def video_filename(self, base):
'''get a video file name'''
if self.logdir is None:
return base + ".mts"
i = 1
while True:
vidfile = os.path.join(self.logdir, "%s%u.mts" % (base,i))
if not os.path.exists(vidfile):
self.logf.write('SIVI', 'QBB', 'TimeUS,Type,Idx',
self.micros64(),
1 if base=='thermal' else 0,
i)
break
i += 1
return vidfile, i
def cmd_thermal(self):
'''open thermal viewer'''
vidfile,idx = self.video_filename('thermal')
self.thermal_view = CameraView(self, self.siyi_settings.rtsp_thermal,
vidfile, (640,512), thermal=True,
fps=self.siyi_settings.fps_thermal,
video_idx=idx)
def cmd_rawthermal(self):
'''open raw thermal viewer'''
self.rawthermal_view = RawThermal(self, (640,512))
def cmd_rgbview(self):
'''open rgb viewer'''
vidfile,idx = self.video_filename('rgb')
self.rgb_view = CameraView(self, self.siyi_settings.rtsp_rgb,
vidfile, (1280,720), thermal=False,
fps=self.siyi_settings.fps_rgb,
video_idx=idx)
def check_thermal_events(self):
'''check for mouse events on thermal image'''
if self.thermal_view is not None:
self.thermal_view.check_events()
if self.rawthermal_view is not None:
self.rawthermal_view.check_events()
if self.rgb_view is not None:
self.rgb_view.check_events()
def log_frame_counter(self, video_idx, thermal, frame_counter):
'''log video frame counter'''
self.logf.write('SIFC', 'QBBI', 'TimeUS,Type,Idx,Frame',
self.micros64(),
1 if thermal else 0,
video_idx,
frame_counter)
def cmd_zoom(self, args):
'''set zoom'''
if len(args) < 1:
print("Usage: siyi zoom ZOOM")
return
self.last_zoom = float(args[0])
ival = int(self.last_zoom)
frac = int((self.last_zoom - ival)*10)
self.send_packet_fmt(ABSOLUTE_ZOOM, "<BB", ival, frac)
def set_target(self, lat, lon, alt):
'''set target position'''
self.target_pos = (lat, lon, alt)
self.mpstate.map.add_object(mp_slipmap.SlipIcon('SIYI',
(lat, lon),
self.icon, layer='SIYI', rotation=0, follow=False))
def therm_set_distance(self, distance):
'''set thermal distance'''
if self.thermal_param is None:
print("Run therm_getenv first")
return
p = copy.copy(self.thermal_param)
p.distance = distance
self.send_packet_fmt(SET_THERMAL_PARAM, "<HHHHH", *p.args())
def therm_set_emissivity(self, emissivity):
'''set thermal emissivity'''
if self.thermal_param is None:
print("Run therm_getenv first")
return
p = copy.copy(self.thermal_param)
p.target_emissivity = emissivity
self.send_packet_fmt(SET_THERMAL_PARAM, "<HHHHH", *p.args())
def therm_set_humidity(self, humidity):
'''set thermal humidity'''
if self.thermal_param is None:
print("Run therm_getenv first")
return
p = copy.copy(self.thermal_param)
p.humidity = humidity
self.send_packet_fmt(SET_THERMAL_PARAM, "<HHHHH", *p.args())
def therm_set_airtemp(self, airtemp):
'''set thermal airtemp'''
if self.thermal_param is None:
print("Run therm_getenv first")
return
p = copy.copy(self.thermal_param)
p.air_temperature = airtemp
self.send_packet_fmt(SET_THERMAL_PARAM, "<HHHHH", *p.args())
def therm_set_reftemp(self, reftemp):
'''set thermal reftemp'''
if self.thermal_param is None:
print("Run therm_getenv first")
return
p = copy.copy(self.thermal_param)
p.reflection_temperature = reftemp
self.send_packet_fmt(SET_THERMAL_PARAM, "<HHHHH", *p.args())
def therm_set_thresholds(self, args):
'''set thermal thresholds
format: therm_setthresholds 30 102,204,255 40 102,204,255 50 102,204,255 80
'''
if len(args) != 7:
print("Usage: therm_setthresholds T1 R,G,B T2 R,G,B T3 R,G,B T4")
return
temps = [int(args[0]), int(args[2]), int(args[4]), int(args[6])]
colors = []
for i in [1,3,5]:
colors.append([int(x) for x in args[i].split(',')])
self.send_packet_fmt(SET_THERMAL_THRESH, "<BhhBBBBhhBBBBhhBBB",
1, temps[0], temps[1], *colors[0],
1, temps[1], temps[2], *colors[1],
1, temps[2], temps[3], *colors[2])
def clear_target(self):
'''clear target position'''
self.target_pos = None
self.mpstate.map.remove_object('SIYI')
self.end_tracking()
self.yaw_rate = None
self.pitch_rate = None
def cmd_angle(self, args):
'''set zoom'''
if len(args) < 1:
print("Usage: siyi angle YAW PITCH")
return
yaw = -float(args[0])
pitch = float(args[1])
self.target_pos = None
self.clear_target()
self.send_packet_fmt(SET_ANGLE, "<hh", int(yaw*10), int(pitch*10))
def send_rates(self):
'''send rates packet'''
now = time.time()
if self.siyi_settings.rates_hz <= 0 or now - self.last_req_send < 1.0/self.siyi_settings.rates_hz:
return
self.last_req_send = now
if self.yaw_rate is not None and self.pitch_rate is not None:
y = rate_mapping(self.yaw_rate)
p = rate_mapping(self.pitch_rate)
y = mp_util.constrain(y, -self.siyi_settings.max_rate, self.siyi_settings.max_rate)
p = mp_util.constrain(p, -self.siyi_settings.max_rate, self.siyi_settings.max_rate)
scale = 1.0
y = int(mp_util.constrain(y*scale, -100, 100))
p = int(mp_util.constrain(p*scale, -100, 100))
self.send_packet_fmt(GIMBAL_ROTATION, "<bb", y, p)
self.logf.write('SIGR', 'Qffbb', 'TimeUS,YRate,PRate,YC,PC',
self.micros64(), self.yaw_rate, self.pitch_rate, y, p)
self.send_named_float('YAW_RT', self.yaw_rate)
self.send_named_float('PITCH_RT', self.pitch_rate)
def cmd_settarget(self, args):
'''set target'''
click = self.mpstate.click_location
if click is None:
print("No map click position available")
return
lat = click[0]
lon = click[1]
alt = self.module('terrain').ElevationModel.GetElevation(lat, lon)
if alt is None:
print("No terrain for location")
return
self.set_target(lat, lon, alt)
def request_telem(self):
'''request telemetry'''
now = time.time()
if self.siyi_settings.temp_hz > 0 and now - self.last_temp_t >= 1.0/self.siyi_settings.temp_hz:
self.last_temp_t = now
self.send_packet_fmt(READ_TEMP_FULL_SCREEN, "<B", 2)
if self.last_att_t is None or now - self.last_att_t > 5:
self.last_att_t = now
self.send_packet_fmt(REQUEST_CONTINUOUS_DATA, "<BB", 1, self.siyi_settings.telem_rate)
if self.last_rf_t is None or now - self.last_rf_t > 10:
self.last_rf_t = now
self.send_packet_fmt(REQUEST_CONTINUOUS_DATA, "<BB", 2, 1)
if self.last_enc_t is None or now - self.last_enc_t > 5:
self.last_enc_t = now
self.send_packet_fmt(REQUEST_CONTINUOUS_DATA, "<BB", 3, self.siyi_settings.telem_rate)
if self.last_volt_t is None or now - self.last_volt_t > 5:
self.last_volt_t = now
self.send_packet_fmt(REQUEST_CONTINUOUS_DATA, "<BB", 4, self.siyi_settings.telem_rate)
if self.last_thresh_t is None or now - self.last_thresh_t > 10:
self.last_thresh_t = now
self.send_packet_fmt(READ_THRESHOLDS, None)
if self.siyi_settings.mode_hz > 0 and now - self.last_mode_t > 1.0/self.siyi_settings.mode_hz:
self.last_mode_t = now
self.send_packet_fmt(READ_CONTROL_MODE, None)
if self.siyi_settings.therm_cap_rate > 0 and now - self.last_therm_mode > 2:
self.last_therm_mode = now
self.send_packet_fmt(GET_THERMAL_MODE, None)
def send_attitude(self):
'''send attitude to gimbal'''
now = time.time()
if self.siyi_settings.att_send_hz <= 0 or now - self.last_att_send_t < 1.0/self.siyi_settings.att_send_hz:
return
self.last_att_send_t = now
att = self.master.messages.get('ATTITUDE',None)
if att is None:
return
self.send_packet_fmt(ATTITUDE_EXTERNAL, "<Iffffff",
self.millis32(),
att.roll, att.pitch, att.yaw,
att.rollspeed, att.pitchspeed, att.yawspeed)
def send_packet(self, command_id, pkt):
'''send SIYI packet'''
plen = len(pkt) if pkt else 0
buf = struct.pack("<BBBHHB", SIYI_HEADER1, SIYI_HEADER2, 1, plen,
self.sequence, command_id)
if pkt:
buf += pkt
buf += struct.pack("<H", crc16_from_bytes(buf))
self.sequence = (self.sequence+1) % 0xffff
try:
self.sock.send(buf)
except Exception:
pass
def send_packet_fmt(self, command_id, fmt, *args):
'''send SIYI packet'''
if fmt is None:
fmt = ""
args = []
try:
self.send_packet(command_id, struct.pack(fmt, *args))
except Exception as ex:
print(ex)
print(fmt, args)
return
args = list(args)
if len(args) > 8:
args = args[:8]
args.extend([0]*(8-len(args)))
self.logf.write('SIOU', 'QBffffffff', 'TimeUS,Cmd,P1,P2,P3,P4,P5,P6,P7,P8', self.micros64(), command_id, *args)
def unpack(self, command_id, fmt, data):
'''unpack SIYI data and log'''
fsize = struct.calcsize(fmt)
if fsize != len(data):
print("cmd 0x%02x needs %u bytes got %u" % (command_id, fsize, len(data)))
return None
v = struct.unpack(fmt, data[:fsize])
args = list(v)
args.extend([0]*(12-len(args)))
self.logf.write('SIIN', 'QBffffffffffff', 'TimeUS,Cmd,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12', self.micros64(), command_id, *args)
return v
def parse_data(self, pkt):
'''parse SIYI packet'''
while len(pkt) >= 10:
(h1,h2,rack,plen,seq,cmd) = struct.unpack("<BBBHHB", pkt[:8])
if plen+10 > len(pkt):
#print("SIYI: short packet", plen+10, len(pkt))
break
self.parse_packet(pkt[:plen+10])
pkt = pkt[plen+10:]
def parse_packet(self, pkt):
'''parse SIYI packet'''
(h1,h2,rack,plen,seq,cmd) = struct.unpack("<BBBHHB", pkt[:8])
data = pkt[8:-2]
crc, = struct.unpack("<H", pkt[-2:])
crc2 = crc16_from_bytes(pkt[:-2])
if crc != crc2:
self.bad_crc += 1
#print("SIYI: BAD CRC", crc, crc2, self.bad_crc)
return
if cmd == ACQUIRE_FIRMWARE_VERSION:
patch,minor,major,gpatch,gminor,gmajor,zpatch,zminor,zmajor,_,_,_ = self.unpack(cmd, "<BBBBBBBBBBBB", data)
self.have_version = True
print("SIYI CAM %u.%u.%u" % (major, minor, patch))
print("SIYI Gimbal %u.%u.%u" % (gmajor, gminor, gpatch))
print("SIYI Zoom %u.%u.%u" % (zmajor, zminor, zpatch))
# change to white hot
self.send_packet_fmt(SET_THERMAL_PALETTE, "<B", 0)
elif cmd == ACQUIRE_GIMBAL_ATTITUDE:
(z,y,x,sz,sy,sx) = self.unpack(cmd, "<hhhhhh", data)
now = time.time()
dt = now - self.last_att_t
self.att_dt_lpf = 0.95 * self.att_dt_lpf + 0.05 * max(dt,0.01)
self.last_att_t = now
(roll,pitch,yaw) = (x*0.1, y*0.1, mp_util.wrap_180(-z*0.1))
self.attitude = (roll,pitch,yaw, sx*0.1, sy*0.1, -sz*0.1)
self.send_named_float('CROLL', self.attitude[0])
self.send_named_float('CPITCH', self.attitude[1])
self.send_named_float('CYAW', self.attitude[2])
self.send_named_float('CROLL_RT', self.attitude[3])
self.send_named_float('CPITCH_RT', self.attitude[4])
self.send_named_float('CYAW_RT', self.attitude[5])
self.update_status()
self.logf.write('SIGA', 'Qffffffhhhhhh', 'TimeUS,Y,P,R,Yr,Pr,Rr,z,y,x,sz,sy,sx',
self.micros64(),
self.attitude[2], self.attitude[1], self.attitude[0],
self.attitude[5], self.attitude[4], self.attitude[3],
z,y,x,sz,sy,sx)
elif cmd == ACQUIRE_GIMBAL_CONFIG_INFO:
res, hdr_sta, res2, record_sta, gim_motion, gim_mount, video, x = self.unpack(cmd, "<BBBBBBBB", data)
self.console.set_status('REC', 'REC %u' % record_sta, row=6)
if self.getconfig_pending:
self.getconfig_pending = False
armed = self.master.motors_armed()
if armed and record_sta == 0:
print("Starting recording")
self.send_packet_fmt(PHOTO, "<B", 2)
if not armed and record_sta == 1:
print("Stopping recording")
self.send_packet_fmt(PHOTO, "<B", 2)
return
print("HDR: %u" % hdr_sta)
print("Recording: %u" % record_sta)
print("GimbalMotion: %u" % gim_motion)
print("GimbalMount: %u" % gim_mount)
print("Video: %u" % video)
print("Unknown: %u" % x)
elif cmd == READ_RANGEFINDER:
r, = self.unpack(cmd, "<H", data)
self.rf_dist = r * 0.1
self.last_rf_t = time.time()
self.update_status()
self.send_named_float('RFND', self.rf_dist)
SR = self.get_slantrange(0,0,1,1)
if SR is None:
SR = -1.0
self.logf.write('SIRF', 'Qff', 'TimeUS,Dist,SR',
self.micros64(),
self.rf_dist,
SR)
elif cmd == READ_ENCODERS:
y,p,r, = self.unpack(cmd, "<hhh", data)
self.last_enc_t = time.time()
self.last_enc_recv_t = time.time()
self.encoders = (r*0.1,p*0.1,-y*0.1)
self.send_named_float('ENC_R', self.encoders[0])
self.send_named_float('ENC_P', self.encoders[1])
self.send_named_float('ENC_Y', self.encoders[2])
self.logf.write('SIEN', 'Qfff', 'TimeUS,R,P,Y',
self.micros64(),
self.encoders[0], self.encoders[1], self.encoders[2])
if self.siyi_settings.show_horizon == 1:
self.have_horizon_lines = True
self.show_horizon_lines()
elif self.have_horizon_lines:
self.remove_horizon_lines()
self.have_horizon_lines = False
elif cmd == READ_VOLTAGES:
if len(data) == 11:
y,p,r,_,_,_ = self.unpack(cmd, "<hhhhhb", data)
else:
y,p,r = self.unpack(cmd, "<hhh", data)
self.last_volt_t = time.time()
self.voltages = (r*0.001,p*0.001,y*0.001)
self.send_named_float('VLT_R', self.voltages[0])
self.send_named_float('VLT_P', self.voltages[1])
self.send_named_float('VLT_Y', self.voltages[2])
self.logf.write('SIVL', 'Qfff', 'TimeUS,R,P,Y',
self.micros64(),
self.voltages[0], self.voltages[1], self.voltages[2])
elif cmd == READ_THRESHOLDS:
climit,volt_thresh,ang_thresh, = self.unpack(cmd, "<hhh", data)
self.last_thresh_t = time.time()
self.send_named_float('CLIMIT', climit)
self.send_named_float('VTHRESH', volt_thresh)
self.send_named_float('ATHRESH', ang_thresh)
self.logf.write('SITH', 'Qhhh', 'TimeUS,WLimit,VThresh,AErr',
self.micros64(),
climit, volt_thresh, ang_thresh)
do_strong_gimballing = self.master.motors_armed()
if self.siyi_settings.force_strong_gimballing:
do_strong_gimballing = True
if do_strong_gimballing:
new_thresh = (self.siyi_settings.thresh_climit,
self.siyi_settings.thresh_volt,
self.siyi_settings.thresh_ang)
weak_control = 0
else:
new_thresh = (self.siyi_settings.thresh_climit_dis,
self.siyi_settings.thresh_volt_dis,
self.siyi_settings.thresh_ang_dis)
weak_control = 1
if (climit != new_thresh[0] or volt_thresh != new_thresh[1] or ang_thresh != new_thresh[2]):
print("SIYI: Setting thresholds (%u,%u,%u) -> (%u,%u,%u)" %
(climit,volt_thresh,ang_thresh,new_thresh[0],new_thresh[1],new_thresh[2]))
self.send_packet_fmt(SET_THRESHOLDS, "<hhh",
new_thresh[0], new_thresh[1], new_thresh[2])
self.send_packet_fmt(SET_WEAK_CONTROL,"<B", weak_control)
elif cmd == READ_CONTROL_MODE:
self.control_mode, = self.unpack(cmd, "<B", data)
self.send_named_float('CMODE', self.control_mode)
self.logf.write('SIMO', 'QB', 'TimeUS,Mode',
self.micros64(), self.control_mode)
elif cmd == READ_TEMP_FULL_SCREEN:
if len(data) < 12:
print("READ_TEMP_FULL_SCREEN: Expected 12 bytes, got %u" % len(data))
return
self.tmax,self.tmin,self.tmax_x,self.tmax_y,self.tmin_x,self.tmin_y = self.unpack(cmd, "<HHHHHH", data)
self.tmax = self.tmax * 0.01
self.tmin = self.tmin * 0.01
self.send_named_float('TMIN', self.tmin)
self.send_named_float('TMAX', self.tmax)
self.last_temp_t = time.time()
frame_counter = -1 if self.thermal_view is None else self.thermal_view.frame_counter
self.logf.write('SITR', 'QffHHHHiI', 'TimeUS,TMin,TMax,TMinX,TMinY,TMaxX,TMaxY,FC,TCAP',
self.micros64(),
self.tmin, self.tmax,
self.tmin_x, self.tmin_y,
self.tmax_x, self.tmax_y,
frame_counter,
self.thermal_capture_count)
if self.thermal_view is not None:
threshold = self.siyi_settings.threshold_temp
threshold_value = int(255*(threshold - self.tmin)/max(1,(self.tmax-self.tmin)))
threshold_value = mp_util.constrain(threshold_value, 0, 255)
if self.tmax < threshold:
threshold_value = -1
else:
threshold_value = max(threshold_value, self.siyi_settings.threshold_min)
self.thermal_view.set_threshold(threshold_value)
elif cmd == FUNCTION_FEEDBACK_INFO:
info_type, = self.unpack(cmd, "<B", data)
feedback = {
0: "Success",
1: "FailPhoto",
2: "HDR ON",
3: "HDR OFF",
4: "FailRecord",
}
print("Feedback %s" % feedback.get(info_type, str(info_type)))
elif cmd == SET_THRESHOLDS:
ok, = self.unpack(cmd, "<B", data)
if ok != 1:
print("Threshold set failure")
elif cmd == SET_WEAK_CONTROL:
ok,weak_control, = self.unpack(cmd, "<BB", data)
if ok != 1:
print("Weak control set failure")
else:
print("Weak control is %u" % weak_control)
elif cmd == GET_THERMAL_MODE:
ok, = self.unpack(cmd,"<B", data)
if self.siyi_settings.therm_cap_rate > 0 and ok != 1:
print("ThermalMode: %u" % ok)
self.send_packet_fmt(SET_THERMAL_MODE, "<B", 1)
elif cmd == SET_THERMAL_MODE:
ok, = self.unpack(cmd,"<B", data)
print("SetThermalMode: %u" % ok)
elif cmd == SET_THERMAL_GAIN:
ok, = self.unpack(cmd,"<B", data)
print("SetThermalGain: %u" % ok)
elif cmd == GET_TEMP_FRAME:
ok, = self.unpack(cmd,"<B", data)
if ok:
self.thermal_capture_count += 1
elif cmd == GET_THERMAL_ENVSWITCH:
ok, = self.unpack(cmd,"<B", data)
print("ThermalEnvSwitch: %u" % ok)
elif cmd == SET_THERMAL_ENVSWITCH:
ok, = self.unpack(cmd,"<B", data)
print("ThermalEnvSwitch: %u" % ok)
elif cmd == SET_THERMAL_PARAM:
ok, = self.unpack(cmd,"<B", data)
print("SetThermalParam: %u" % ok)
elif cmd == GET_THERMAL_PARAM:
dist,emiss,humidity,airtemp,reftemp, = self.unpack(cmd,"<HHHHH", data)
self.thermal_param = ThermalParameters(dist*0.01, emiss*0.01, humidity*0.01, airtemp*0.01, reftemp*0.01)
print("ThermalParam: %s" % self.thermal_param)
elif cmd == SET_TIME:
ok, = self.unpack(cmd,"<B", data)
print("SetTime: %u" % ok)
elif cmd in [GET_THERMAL_THRESH_STATE, SET_THERMAL_THRESH_STATE]:
ok, = self.unpack(cmd,"<B", data)
print("ThermalThreshState: %u" % ok)
elif cmd in [SET_THERMAL_THRESH]:
ok, = self.unpack(cmd,"<B", data)
print("SetThermThresh: %u" % ok)
elif cmd == GET_THERMAL_THRESH:
sw1,t1min,t1max,r1,g1,b1,sw2,t2min,t2max,r2,g2,b2,sw3,t3min,t3max,r3,g3,b3, = self.unpack(cmd,"<BhhBBB BhhBBB BhhBBB", data)
print("ThermalThresh: %u(%d:%d %u,%u,%u) %u(%d:%d %u,%u,%u) %u(%d:%d %u,%u,%u)" % (
sw1,t1min,t1max,r1,g1,b1,sw2,t2min,t2max,r2,g2,b2,sw3,t3min,t3max,r3,g3,b3))
elif cmd in [SET_ANGLE, CENTER, GIMBAL_ROTATION, ABSOLUTE_ZOOM, SET_IMAGE_TYPE,
REQUEST_CONTINUOUS_DATA, SET_THERMAL_PALETTE, MANUAL_ZOOM_AND_AUTO_FOCUS]:
# an ack
pass
else:
print("SIYI: Unknown command 0x%02x" % cmd)
def update_title(self):
'''update thermal view title'''
if self.thermal_view is not None:
self.thermal_view.update_title()
if self.rawthermal_view is not None:
self.rawthermal_view.update_title()
if self.rgb_view is not None:
self.rgb_view.update_title()
def update_status(self):
if self.attitude is None:
return
(r,p,y) = self.get_gimbal_attitude()
self.console.set_status('SIYI', 'SIYI (%.1f,%.1f,%.1f) %.1fHz SR=%.1f M=%d' % (
r,p,y,
1.0/self.att_dt_lpf,
self.rf_dist, self.control_mode), row=6)
if self.tmin is not None:
self.console.set_status('TEMP', 'TEMP %.2f/%.2f' % (self.tmin, self.tmax), row=6)
self.update_title()
self.console.set_status('TCAP', 'TCAP %u' % self.thermal_capture_count, row=6)
def check_rate_end(self):
'''check for ending yaw/pitch command'''
now = time.time()
if self.yaw_end is not None and now >= self.yaw_end:
self.yaw_rate = 0
self.yaw_end = None
if self.pitch_end is not None and now >= self.pitch_end:
self.pitch_rate = 0
self.pitch_end = None
def get_encoder_attitude(self):
'''get attitude from encoders in vehicle frame'''
now = time.time()
att = self.master.messages.get('ATTITUDE',None)
if now - self.last_enc_recv_t > 2.0 or att is None:
return None
m = Matrix3()
# we use zero yaw as this is in vehicle frame
m.from_euler(att.roll,att.pitch,0)
m.rotate_312(radians(self.encoders[0]),radians(self.encoders[1]),radians(self.encoders[2]))
(r,p,y) = m.to_euler()
return degrees(r),degrees(p),mp_util.wrap_180(degrees(y))
def get_direct_attitude(self):
'''get extrapolated gimbal attitude, returning r,p,y in degrees in vehicle frame'''
now = time.time()
dt = (now - self.last_att_t)+self.siyi_settings.lag
dt = max(dt,0)
yaw = self.attitude[2]+self.attitude[5]*dt
pitch = self.attitude[1]+self.attitude[4]*dt
yaw = mp_util.wrap_180(yaw)
roll = self.attitude[0]
return roll, pitch, yaw
def get_gimbal_attitude(self):
'''get extrapolated gimbal attitude, returning yaw and pitch'''
ret = self.get_encoder_attitude()
if ret is not None:
(r,p,y) = ret
now = time.time()
if now - self.last_SIEA >= 0.2:
self.last_SIEA = now
self.logf.write('SIEA', 'Qfff', 'TimeUS,R,P,Y',
self.micros64(),
r,p,y)
self.send_named_float('EA_R', r)
self.send_named_float('EA_P', p)
self.send_named_float('EA_Y', y)
if self.siyi_settings.use_encoders:
if ret is not None:
return r,p,y
return self.get_direct_attitude()
def get_fov_attitude(self):
'''get attitude for FOV calculations'''
(r,p,y) = self.get_gimbal_attitude()
return (r,p-self.siyi_settings.mount_pitch,mp_util.wrap_180(y-self.siyi_settings.mount_yaw))
def get_slantrange(self,x,y,FOV,aspect_ratio):
'''
get range to ground
x and y are from -1 to 1, relative to center of camera view
'''
C = camera_projection.CameraParams(xresolution=1024, yresolution=int(1024/aspect_ratio), FOV=FOV)
cproj = camera_projection.CameraProjection(C, elevation_model=self.module('terrain').ElevationModel)
fov_att = self.get_fov_attitude()
att = self.master.messages.get('ATTITUDE',None)
gpi = self.master.messages.get('GLOBAL_POSITION_INT',None)
if gpi is None or att is None:
return None
return cproj.get_slantrange(gpi.lat*1.0e-7,gpi.lon*1.0e-7,gpi.alt*1.0e-3,fov_att[0],fov_att[1],fov_att[2]+math.degrees(att.yaw))
def get_latlonalt(self, slant_range, x, y, FOV, aspect_ratio):
'''
get ground lat/lon given vehicle orientation, camera orientation and slant range
x and y are from -1 to 1, relative to center of camera view
'''
C = camera_projection.CameraParams(xresolution=1024, yresolution=int(1024/aspect_ratio), FOV=FOV)
cproj = camera_projection.CameraProjection(C, elevation_model=self.module('terrain').ElevationModel)
px = int(C.xresolution * 0.5*(1+x))
py = int(C.yresolution * 0.5*(1+y))
fov_att = self.get_fov_attitude()
att = self.master.messages.get('ATTITUDE',None)
gpi = self.master.messages.get('GLOBAL_POSITION_INT',None)
if gpi is None or att is None:
return None
return cproj.get_latlonalt_for_pixel(px, py, gpi.lat*1.0e-7,gpi.lon*1.0e-7,gpi.alt*1.0e-3,fov_att[0],fov_att[1],fov_att[2]+math.degrees(att.yaw))
def get_target_yaw_pitch(self, lat, lon, alt, mylat, mylon, myalt, vehicle_yaw_rad):
'''get target yaw/pitch in vehicle frame for a target lat/lon'''
GPS_vector_x = (lon-mylon)*1.0e7*math.cos(math.radians((mylat + lat) * 0.5)) * 0.01113195
GPS_vector_y = (lat - mylat) * 0.01113195 * 1.0e7
GPS_vector_z = alt - myalt # was cm
target_distance = math.sqrt(GPS_vector_x**2 + GPS_vector_y**2)
# calculate pitch, yaw angles
pitch = math.atan2(GPS_vector_z, target_distance)
yaw = math.atan2(GPS_vector_x, GPS_vector_y)
yaw -= vehicle_yaw_rad
yaw_deg = mp_util.wrap_180(math.degrees(yaw))
pitch_deg = math.degrees(pitch)
return yaw_deg, pitch_deg
def update_target(self):
'''update position targetting'''
if not 'GLOBAL_POSITION_INT' in self.master.messages or not 'ATTITUDE' in self.master.messages:
return
# added rate of target update
map_module = self.module('map')
if self.siyi_settings.track_ROI == 1 and map_module is not None and map_module.current_ROI != self.last_map_ROI:
self.last_map_ROI = map_module.current_ROI
(lat, lon, alt) = self.last_map_ROI
self.clear_target()
self.set_target(lat, lon, alt)
if self.target_pos is None or self.attitude is None:
return
now = time.time()
if self.siyi_settings.target_rate <= 0 or now - self.last_target_send < 1.0 / self.siyi_settings.target_rate:
return
self.last_target_send = now
GLOBAL_POSITION_INT = self.master.messages['GLOBAL_POSITION_INT']
ATTITUDE = self.master.messages['ATTITUDE']
lat, lon, alt = self.target_pos
mylat = GLOBAL_POSITION_INT.lat*1.0e-7
mylon = GLOBAL_POSITION_INT.lon*1.0e-7
myalt = GLOBAL_POSITION_INT.alt*1.0e-3
dt = now - GLOBAL_POSITION_INT._timestamp
vn = GLOBAL_POSITION_INT.vx*0.01
ve = GLOBAL_POSITION_INT.vy*0.01
vd = GLOBAL_POSITION_INT.vz*0.01
(mylat, mylon) = mp_util.gps_offset(mylat, mylon, ve*dt, vn*dt)
myalt -= vd*dt
dt = now - ATTITUDE._timestamp
vehicle_yaw_rad = ATTITUDE.yaw + ATTITUDE.yawspeed*dt
yaw_deg, pitch_deg = self.get_target_yaw_pitch(lat, lon, alt, mylat, mylon, myalt, vehicle_yaw_rad)
self.send_named_float('TYAW', yaw_deg)
self.send_named_float('TPITCH', pitch_deg)
if self.siyi_settings.att_control == 1:
self.yaw_rate = None
self.pitch_rate = None
self.send_packet_fmt(SET_ANGLE, "<hh", int(-yaw_deg*10), int(pitch_deg*10))
return
if self.siyi_settings.los_correction == 1:
GLOBAL_POSITION_INT = self.master.messages['GLOBAL_POSITION_INT']
(mylat2, mylon2) = mp_util.gps_offset(mylat, mylon, ve*(dt+1), vn*(dt+1))
vehicle_yaw_rad2 = vehicle_yaw_rad + ATTITUDE.yawspeed
yaw_deg2, pitch_deg2 = self.get_target_yaw_pitch(lat, lon, alt, mylat2, mylon2, myalt, vehicle_yaw_rad2)
los_yaw_rate = mp_util.wrap_180(yaw_deg2 - yaw_deg)
los_pitch_rate = pitch_deg2 - pitch_deg
else:
los_yaw_rate = 0.0
los_pitch_rate = 0.0
#print(los_yaw_rate, los_pitch_rate)
cam_roll, cam_pitch, cam_yaw = self.get_gimbal_attitude()
err_yaw = mp_util.wrap_180(yaw_deg - cam_yaw)
err_pitch = pitch_deg - cam_pitch
err_yaw += self.siyi_settings.mount_yaw
err_yaw = mp_util.wrap_180(err_yaw)
err_pitch += self.siyi_settings.mount_pitch
self.yaw_rate = self.yaw_controller.run(err_yaw, los_yaw_rate)
self.pitch_rate = self.pitch_controller.run(err_pitch, los_pitch_rate)
self.send_named_float('EYAW', err_yaw)
self.send_named_float('EPITCH', err_pitch)
self.logf.write('SIPY', "Qfffff", "TimeUS,CYaw,TYaw,Yerr,I,FF",
self.micros64(), cam_yaw, yaw_deg, err_yaw, self.yaw_controller.I, los_yaw_rate)
self.logf.write('SIPP', "Qfffff", "TimeUS,CPitch,TPitch,Perr,I,FF",
self.micros64(), cam_pitch, pitch_deg, err_pitch, self.pitch_controller.I, los_pitch_rate)
def show_fov1(self, FOV, name, aspect_ratio, color):
'''show one FOV polygon'''
points = []
C = camera_projection.CameraParams(xresolution=1024, yresolution=int(1024/aspect_ratio), FOV=FOV)
cproj = camera_projection.CameraProjection(C, elevation_model=self.module('terrain').ElevationModel)
fov_att = self.get_fov_attitude()
att = self.master.messages.get('ATTITUDE',None)
gpi = self.master.messages.get('GLOBAL_POSITION_INT',None)
if gpi is None or att is None:
return None
points = cproj.get_projection(gpi.lat*1.0e-7,gpi.lon*1.0e-7,gpi.alt*1.0e-3,fov_att[0],fov_att[1],fov_att[2]+math.degrees(att.yaw))
if points is not None:
self.mpstate.map.add_object(mp_slipmap.SlipPolygon(name, points, layer='SIYI',
linewidth=2, colour=color))
def show_fov(self):
'''show FOV polygons'''
self.show_fov1(self.siyi_settings.thermal_fov, 'FOV_thermal', 640.0/512.0, (0,0,128))
FOV2 = self.siyi_settings.wide_fov
if self.rgb_lens == "zoom":
FOV2 = self.siyi_settings.zoom_fov / self.last_zoom
self.show_fov1(FOV2, 'FOV_RGB', 1280.0/720.0, (0,128,128))
def camera_click(self, mode, latlonalt):
'''handle click on camera window'''
latlon = (latlonalt[0], latlonalt[1])
# set click location for other commands
self.mpstate.click_location = latlon
if mode == 'ClickTrack':
self.set_target(latlonalt[0], latlonalt[1], latlonalt[2])
else:
self.mpstate.map.add_object(
mp_slipmap.SlipIcon("SIYIClick", latlon, self.click_icon, layer="SIYI")
)
def handle_marker(self, marker):
'''handle marker menu on image'''
map = self.module('map')
if map:
map.cmd_map_marker([marker])
def end_tracking(self):
'''end all tracking'''
if self.rgb_view is not None:
self.rgb_view.end_tracking()
if self.thermal_view is not None:
self.thermal_view.end_tracking()
if self.rawthermal_view is not None:
self.rawthermal_view.end_tracking()
def armed_checks(self):
'''checks for armed/disarmed'''
now = time.time()
armed = self.master.motors_armed()
if armed and not self.last_armed:
print("Setting SIYI time")
self.cmd_settime()
print("Enabling thermal capture")
self.siyi_settings.therm_cap_rate = 1.0
if not armed and self.last_armed:
print("Disabling thermal capture")
self.siyi_settings.therm_cap_rate = 0.0
self.last_armed = armed
if now - self.last_getconfig > 5:
self.getconfig_pending = True
self.last_getconfig = now
self.send_packet(ACQUIRE_GIMBAL_CONFIG_INFO, None)
def mavlink_packet(self, m):
'''process a mavlink message'''
mtype = m.get_type()
self.armed_checks()
if mtype == 'GPS_RAW_INT':
gwk, gms = mp_util.get_gps_time(time.time())
self.logf.write('GPS', "QBIHLLff", "TimeUS,Status,GMS,GWk,Lat,Lng,Alt,Spd",
self.micros64(), m.fix_type, gms, gwk, m.lat, m.lon, m.alt*0.001, m.vel*0.01)
if mtype == 'ATTITUDE':
self.logf.write('ATT', "Qffffff", "TimeUS,Roll,Pitch,Yaw,GyrX,GyrY,GyrZ",
self.micros64(),
math.degrees(m.roll), math.degrees(m.pitch), math.degrees(m.yaw),
math.degrees(m.rollspeed), math.degrees(m.pitchspeed), math.degrees(m.yawspeed))
if mtype == 'GLOBAL_POSITION_INT':
try:
self.show_fov()
except Exception as ex:
print(traceback.format_exc())
elif mtype == 'EXTENDED_SYS_STATE':
if self.siyi_settings.stow_on_landing:
self.extended_sys_state_received_time = time.time()
if (m.landed_state == mavutil.mavlink.MAV_LANDED_STATE_LANDING and
self.last_landed_state != mavutil.mavlink.MAV_LANDED_STATE_LANDING):
# we've just transition into landing
self.retract()
self.last_landed_state = m.landed_state
def retract(self):
print("SIYI: stowing camera")
self.cmd_angle([0, 0])
def receive_thread(self):
'''thread for receiving UDP packets from SIYI'''
while True:
if self.sock is None:
time.sleep(0.1)
continue
try:
pkt = self.sock.recv(10240)
except Exception as ex:
print("SIYI receive failed", ex)
continue
self.parse_data(pkt)
def therm_capture(self):
if self.siyi_settings.therm_cap_rate <= 0:
return
now = time.time()
dt = now - self.last_therm_cap
if dt > 5:
self.send_packet_fmt(SET_THERMAL_MODE, "<B", 1)
if dt > 1.0 / self.siyi_settings.therm_cap_rate:
self.send_packet_fmt(GET_TEMP_FRAME, None)
self.last_therm_cap = now
def idle_task(self):
'''called on idle'''
if not self.sock:
return
if not self.have_version and time.time() - self.last_version_send > 2.0:
self.last_version_send = time.time()
self.send_packet(ACQUIRE_FIRMWARE_VERSION, None)
self.check_rate_end()
self.update_target()
self.send_rates()
self.request_telem()
self.send_attitude()
self.check_thermal_events()
self.therm_capture()
# we need EXTENDED_SYS_STATE to work out if we're landing:
if self.siyi_settings.stow_on_landing:
now = time.time()
delta_t = now - self.extended_sys_state_received_time
delta_sent_t = now - self.extended_sys_state_request_time
if delta_t > 5 and delta_sent_t > 5:
self.extended_sys_state_request_time = now
self.master.mav.command_long_send(
1, # FIXME, target_system
1, # FIXME, target_component
mavutil.mavlink.MAV_CMD_SET_MESSAGE_INTERVAL,
0, # confirmation
mavutil.mavlink.MAVLINK_MSG_ID_EXTENDED_SYS_STATE, # p1
1e6, #p2 interval (microseconds)
0, #p3 instance
0,
0,
0,
0
)
delta_warn_t = now - self.extended_sys_state_warn_time
if delta_t > 60 and delta_warn_t > 60:
self.extended_sys_state_warn_time = now
print("SIYI: no EXTENDED_SYS_STATE, can't auto-stow")
if self.siyi_settings.stow_heuristics_enabled:
self.check_stow_on_landing_heuristics()
def check_stow_on_landing_heuristics(self):
tr = self.master.messages.get('TERRAIN_REPORT', None)
vfr_hud = self.master.messages.get('VFR_HUD', None)
if tr is None or vfr_hud is None:
now = time.time()
if now - self.landing_heuristics["last_warning_ms"] > 60:
self.landing_heuristics["last_warning_ms"] = now
print("SIYI: missing messages, hueristics-stow not available")
return
# first work out whether we should "arm" the stowing; must
# meet minimum conditions to do so:
current_terrain_alt = tr.current_height
if current_terrain_alt > self.siyi_settings.stow_heuristics_minalt + 1:
# above trigger altitude
self.landing_heuristics["armed"] = True
# now work out whether to stow:
if not self.landing_heuristics["armed"]:
return
if current_terrain_alt > self.siyi_settings.stow_heuristics_minalt:
# above the minimum altitude
return
if vfr_hud.groundspeed > self.siyi_settings.stow_heuristics_maxhorvel:
# travelling rapidly horizontally
return
if vfr_hud.climb > 0:
# climbing
return
self.landing_heuristics["armed"] = False
self.retract()
def show_horizon_lines(self):
'''show horizon lines'''
if self.rgb_view is None or self.rgb_view.im is None:
return
att = self.master.messages.get('ATTITUDE',None)
if att is None:
return
r,p,y = self.get_encoder_attitude()
self.rgb_view.im.add_OSD(MPImageOSD_HorizonLine('hor1', r, p, self.siyi_settings.wide_fov, (255,0,255)))
# convert SIYI 312 to 321
m = Matrix3()
m.from_euler312(radians(self.attitude[0]), radians(self.attitude[1]), radians(self.attitude[2]))
r,p,y = m.to_euler()
self.rgb_view.im.add_OSD(MPImageOSD_HorizonLine('hor2', degrees(r), degrees(p), self.siyi_settings.wide_fov, (255,255,0)))
def remove_horizon_lines(self):
'''remove horizon lines'''
self.rgb_view.im.add_OSD(MPImageOSD_None('hor1'))
self.rgb_view.im.add_OSD(MPImageOSD_None('hor2'))
|
class SIYIModule(mp_module.MPModule):
def __init__(self, mpstate):
pass
def micros64(self):
pass
def millis32(self):
pass
def cmd_siyi(self, args):
'''siyi command parser'''
pass
def cmd_connect(self):
'''connect to the camera'''
pass
def cmd_rates(self, args):
'''update rates'''
pass
def cmd_yaw(self, args):
'''update yaw'''
pass
def cmd_pitch(self, args):
'''update pitch'''
pass
def cmd_imode(self, args):
'''update image mode'''
pass
def cmd_palette(self, args):
'''update thermal palette'''
pass
def cmd_settime(self):
'''set camera time'''
pass
def video_filename(self, base):
'''get a video file name'''
pass
def cmd_thermal(self):
'''open thermal viewer'''
pass
def cmd_rawthermal(self):
'''open raw thermal viewer'''
pass
def cmd_rgbview(self):
'''open rgb viewer'''
pass
def check_thermal_events(self):
'''check for mouse events on thermal image'''
pass
def log_frame_counter(self, video_idx, thermal, frame_counter):
'''log video frame counter'''
pass
def cmd_zoom(self, args):
'''set zoom'''
pass
def set_target(self, lat, lon, alt):
'''set target position'''
pass
def therm_set_distance(self, distance):
'''set thermal distance'''
pass
def therm_set_emissivity(self, emissivity):
'''set thermal emissivity'''
pass
def therm_set_humidity(self, humidity):
'''set thermal humidity'''
pass
def therm_set_airtemp(self, airtemp):
'''set thermal airtemp'''
pass
def therm_set_reftemp(self, reftemp):
'''set thermal reftemp'''
pass
def therm_set_thresholds(self, args):
'''set thermal thresholds
format: therm_setthresholds 30 102,204,255 40 102,204,255 50 102,204,255 80
'''
pass
def clear_target(self):
'''clear target position'''
pass
def cmd_angle(self, args):
'''set zoom'''
pass
def send_rates(self):
'''send rates packet'''
pass
def cmd_settarget(self, args):
'''set target'''
pass
def request_telem(self):
'''request telemetry'''
pass
def send_attitude(self):
'''send attitude to gimbal'''
pass
def send_packet(self, command_id, pkt):
'''send SIYI packet'''
pass
def send_packet_fmt(self, command_id, fmt, *args):
'''send SIYI packet'''
pass
def unpack(self, command_id, fmt, data):
'''unpack SIYI data and log'''
pass
def parse_data(self, pkt):
'''parse SIYI packet'''
pass
def parse_packet(self, pkt):
'''parse SIYI packet'''
pass
def update_title(self):
'''update thermal view title'''
pass
def update_status(self):
pass
def check_rate_end(self):
'''check for ending yaw/pitch command'''
pass
def get_encoder_attitude(self):
'''get attitude from encoders in vehicle frame'''
pass
def get_direct_attitude(self):
'''get extrapolated gimbal attitude, returning r,p,y in degrees in vehicle frame'''
pass
def get_gimbal_attitude(self):
'''get extrapolated gimbal attitude, returning yaw and pitch'''
pass
def get_fov_attitude(self):
'''get attitude for FOV calculations'''
pass
def get_slantrange(self,x,y,FOV,aspect_ratio):
'''
get range to ground
x and y are from -1 to 1, relative to center of camera view
'''
pass
def get_latlonalt(self, slant_range, x, y, FOV, aspect_ratio):
'''
get ground lat/lon given vehicle orientation, camera orientation and slant range
x and y are from -1 to 1, relative to center of camera view
'''
pass
def get_target_yaw_pitch(self, lat, lon, alt, mylat, mylon, myalt, vehicle_yaw_rad):
'''get target yaw/pitch in vehicle frame for a target lat/lon'''
pass
def update_target(self):
'''update position targetting'''
pass
def show_fov1(self, FOV, name, aspect_ratio, color):
'''show one FOV polygon'''
pass
def show_fov1(self, FOV, name, aspect_ratio, color):
'''show FOV polygons'''
pass
def camera_click(self, mode, latlonalt):
'''handle click on camera window'''
pass
def handle_marker(self, marker):
'''handle marker menu on image'''
pass
def end_tracking(self):
'''end all tracking'''
pass
def armed_checks(self):
'''checks for armed/disarmed'''
pass
def mavlink_packet(self, m):
'''process a mavlink message'''
pass
def retract(self):
pass
def receive_thread(self):
'''thread for receiving UDP packets from SIYI'''
pass
def therm_capture(self):
pass
def idle_task(self):
'''called on idle'''
pass
def check_stow_on_landing_heuristics(self):
pass
def show_horizon_lines(self):
'''show horizon lines'''
pass
def remove_horizon_lines(self):
'''remove horizon lines'''
pass
| 62 | 54 | 21 | 1 | 18 | 2 | 4 | 0.1 | 1 | 25 | 15 | 0 | 61 | 68 | 61 | 99 | 1,332 | 123 | 1,123 | 288 | 1,061 | 116 | 870 | 285 | 808 | 45 | 2 | 3 | 258 |
7,074 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SIYI/__init__.py
|
MAVProxy.modules.mavproxy_SIYI.ThermalParameters
|
class ThermalParameters:
def __init__(self, distance, target_emissivity, humidity, air_temperature, reflection_temperature):
self.distance = distance
self.target_emissivity = target_emissivity
self.humidity = humidity
self.air_temperature = air_temperature
self.reflection_temperature = reflection_temperature
def __repr__(self):
return "Dist=%.2f Emiss=%.2f Hum=%.2f AirTemp=%.2f RefTemp=%.2f" % (self.distance,
self.target_emissivity,
self.humidity,
self.air_temperature,
self.reflection_temperature)
def args(self):
return [int(self.distance*100), int(self.target_emissivity*100),
int(self.humidity*100), int(self.air_temperature*100), int(self.reflection_temperature*100)]
|
class ThermalParameters:
def __init__(self, distance, target_emissivity, humidity, air_temperature, reflection_temperature):
pass
def __repr__(self):
pass
def args(self):
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 3 | 5 | 3 | 3 | 18 | 2 | 16 | 9 | 12 | 0 | 11 | 9 | 7 | 1 | 0 | 0 | 3 |
7,075 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wavefront.py
|
MAVProxy.modules.lib.wavefront.Parser
|
class Parser(object):
def __init__(self, filename=None, string='', enable_cache=False):
self.filename = filename
self.string = string
self.enable_cache = enable_cache
self.deps = []
def parse(self, progress_callback=None):
if self.filename:
return self.parse_file(progress_callback)
return self.parse_str(progress_callback)
def from_cache(self, progress_callback=None):
deps_filename = self.filename + '.deps'
if not os.path.exists(deps_filename):
return None
with open(deps_filename, 'r') as f:
for line in f:
filename = line.strip()
if not os.path.exists(filename):
return None
cache_filename = filename + '.cache'
if not os.path.exists(cache_filename):
return None
s = os.stat(filename)
sc = os.stat(cache_filename)
if sc.st_mtime < s.st_mtime:
return None
if progress_callback:
progress_callback(-1, -1)
with open(self.filename + '.cache', 'r') as f:
try:
obj = pickle.load(f)
except:
print("wavefront parser: error on loading cache, falling back to parsing", file=sys.stderr)
return None
else:
return obj
def parse_file(self, progress_callback=None):
if self.enable_cache:
obj = self.from_cache(progress_callback=progress_callback)
if obj:
return obj
s = os.stat(self.filename)
try:
blksize = s.st_blksize
except AttributeError:
blksize = 4096
num_lines = None
if progress_callback:
num_lines = 0
with open(self.filename, 'r') as f:
try:
read = f.raw.read
except AttributeError:
read = f.read
blk = read(blksize)
while blk:
num_lines += blk.count("\n")
blk = read(blksize)
self.deps = [self.filename]
with open(self.filename, 'r') as f:
obj = self.parse_lines(
f,
num_lines=num_lines,
progress_callback=progress_callback,
)
if self.enable_cache:
# FIXME: this will make the cache files be located at the same
# location as the source file, which might be somewhere the
# user doesn't have write access.
with open(self.filename + '.deps', 'w') as deps_file:
for filename in self.deps:
print(filename, file=deps_file)
with open(self.filename + '.cache', 'w') as cache_file:
pickle.dump(obj, cache_file)
return obj
def parse_str(self, progress_callback=None):
self.deps = []
lines = self.string.splitlines()
return self.parse_lines(
lines,
num_lines=len(lines) if progress_callback else None,
progress_callback=progress_callback,
)
def parse_lines(self, lines, num_lines=None, progress_callback=None):
obj = self.new_target()
self.reset()
i = 0
for line in lines:
line = self.filter_line(line)
i += 1
if not line:
continue
self.parse_line(line, obj)
if progress_callback and num_lines:
progress_callback(i, num_lines)
return obj
def filter_line(self, line):
i = line.find('#')
if i != -1:
line = line[:i]
return line.strip()
|
class Parser(object):
def __init__(self, filename=None, string='', enable_cache=False):
pass
def parse(self, progress_callback=None):
pass
def from_cache(self, progress_callback=None):
pass
def parse_file(self, progress_callback=None):
pass
def parse_str(self, progress_callback=None):
pass
def parse_lines(self, lines, num_lines=None, progress_callback=None):
pass
def filter_line(self, line):
pass
| 8 | 0 | 16 | 2 | 14 | 1 | 4 | 0.04 | 1 | 1 | 0 | 2 | 7 | 4 | 7 | 7 | 119 | 18 | 98 | 35 | 90 | 4 | 90 | 31 | 82 | 9 | 1 | 4 | 28 |
7,076 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wavefront.py
|
MAVProxy.modules.lib.wavefront.ParserWorker
|
class ParserWorker(threading.Thread):
def __init__(self, parser, progress_callback=None, complete_callback=None):
super(ParserWorker, self).__init__()
self.lock = threading.Lock()
self.parser = parser
self.complete_callback = complete_callback
self.progress = 0, 0
def run(self):
self.obj = self.parser.parse(progress_callback=self.progress_callback)
if self.complete_callback:
self.complete_callback()
def progress_callback(self, i, num_lines):
self.lock.acquire()
self.progress = i, num_lines
self.lock.release()
def get_progress(self):
self.lock.acquire()
p = self.progress
self.lock.release()
return p
|
class ParserWorker(threading.Thread):
def __init__(self, parser, progress_callback=None, complete_callback=None):
pass
def run(self):
pass
def progress_callback(self, i, num_lines):
pass
def get_progress(self):
pass
| 5 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 4 | 5 | 4 | 29 | 23 | 3 | 20 | 11 | 15 | 0 | 20 | 11 | 15 | 2 | 1 | 1 | 5 |
7,077 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/win_layout.py
|
MAVProxy.modules.lib.win_layout.ManagedWindow
|
class ManagedWindow(object):
'''a layout plus callback for setting window position and size'''
def __init__(self, layout, callback):
self.layout = layout
self.callback = callback
|
class ManagedWindow(object):
'''a layout plus callback for setting window position and size'''
def __init__(self, layout, callback):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.25 | 1 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 5 | 0 | 4 | 4 | 2 | 1 | 4 | 4 | 2 | 1 | 1 | 0 | 1 |
7,078 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/win_layout.py
|
MAVProxy.modules.lib.win_layout.WinLayout
|
class WinLayout(object):
'''represent window layout'''
def __init__(self, name, pos, size, dsize):
self.name = name
self.pos = pos
self.size = size
self.dsize = dsize
def __str__(self):
return "%s(%ux%u@%u-%u)" % (self.name,
self.size[0], self.size[1],
self.pos[0], self.pos[1])
|
class WinLayout(object):
'''represent window layout'''
def __init__(self, name, pos, size, dsize):
pass
def __str__(self):
pass
| 3 | 1 | 5 | 0 | 5 | 0 | 1 | 0.1 | 1 | 0 | 0 | 0 | 2 | 4 | 2 | 2 | 12 | 1 | 10 | 7 | 7 | 1 | 8 | 7 | 5 | 1 | 1 | 0 | 2 |
7,079 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_ui.py
|
MAVProxy.modules.lib.wxsaildash_ui.InstrumentDisplay
|
class InstrumentDisplay(wx.Panel):
'''
class: `InstrumentDisplay` is a panel for displaying sailing instrument data
'''
def __init__(self, *args, **kwargs):
# customise the style
kwargs.setdefault('style', wx.TE_READONLY)
# initialise super class
super(InstrumentDisplay, self).__init__(*args, **kwargs)
# set the background colour (also for text controls)
# self.SetBackgroundColour(wx.WHITE)
# text controls
self._label_text = wx.TextCtrl(self, style=wx.BORDER_NONE)
self._label_text.SetFont(wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
self._label_text.SetBackgroundColour(self.GetBackgroundColour())
self._label_text.ChangeValue("---")
self._value_text = wx.TextCtrl(self, style=wx.BORDER_NONE|wx.TE_CENTRE)
self._value_text.SetFont(wx.Font(30, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
self._value_text.SetBackgroundColour(self.GetBackgroundColour())
self._value_text.ChangeValue("-.-")
self._value_text.SetMinSize((60, 40))
self._unit_text = wx.TextCtrl(self, style=wx.BORDER_NONE|wx.TE_RIGHT)
self._unit_text.SetFont(wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
self._unit_text.SetBackgroundColour(self.GetBackgroundColour())
self._unit_text.ChangeValue("--")
# value text needs a nested sizer to centre vertically
self._value_sizer = wx.BoxSizer(wx.HORIZONTAL)
self._value_sizer.Add(self._value_text,
wx.SizerFlags(1).Align(wx.ALIGN_CENTRE_VERTICAL).Border(wx.ALL, 0))
# top level sizers
self._top_sizer = wx.BoxSizer(wx.VERTICAL)
self._top_sizer.Add(self._label_text,
wx.SizerFlags(0).Align(wx.ALIGN_TOP|wx.ALIGN_LEFT).Border(wx.ALL, 2))
self._top_sizer.Add(self._value_sizer,
wx.SizerFlags(1).Expand().Border(wx.ALL, 1))
self._top_sizer.Add(self._unit_text,
wx.SizerFlags(0).Align(wx.ALIGN_RIGHT).Border(wx.ALL, 2))
# layout sizers
self._top_sizer.SetSizeHints(self)
self.SetSizer(self._top_sizer)
self.SetAutoLayout(True)
@property
def label(self):
return self._label_text.GetValue()
@label.setter
def label(self, label):
self._label_text.ChangeValue(label)
@property
def value(self):
return self._value_text.GetValue()
@value.setter
def value(self, value):
self._value_text.ChangeValue("{:.2f}".format(value))
@property
def unit(self):
return self._unit_text.GetValue()
@unit.setter
def unit(self, unit):
self._unit_text.ChangeValue(unit)
|
class InstrumentDisplay(wx.Panel):
'''
class: `InstrumentDisplay` is a panel for displaying sailing instrument data
'''
def __init__(self, *args, **kwargs):
pass
@property
def label(self):
pass
@label.setter
def label(self):
pass
@property
def value(self):
pass
@value.setter
def value(self):
pass
@property
def unit(self):
pass
@unit.setter
def unit(self):
pass
| 14 | 1 | 8 | 1 | 6 | 1 | 1 | 0.23 | 1 | 1 | 0 | 0 | 7 | 5 | 7 | 7 | 74 | 15 | 48 | 19 | 34 | 11 | 38 | 13 | 30 | 1 | 1 | 0 | 7 |
7,080 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_ui.py
|
MAVProxy.modules.lib.wxsaildash_ui.SailingDashboardFrame
|
class SailingDashboardFrame(wx.Frame):
'''The main frame of the sailing dashboard'''
def __init__(self, state, title, size):
super(SailingDashboardFrame, self).__init__(None, title=title, size=size)
self._state = state
self._title = title
# control update rate
self._timer = wx.Timer(self)
self._fps = 10.0
self._start_time = time.time()
# events
self.Bind(wx.EVT_TIMER, self.OnTimer, self._timer)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyPress)
# restart the timer
self._timer.Start(milliseconds=100)
# create wind meters for true and apparent wind
self._wind_meter1 = WindMeter(self)
self._wind_meter1.SetWindReference(WindReference.RELATIVE)
self._wind_meter1.SetWindSpeedUnit(SpeedUnit.KNOTS)
self._wind_meter1.SetWindAngle(0)
self._wind_meter1.SetWindSpeed(0)
self._wind_meter2 = WindMeter(self)
self._wind_meter2.SetWindReference(WindReference.TRUE)
self._wind_meter2.SetWindSpeedUnit(SpeedUnit.KNOTS)
self._wind_meter2.SetWindAngle(0)
self._wind_meter2.SetWindSpeed(0)
# instrument display
self._instr1 = InstrumentDisplay(self)
self._instr1.label = "AWS"
self._instr1.unit = "kn"
self._instr1.value = 0.0
self._instr2 = InstrumentDisplay(self)
self._instr2.label = "TWS"
self._instr2.unit = "kn"
self._instr2.value = 0.0
self._instr3 = InstrumentDisplay(self)
self._instr3.label = "STW"
self._instr3.unit = "kn"
self._instr3.value = 0.0
self._instr4 = InstrumentDisplay(self)
self._instr4.label = "AWA"
self._instr4.unit = "deg"
self._instr4.value = 0.0
self._instr5 = InstrumentDisplay(self)
self._instr5.label = "TWA"
self._instr5.unit = "deg"
self._instr5.value = 0.0
self._instr6 = InstrumentDisplay(self)
self._instr6.label = "HDT"
self._instr6.unit = "deg"
self._instr3.value = 0.0
# instrument panel sizers
self._instr_sizer1 = wx.BoxSizer(wx.VERTICAL)
self._instr_sizer1.Add(self._instr1, 1, wx.EXPAND)
self._instr_sizer1.Add(self._instr2, 1, wx.EXPAND)
self._instr_sizer1.Add(self._instr3, 1, wx.EXPAND)
self._instr_sizer2 = wx.BoxSizer(wx.VERTICAL)
self._instr_sizer2.Add(self._instr4, 1, wx.EXPAND)
self._instr_sizer2.Add(self._instr5, 1, wx.EXPAND)
self._instr_sizer2.Add(self._instr6, 1, wx.EXPAND)
# top level sizers
self._top_sizer = wx.BoxSizer(wx.HORIZONTAL)
self._top_sizer.Add(self._wind_meter1, 2, wx.EXPAND)
self._top_sizer.Add(self._wind_meter2, 2, wx.EXPAND)
self._top_sizer.Add(self._instr_sizer1, 1, wx.EXPAND)
self._top_sizer.Add(self._instr_sizer2, 1, wx.EXPAND)
# layout sizers
self.SetSizer(self._top_sizer)
self.SetAutoLayout(1)
# self.sizer.Fit(self)
def OnIdle(self, event):
'''Handle idle events
- e.g. managed scaling when window resized if needed
'''
pass
def OnTimer(self, event):
'''Handle timed tasks'''
# check for close events
if self._state.close_event.wait(timeout=0.001):
# stop the timer and destroy the window - this ensures
# the window is closed whhen the module is unloaded
self._timer.Stop()
self.Destroy()
return
# receive data from the module
while self._state.child_pipe_recv.poll():
obj_list = self._state.child_pipe_recv.recv()
for obj in obj_list:
if isinstance(obj, WindAngleAndSpeed):
if obj.wind_reference == WindReference.RELATIVE:
# apparent wind meter
self._wind_meter1.SetWindReference(obj.wind_reference)
self._wind_meter1.SetWindAngle(obj.wind_angle)
self._wind_meter1.SetWindSpeed(obj.wind_speed)
self._wind_meter1.SetWindSpeedUnit(obj.wind_speed_unit)
# apparent wind displays
self._instr1.value = obj.wind_speed
self._instr4.value = obj.wind_angle
elif obj.wind_reference == WindReference.TRUE:
# apparent wind meter
self._wind_meter2.SetWindReference(obj.wind_reference)
self._wind_meter2.SetWindAngle(obj.wind_angle)
self._wind_meter2.SetWindSpeed(obj.wind_speed)
self._wind_meter2.SetWindSpeedUnit(obj.wind_speed_unit)
# apparent wind displays
self._instr2.value = obj.wind_speed
self._instr5.value = obj.wind_angle
elif isinstance(obj, WaterSpeedAndHeading):
# water speed and heading
self._instr3.value = obj.water_speed
self._instr6.value = obj.heading_true
# reset counters
self._start_time = time.time()
def OnKeyPress(self, event):
'''Handle keypress events'''
pass
|
class SailingDashboardFrame(wx.Frame):
'''The main frame of the sailing dashboard'''
def __init__(self, state, title, size):
pass
def OnIdle(self, event):
'''Handle idle events
- e.g. managed scaling when window resized if needed
'''
pass
def OnTimer(self, event):
'''Handle timed tasks'''
pass
def OnKeyPress(self, event):
'''Handle keypress events'''
pass
| 5 | 4 | 35 | 7 | 23 | 6 | 3 | 0.27 | 1 | 7 | 6 | 0 | 4 | 16 | 4 | 4 | 147 | 30 | 92 | 23 | 87 | 25 | 90 | 23 | 85 | 8 | 1 | 4 | 11 |
7,081 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_ui.py
|
MAVProxy.modules.lib.wxsaildash_ui.WindMeter
|
class WindMeter(SM.SpeedMeter):
'''
class: `WindMeter` is a custom `SpeedMeter`for displaying true or apparent wind
'''
def __init__(self, *args, **kwargs):
# customise the agw style
kwargs.setdefault('agwStyle', SM.SM_DRAW_HAND
|SM.SM_DRAW_PARTIAL_SECTORS
|SM.SM_DRAW_SECONDARY_TICKS
|SM.SM_DRAW_MIDDLE_TEXT)
# initialise super class
super(WindMeter, self).__init__(*args, **kwargs)
# non-public attributes
self._wind_reference = WindReference.RELATIVE
self._wind_speed = 0
self._wind_speed_unit = SpeedUnit.KNOTS
# colours
dial_colour = wx.ColourDatabase().Find('DARK SLATE GREY')
port_arc_colour = wx.ColourDatabase().Find('RED')
stbd_arc_colour = wx.ColourDatabase().Find('GREEN')
bottom_arc_colour = wx.ColourDatabase().Find('TAN')
self.SetSpeedBackground(dial_colour)
# set lower limit to 2.999/2 to prevent the partial sectors from filling
# the entire dial
self.SetAngleRange(- 2.995/2 * math.pi, math.pi/2)
# create the intervals
intervals = range(0, 361, 20)
self.SetIntervals(intervals)
# assign colours to sectors
colours = [dial_colour] \
+ [stbd_arc_colour] * 2 \
+ [dial_colour] * 4 \
+ [bottom_arc_colour] * 4 \
+ [dial_colour] * 4 \
+ [port_arc_colour] * 2 \
+ [dial_colour]
self.SetIntervalColours(colours)
# assign the ticks, colours and font
ticks = ['0', '20', '40', '60', '80', '100', '120', '140', '160', '180', '-160', '-140', '-120', '-100', '-80', '-60', '-40', '-20', '']
self.SetTicks(ticks)
self.SetTicksColour(wx.WHITE)
self.SetNumberOfSecondaryTicks(1)
self.SetTicksFont(wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
# set the colour for the first hand indicator
self.SetHandColour(wx.Colour(210, 210, 210))
self.SetHandStyle("Hand")
# do not draw the external (container) arc
self.DrawExternalArc(False)
# initialise the meter to zero
self.SetWindAngle(0.0)
# wind speed display
self.SetMiddleTextColour(wx.WHITE)
self.SetMiddleTextFont(wx.Font(16, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
self.SetWindSpeed(0.0)
def SetWindAngle(self, wind_angle):
'''Set the wind angle
The wind angle is measured with respect to the front of the vehicle, so:
-180 <= wind_angle <= 180
'''
# Convert the wind angle to the meter interval [0 - 360]
dial_value = wind_angle
if wind_angle < 0:
dial_value += 360
self.SetSpeedValue(dial_value)
def SetWindSpeed(self, wind_speed):
'''Set the wind speed'''
self._wind_speed = wind_speed
reference_code = None
if self._wind_reference == WindReference.RELATIVE:
reference_code ='AWS'
elif self._wind_reference == WindReference.TRUE:
reference_code ='TWS'
else:
reference_code ='INVALID'
unit_code = None
if self._wind_speed_unit == SpeedUnit.KPH:
unit_code ='kph'
elif self._wind_speed_unit == SpeedUnit.MPH:
unit_code ='mph'
elif self._wind_speed_unit == SpeedUnit.KNOTS:
unit_code ='kn'
else:
unit_code ='INVALID'
txt = reference_code + " {:.2f}".format(self._wind_speed) + ' ' + unit_code
self.SetMiddleText(txt)
def SetWindReference(self, reference):
'''Set the wind reference (i.e relative(apparent) or true)'''
if not (reference == WindReference.RELATIVE or reference == WindReference.TRUE):
raise Exception("Invalid wind reference. Must be 'RELATIVE' or 'TRUE'")
self._wind_reference = reference
def SetWindSpeedUnit(self, unit):
'''Set the wind speed units'''
if not (unit == SpeedUnit.KPH or unit == SpeedUnit.MPH or unit == SpeedUnit.KNOTS):
raise Exception("Invalid wind speed unit. Must be 'KPH' or 'MPH' or 'KNOTS'")
self._wind_speed_unit = unit
|
class WindMeter(SM.SpeedMeter):
'''
class: `WindMeter` is a custom `SpeedMeter`for displaying true or apparent wind
'''
def __init__(self, *args, **kwargs):
pass
def SetWindAngle(self, wind_angle):
'''Set the wind angle
The wind angle is measured with respect to the front of the vehicle, so:
-180 <= wind_angle <= 180
'''
pass
def SetWindSpeed(self, wind_speed):
'''Set the wind speed'''
pass
def SetWindReference(self, reference):
'''Set the wind reference (i.e relative(apparent) or true)'''
pass
def SetWindSpeedUnit(self, unit):
'''Set the wind speed units'''
pass
| 6 | 5 | 23 | 4 | 14 | 4 | 3 | 0.34 | 1 | 5 | 2 | 0 | 5 | 3 | 5 | 5 | 122 | 27 | 71 | 20 | 65 | 24 | 57 | 20 | 51 | 6 | 1 | 1 | 13 |
7,082 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_util.py
|
MAVProxy.modules.lib.wxsaildash_util.SpeedUnit
|
class SpeedUnit(enum.Enum):
'''
An enumeration for the units of speed: kph, mph, or knots
'''
KPH = 1
MPH = 2
KNOTS = 3
|
class SpeedUnit(enum.Enum):
'''
An enumeration for the units of speed: kph, mph, or knots
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 8 | 1 | 4 | 4 | 3 | 3 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
7,083 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_util.py
|
MAVProxy.modules.lib.wxsaildash_util.WaterSpeedAndHeading
|
class WaterSpeedAndHeading(object):
'''
Water speed and heading attributes
'''
def __init__(self, water_speed, heading_true):
self.water_speed = water_speed
self.heading_true = heading_true
|
class WaterSpeedAndHeading(object):
'''
Water speed and heading attributes
'''
def __init__(self, water_speed, heading_true):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.75 | 1 | 0 | 0 | 0 | 1 | 2 | 1 | 1 | 8 | 1 | 4 | 4 | 2 | 3 | 4 | 4 | 2 | 1 | 1 | 0 | 1 |
7,084 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_util.py
|
MAVProxy.modules.lib.wxsaildash_util.WindAngleAndSpeed
|
class WindAngleAndSpeed(object):
'''
Wind angle and speed attributes
'''
def __init__(self, reference, angle, speed, unit):
self.wind_reference = reference
self.wind_angle = angle
self.wind_speed = speed
self.wind_speed_unit = unit
|
class WindAngleAndSpeed(object):
'''
Wind angle and speed attributes
'''
def __init__(self, reference, angle, speed, unit):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 1 | 0.5 | 1 | 0 | 0 | 0 | 1 | 4 | 1 | 1 | 10 | 1 | 6 | 6 | 4 | 3 | 6 | 6 | 4 | 1 | 1 | 0 | 1 |
7,085 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsaildash_util.py
|
MAVProxy.modules.lib.wxsaildash_util.WindReference
|
class WindReference(enum.Enum):
'''
An enumeration for the wind reference (either RELATIVE or TRUE)
'''
RELATIVE = 1
TRUE = 2
|
class WindReference(enum.Enum):
'''
An enumeration for the wind reference (either RELATIVE or TRUE)
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 7 | 1 | 3 | 3 | 2 | 3 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
7,086 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsettings.py
|
MAVProxy.modules.lib.wxsettings.WXSettings
|
class WXSettings(object):
'''
a graphical settings dialog for mavproxy
'''
def __init__(self, settings):
self.settings = settings
self.parent_pipe,self.child_pipe = multiproc.Pipe()
self.close_event = multiproc.Event()
self.close_event.clear()
self.child = multiproc.Process(target=self.child_task)
self.child.start()
t = threading.Thread(target=self.watch_thread)
t.daemon = True
t.start()
def child_task(self):
'''child process - this holds all the GUI elements'''
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxsettings_ui import SettingsDlg
mp_util.child_close_fds()
app = wx.App(False)
dlg = SettingsDlg(self.settings)
dlg.parent_pipe = self.parent_pipe
dlg.ShowModal()
dlg.Destroy()
def watch_thread(self):
'''watch for settings changes from child'''
from MAVProxy.modules.lib.mp_settings import MPSetting
while True:
setting = self.child_pipe.recv()
if not isinstance(setting, MPSetting):
break
try:
self.settings.set(setting.name, setting.value)
except Exception:
print("Unable to set %s to %s" % (setting.name, setting.value))
def is_alive(self):
'''check if child is still going'''
return self.child.is_alive()
|
class WXSettings(object):
'''
a graphical settings dialog for mavproxy
'''
def __init__(self, settings):
pass
def child_task(self):
'''child process - this holds all the GUI elements'''
pass
def watch_thread(self):
'''watch for settings changes from child'''
pass
def is_alive(self):
'''check if child is still going'''
pass
| 5 | 4 | 9 | 0 | 8 | 1 | 2 | 0.18 | 1 | 4 | 2 | 0 | 4 | 5 | 4 | 4 | 44 | 4 | 34 | 18 | 24 | 6 | 34 | 18 | 24 | 4 | 1 | 2 | 7 |
7,087 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsettings_ui.py
|
MAVProxy.modules.lib.wxsettings_ui.SettingsDlg
|
class SettingsDlg(TabbedDialog):
def __init__(self, settings):
title = "Resize the dialog and see how controls adapt!"
self.settings = settings
tabs = []
for k in self.settings.list():
setting = self.settings.get_setting(k)
tab = setting.tab
if tab is None:
tab = 'Settings'
if not tab in tabs:
tabs.append(tab)
title = self.settings.get_title()
if title is None:
title = 'Settings'
TabbedDialog.__init__(self, tabs, title)
for name in self.settings.list():
setting = self.settings.get_setting(name)
if setting.type == bool:
self.add_choice(setting, ['True', 'False'])
elif setting.choice is not None:
self.add_choice(setting, setting.choice)
elif setting.type == int and setting.increment is not None and setting.range is not None:
self.add_intspin(setting)
elif setting.type == float and setting.increment is not None and setting.range is not None:
self.add_floatspin(setting)
else:
self.add_text(setting)
self.refit()
|
class SettingsDlg(TabbedDialog):
def __init__(self, settings):
pass
| 2 | 0 | 28 | 0 | 28 | 0 | 10 | 0 | 1 | 3 | 0 | 0 | 1 | 1 | 1 | 14 | 29 | 0 | 29 | 9 | 27 | 0 | 25 | 9 | 23 | 10 | 2 | 2 | 10 |
7,088 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxsettings_ui.py
|
MAVProxy.modules.lib.wxsettings_ui.TabbedDialog
|
class TabbedDialog(wx.Dialog):
def __init__(self, tab_names, title='Title', size=wx.DefaultSize):
wx.Dialog.__init__(self, None, -1, title,
style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
self.tab_names = tab_names
self.notebook = wx.Notebook(self, -1, size=size)
self.panels = {}
self.sizers = {}
for t in tab_names:
self.panels[t] = wx.Panel(self.notebook)
self.notebook.AddPage(self.panels[t], t)
self.sizers[t] = wx.BoxSizer(wx.VERTICAL)
self.panels[t].SetSizer(self.sizers[t])
self.dialog_sizer = wx.BoxSizer(wx.VERTICAL)
self.dialog_sizer.Add(self.notebook, 1, wx.EXPAND|wx.ALL, 5)
self.controls = {}
self.browse_option_map = {}
self.control_map = {}
self.setting_map = {}
button_box = wx.BoxSizer(wx.HORIZONTAL)
self.button_apply = wx.Button(self, -1, "Apply")
self.button_cancel = wx.Button(self, -1, "Cancel")
self.button_save = wx.Button(self, -1, "Save")
self.button_load = wx.Button(self, -1, "Load")
button_box.Add(self.button_cancel, 0, wx.ALL)
button_box.Add(self.button_apply, 0, wx.ALL)
button_box.Add(self.button_save, 0, wx.ALL)
button_box.Add(self.button_load, 0, wx.ALL)
self.dialog_sizer.Add(button_box, 0, wx.GROW|wx.ALL, 5)
self.Bind(wx.EVT_BUTTON, self.on_cancel, self.button_cancel)
self.Bind(wx.EVT_BUTTON, self.on_apply, self.button_apply)
self.Bind(wx.EVT_BUTTON, self.on_save, self.button_save)
self.Bind(wx.EVT_BUTTON, self.on_load, self.button_load)
self.Centre()
def on_cancel(self, event):
'''called on cancel'''
self.Destroy()
def on_apply(self, event):
'''called on apply'''
for label in self.setting_map.keys():
setting = self.setting_map[label]
ctrl = self.controls[label]
value = ctrl.GetValue()
if str(value) != str(setting.value):
oldvalue = setting.value
if not setting.set(value):
print("Invalid value %s for %s" % (value, setting.name))
continue
if str(oldvalue) != str(setting.value):
self.parent_pipe.send(setting)
def on_save(self, event):
'''called on save button'''
dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*',
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
self.settings.save(dlg.GetPath())
def on_load(self, event):
'''called on load button'''
dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*', wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.settings.load(dlg.GetPath())
# update the controls with new values
for label in self.setting_map.keys():
setting = self.setting_map[label]
ctrl = self.controls[label]
value = ctrl.GetValue()
# Python 2 compatiblility - alternative is:
# import six
# isinstance(value, six.string_types)
if isinstance(value, str) \
or isinstance(value, str if sys.version_info[0] >= 3 else unicode):
ctrl.SetValue(str(setting.value))
else:
ctrl.SetValue(setting.value)
def panel(self, tab_name):
'''return the panel for a named tab'''
return self.panels[tab_name]
def sizer(self, tab_name):
'''return the sizer for a named tab'''
return self.sizers[tab_name]
def refit(self):
'''refit after elements are added'''
self.SetSizerAndFit(self.dialog_sizer)
def _add_input(self, setting, ctrl, ctrl2=None, value=None):
tab_name = setting.tab
label = setting.label
tab = self.panel(tab_name)
box = wx.BoxSizer(wx.HORIZONTAL)
labelctrl = wx.StaticText(tab, -1, label )
box.Add(labelctrl, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
box.Add( ctrl, 1, wx.ALIGN_CENTRE|wx.ALL, 5 )
if ctrl2 is not None:
box.Add( ctrl2, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
self.sizer(tab_name).Add(box, 0, wx.GROW|wx.ALL, 5)
self.controls[label] = ctrl
if value is not None:
ctrl.Value = value
else:
ctrl.Value = str(setting.value)
self.control_map[ctrl.GetId()] = label
self.setting_map[label] = setting
def add_text(self, setting, width=300, height=100, multiline=False):
'''add a text input line'''
tab = self.panel(setting.tab)
if multiline:
ctrl = wx.TextCtrl(tab, -1, "", size=(width,height), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
else:
ctrl = wx.TextCtrl(tab, -1, "", size=(width,-1) )
self._add_input(setting, ctrl)
def add_choice(self, setting, choices):
'''add a choice input line'''
tab = self.panel(setting.tab)
default = setting.value
if default is None:
default = choices[0]
ctrl = wx.ComboBox(tab, -1, choices=choices,
value = str(default),
style = wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT )
self._add_input(setting, ctrl)
def add_intspin(self, setting):
'''add a spin control'''
tab = self.panel(setting.tab)
default = setting.value
(minv, maxv) = setting.range
ctrl = wx.SpinCtrl(tab, -1,
initial = default,
min = minv,
max = maxv)
self._add_input(setting, ctrl, value=default)
def add_floatspin(self, setting):
'''add a floating point spin control'''
from wx.lib.agw.floatspin import FloatSpin
tab = self.panel(setting.tab)
default = setting.value
(minv, maxv) = setting.range
ctrl = FloatSpin(tab, -1,
value = default,
min_val = minv,
max_val = maxv,
increment = setting.increment)
if setting.format is not None:
ctrl.SetFormat(setting.format)
if setting.digits is not None:
ctrl.SetDigits(setting.digits)
self._add_input(setting, ctrl, value=default)
|
class TabbedDialog(wx.Dialog):
def __init__(self, tab_names, title='Title', size=wx.DefaultSize):
pass
def on_cancel(self, event):
'''called on cancel'''
pass
def on_apply(self, event):
'''called on apply'''
pass
def on_save(self, event):
'''called on save button'''
pass
def on_load(self, event):
'''called on load button'''
pass
def panel(self, tab_name):
'''return the panel for a named tab'''
pass
def sizer(self, tab_name):
'''return the sizer for a named tab'''
pass
def refit(self):
'''refit after elements are added'''
pass
def _add_input(self, setting, ctrl, ctrl2=None, value=None):
pass
def add_text(self, setting, width=300, height=100, multiline=False):
'''add a text input line'''
pass
def add_choice(self, setting, choices):
'''add a choice input line'''
pass
def add_intspin(self, setting):
'''add a spin control'''
pass
def add_floatspin(self, setting):
'''add a floating point spin control'''
pass
| 14 | 11 | 11 | 0 | 10 | 1 | 2 | 0.12 | 1 | 1 | 0 | 1 | 13 | 13 | 13 | 13 | 159 | 14 | 130 | 59 | 115 | 15 | 115 | 59 | 100 | 5 | 1 | 3 | 29 |
7,089 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxrc.py
|
MAVProxy.modules.lib.wxrc.RCStatus
|
class RCStatus():
'''
A RC input and Servo output GUI for MAVProxy.
'''
def __init__(self, panelType=PanelType.RC_IN):
self.panelType = panelType
# 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()
def child_task(self):
'''child process - this holds all the GUI elements'''
# from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
# Create wx application
app = wx.App(False)
app.frame = RCFrame(panelType=self.panelType, child_pipe_recv=self.child_pipe_recv)
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)
self.parent_pipe_send.close()
self.child_pipe_recv.close()
def is_alive(self):
'''check if child is still going'''
return self.child.is_alive()
def processPacket(self, m):
'''Send mavlink packet onwards to panel'''
self.parent_pipe_send.send(m)
|
class RCStatus():
'''
A RC input and Servo output GUI for MAVProxy.
'''
def __init__(self, panelType=PanelType.RC_IN):
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
def processPacket(self, m):
'''Send mavlink packet onwards to panel'''
pass
| 6 | 5 | 6 | 0 | 5 | 2 | 1 | 0.42 | 0 | 2 | 2 | 0 | 5 | 5 | 5 | 5 | 40 | 4 | 26 | 12 | 19 | 11 | 26 | 12 | 19 | 2 | 0 | 1 | 6 |
7,090 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxrc.py
|
MAVProxy.modules.lib.wxrc.RCPanel
|
class RCPanel(wx.lib.scrolledpanel.ScrolledPanel):
def __init__(self, parent, panelType=PanelType.RC_IN):
super().__init__(parent)
self.rc_labels = []
self.rc_gauges = []
self.rc_sizers = []
self.panelType = panelType
self.sizer_main = wx.BoxSizer(wx.VERTICAL)
if self.panelType == PanelType.RC_IN:
self.create_rc_widgets(18)
else:
self.create_rc_widgets(16)
self.SetSizer(self.sizer_main)
self.SetupScrolling()
def create_rc_widgets(self, num_channels, starting_id=0):
for i in range(num_channels):
curChanSizer = wx.BoxSizer(wx.HORIZONTAL)
label = wx.StaticText(self, label="{0} Channel {1}:".format(str(self.panelType.short_string),
str(i+1+starting_id)))
gauge = PG.PyGauge(self, range=2000, size=(200, 25), style=wx.GA_HORIZONTAL) # Assuming RC values range from 1000 to 2000
gauge.SetDrawValue(draw=True, drawPercent=False, font=None, colour=wx.BLACK, formatString=None)
gauge.SetBarColour(wx.GREEN)
gauge.SetBackgroundColour(wx.WHITE)
gauge.SetBorderColor(wx.BLACK)
gauge.SetValue(0)
self.sizer_main.Add(curChanSizer, 1, wx.EXPAND, 0)
self.rc_labels.append(label)
self.rc_gauges.append(gauge)
curChanSizer.Add(label, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
curChanSizer.Add(gauge, 1, wx.ALL | wx.EXPAND, 5)
self.rc_sizers.append(curChanSizer)
def update_gauges(self, msg):
# Update the gauges based on the relevant mavlink packet info
# Returns 1 if the window needs to be resized to fit additional gauges
# If the vehicle is using >16 servo_outs, need to update the GUI
if len(self.rc_gauges) == 16 and self.panelType == PanelType.SERVO_OUT and getattr(msg, 'port', 0) == 1:
# add another 16 gauges
self.create_rc_widgets(16, starting_id=16)
self.Layout()
self.SetupScrolling()
return 1
for i, gauge in enumerate(self.rc_gauges):
if msg.get_type() == 'RC_CHANNELS' and self.panelType == PanelType.RC_IN:
value = getattr(msg, 'chan{0}_raw'.format(i+1), 0)
if value > gauge.GetRange():
gauge.SetRange(value + 50)
gauge.SetValue(value)
gauge.Refresh()
elif (msg.get_type() == 'SERVO_OUTPUT_RAW' and self.panelType == PanelType.SERVO_OUT and
getattr(msg, 'port', 0) == 0) and i < 16:
value = getattr(msg, 'servo{0}_raw'.format(i+1), 0)
if value > gauge.GetRange():
gauge.SetRange(value + 50)
gauge.SetValue(value)
gauge.Refresh()
elif (msg.get_type() == 'SERVO_OUTPUT_RAW' and self.panelType == PanelType.SERVO_OUT and
getattr(msg, 'port', 0) == 1) and i >= 17:
# 2nd bank of servos (17-32), if used
value = getattr(msg, 'servo{0}_raw'.format(i+1-16), 0)
if value > gauge.GetRange():
gauge.SetRange(value + 50)
gauge.SetValue(value)
gauge.Refresh()
return 0
|
class RCPanel(wx.lib.scrolledpanel.ScrolledPanel):
def __init__(self, parent, panelType=PanelType.RC_IN):
pass
def create_rc_widgets(self, num_channels, starting_id=0):
pass
def update_gauges(self, msg):
pass
| 4 | 0 | 22 | 1 | 19 | 2 | 4 | 0.1 | 1 | 5 | 1 | 0 | 3 | 5 | 3 | 3 | 70 | 6 | 59 | 15 | 55 | 6 | 53 | 15 | 49 | 9 | 1 | 3 | 13 |
7,091 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxrc.py
|
MAVProxy.modules.lib.wxrc.RCFrame
|
class RCFrame(wx.Frame):
def __init__(self, panelType, child_pipe_recv):
super().__init__(None, title=panelType.display_string)
self.panel = RCPanel(self, panelType)
self.Bind(wx.EVT_CLOSE, self.on_close)
self.panel.sizer_main.Fit(self)
# self.Center()
self.Layout()
self.child_pipe_recv = child_pipe_recv
# Start a separate timer to update RC data
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.timer.Start(100)
def on_timer(self, event):
'''Main Loop.'''
while self.child_pipe_recv.poll():
msg = self.child_pipe_recv.recv()
if msg:
if self.panel.update_gauges(msg) == 1:
self.SetSize(self.GetSize()[0] + 30, self.GetSize()[1])
def on_close(self, event):
self.Destroy()
|
class RCFrame(wx.Frame):
def __init__(self, panelType, child_pipe_recv):
pass
def on_timer(self, event):
'''Main Loop.'''
pass
def on_close(self, event):
pass
| 4 | 1 | 8 | 1 | 6 | 1 | 2 | 0.16 | 1 | 2 | 1 | 0 | 3 | 3 | 3 | 3 | 26 | 4 | 19 | 8 | 15 | 3 | 19 | 8 | 15 | 4 | 1 | 3 | 6 |
7,092 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxrc.py
|
MAVProxy.modules.lib.wxrc.PanelType
|
class PanelType(Enum):
SERVO_OUT = (0, "Servo Out", "Servo")
RC_IN = (1, "RC In", "RC")
def __new__(cls, value, display_string, short_string):
obj = object.__new__(cls)
obj._value_ = value
obj.display_string = display_string
obj.short_string = short_string
return obj
|
class PanelType(Enum):
def __new__(cls, value, display_string, short_string):
pass
| 2 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 50 | 10 | 1 | 9 | 5 | 7 | 0 | 9 | 5 | 7 | 1 | 4 | 0 | 1 |
7,093 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_SIYI/camera_view.py
|
MAVProxy.modules.mavproxy_SIYI.camera_view.CameraView
|
class CameraView:
"""handle camera view image"""
def __init__(self, siyi, rtsp_url, filename, res, thermal=False, fps=10, video_idx=-1):
self.siyi = siyi
self.thermal = thermal
self.im = None
self.im_colormap = "MAGMA"
self.tracking = False
self.cap = None
self.res = res
self.rtsp_url = rtsp_url
self.filename = filename
self.last_frame_t = time.time()
self.fps = fps
self.frame_counter = -1
self.video_idx = video_idx
self.im = MPImage(
title="Camera View",
mouse_events=True,
mouse_movement_events=self.thermal,
width=self.res[0],
height=self.res[1],
key_events=True,
can_drag=False,
can_zoom=False,
auto_size=False,
auto_fit=True,
fps = 30,
)
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"))
if self.thermal:
colormaps = [
"Threshold",
"GloryHot",
"AUTUMN",
"BONE",
"JET",
"WINTER",
"RAINBOW",
"OCEAN",
"SUMMER",
"SPRING",
"COOL",
"HSV",
"PINK",
"HOT",
"PARULA",
"MAGMA",
"INFERNO",
"PLASMA",
"VIRIDIS",
"CIVIDIS",
"TWILIGHT",
"TWILIGHT_SHIFTED",
"TURBO",
"DEEPGREEN",
"None",
]
for c in colormaps:
popup.add_to_submenu(
["ColorMap"], MPMenuItem(c, returnkey="COLORMAP_" + c)
)
else:
popup.add_to_submenu(
["Lens"], MPMenuItem("WideAngle", returnkey="Lens:wide")
)
popup.add_to_submenu(["Lens"], MPMenuItem("Zoom", returnkey="Lens:zoom"))
popup.add_to_submenu(
["Lens"], MPMenuItem("SplitScreen", returnkey="Lens:split")
)
for z in range(1, 11):
popup.add_to_submenu(
["Zoom"], MPMenuItem("%ux" % z, returnkey="Zoom:%u" % z)
)
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"))
gst_pipeline = "rtspsrc location={0} latency=0 buffer-mode=auto ! rtph265depay ! tee name=tee1 tee1. ! queue ! h265parse ! avdec_h265 ! videoconvert ! video/x-raw,format=BGRx ! appsink tee1. ! queue ! h265parse config-interval=15 ! video/x-h265 ! mpegtsmux ! filesink location={1}".format(
self.rtsp_url, self.filename
)
self.im.set_gstreamer(gst_pipeline)
if self.thermal:
self.im.set_colormap(self.im_colormap)
self.im.set_colormap("None")
self.siyi.cmd_palette(["WhiteHot"])
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
title += " (mode %s)" % self.siyi.click_mode
self.im.set_title(title)
def get_pixel_temp(self, event):
"""get temperature of a pixel"""
if event.pixel is None:
return -1
v = event.pixel[0]
gmin = 0
gmax = 255
if self.siyi is None:
return -1
return self.siyi.tmin + ((v - gmin) / float(gmax - gmin)) * (
self.siyi.tmax - self.siyi.tmin
)
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"""
if self.siyi is None:
return
if self.thermal:
self.set_title(
"Thermal View TEMP=%.2fC RANGE(%.2fC to %.2fC)"
% (self.siyi.spot_temp, self.siyi.tmin, self.siyi.tmax)
)
elif self.siyi.rgb_lens == "zoom":
self.set_title("Zoom View %.1fx" % self.siyi.last_zoom)
else:
self.set_title("Wide View")
def xy_to_latlon(self, x, y, shape):
'''convert x,y pixel coordinates to a latlon tuple'''
(yres, xres, depth) = shape
x = (2 * x / float(xres)) - 1.0
y = (2 * y / float(yres)) - 1.0
aspect_ratio = float(xres) / yres
if self.thermal:
FOV = self.siyi.siyi_settings.thermal_fov
elif self.siyi.rgb_lens == "zoom":
FOV = self.siyi.siyi_settings.zoom_fov / self.siyi.last_zoom
else:
FOV = self.siyi.siyi_settings.wide_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("COLORMAP_Threshold"):
d = self.create_colormap_dict()
self.im.set_colormap(d)
self.siyi.cmd_palette(["WhiteHot"])
if event.returnkey.startswith("COLORMAP_GloryHot"):
self.im.set_colormap("None")
self.siyi.cmd_palette(["GloryHot"])
elif event.returnkey.startswith("COLORMAP_"):
self.im.set_colormap(event.returnkey[9:])
self.siyi.cmd_palette(["WhiteHot"])
elif 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.startswith("Lens:") and self.siyi is not None:
self.siyi.cmd_imode([event.returnkey[5:]])
elif event.returnkey.startswith("Zoom:") and self.siyi is not None:
self.siyi.cmd_zoom([event.returnkey[5:]])
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, event.shape)
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
self.siyi.log_frame_counter(self.video_idx, self.thermal, self.frame_counter)
continue
if event.ClassName == "wxMouseEvent":
if event.pixel is not None:
self.siyi.spot_temp = self.get_pixel_temp(event)
self.update_title()
if (
event.ClassName == "wxMouseEvent"
and event.leftIsDown
and event.pixel is not None
and self.siyi is not None
):
latlonalt = self.xy_to_latlon(event.x, event.y, event.shape)
if latlonalt is None:
continue
if event.shiftDown:
(xres,yres) = (event.shape[1], event.shape[0])
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 CameraView:
'''handle camera view image'''
def __init__(self, siyi, rtsp_url, filename, res, thermal=False, fps=10, video_idx=-1):
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, shape):
'''convert x,y pixel coordinates to a latlon tuple'''
pass
def check_events(self):
'''check for image events'''
pass
| 12 | 10 | 22 | 1 | 20 | 1 | 5 | 0.05 | 0 | 8 | 4 | 0 | 10 | 13 | 10 | 10 | 251 | 19 | 222 | 52 | 210 | 10 | 150 | 52 | 138 | 24 | 0 | 3 | 50 |
7,094 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.WaypointInfo
|
class WaypointInfo():
'''Current and final waypoint numbers, and the distance
to the current waypoint.'''
def __init__(self,current,final,currentDist,nextWPTime,wpBearing):
self.current = current
self.final = final
self.currentDist = currentDist
self.nextWPTime = nextWPTime
self.wpBearing = wpBearing
|
class WaypointInfo():
'''Current and final waypoint numbers, and the distance
to the current waypoint.'''
def __init__(self,current,final,currentDist,nextWPTime,wpBearing):
pass
| 2 | 1 | 6 | 0 | 6 | 0 | 1 | 0.29 | 0 | 0 | 0 | 0 | 1 | 5 | 1 | 1 | 9 | 0 | 7 | 7 | 5 | 2 | 7 | 7 | 5 | 1 | 0 | 0 | 1 |
7,095 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.Global_Position_INT
|
class Global_Position_INT():
'''Altitude relative to ground (GPS).'''
def __init__(self,gpsINT,curTime):
self.relAlt = gpsINT.relative_alt/1000.0
self.curTime = curTime
|
class Global_Position_INT():
'''Altitude relative to ground (GPS).'''
def __init__(self,gpsINT,curTime):
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,096 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.FlightState
|
class FlightState():
'''Mode and arm state.'''
def __init__(self,mode,armState):
self.mode = mode
self.armState = armState
|
class FlightState():
'''Mode and arm state.'''
def __init__(self,mode,armState):
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,097 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.FPS
|
class FPS():
'''Stores intended frame rate information.'''
def __init__(self,fps):
self.fps = fps
|
class FPS():
'''Stores intended frame rate information.'''
def __init__(self,fps):
pass
| 2 | 1 | 2 | 0 | 2 | 1 | 1 | 0.67 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 4 | 0 | 3 | 3 | 1 | 2 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
7,098 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.BatteryInfo
|
class BatteryInfo():
'''Voltage, current and remaning battery.'''
def __init__(self,batMsg):
self.voltage = batMsg.voltage_battery/1000.0 # Volts
self.current = batMsg.current_battery/100.0 # Amps
self.batRemain = batMsg.battery_remaining
|
class BatteryInfo():
'''Voltage, current and remaning battery.'''
def __init__(self,batMsg):
pass
| 2 | 1 | 4 | 0 | 4 | 3 | 1 | 0.8 | 0 | 0 | 0 | 0 | 1 | 3 | 1 | 1 | 6 | 0 | 5 | 5 | 3 | 4 | 5 | 5 | 3 | 1 | 0 | 0 | 1 |
7,099 |
ArduPilot/MAVProxy
|
ArduPilot_MAVProxy/MAVProxy/modules/lib/wxhorizon_util.py
|
MAVProxy.modules.lib.wxhorizon_util.Attitude
|
class Attitude():
'''The current Attitude Data'''
def __init__(self, attitudeMsg):
self.pitch = attitudeMsg.pitch
self.roll = attitudeMsg.roll
self.yaw = attitudeMsg.yaw
|
class Attitude():
'''The current Attitude Data'''
def __init__(self, attitudeMsg):
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.