INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
draw a series of connected lines on the map, calling callback when done
|
def draw_lines(self, callback):
'''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_line = []
self.map.add_object(mp_slipmap.SlipDefaultPopup(None))
|
called when user selects "Set Home" on map
|
def cmd_set_homepos(self, args):
'''called when user selects "Set Home" on map'''
(lat, lon) = (self.click_position[0], self.click_position[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)
|
called when user selects "Set Origin (with height)" on map
|
def cmd_set_origin(self, args):
'''called when user selects "Set Origin (with height)" on map'''
(lat, lon) = (self.click_position[0], self.click_position[1])
alt = self.ElevationMap.GetElevation(lat, lon)
print("Setting origin to: ", lat, lon, alt)
self.master.mav.set_gps_global_origin_send(
self.settings.target_system,
lat*10000000, # lat
lon*10000000, # lon
alt*1000)
|
called when user selects "Set Origin" on map
|
def cmd_set_originpos(self, args):
'''called when user selects "Set Origin" on map'''
(lat, lon) = (self.click_position[0], self.click_position[1])
print("Setting origin to: ", lat, lon)
self.master.mav.set_gps_global_origin_send(
self.settings.target_system,
lat*10000000, # lat
lon*10000000, # lon
0*1000)
|
control zoom
|
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)
|
control center of view
|
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)
|
control following of vehicle
|
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)
|
show 2nd vehicle on map
|
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.ElevationMap.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))
|
handle an incoming mavlink packet
|
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":
vname = 'plane'
if m.type in [mavutil.mavlink.MAV_TYPE_FIXED_WING]:
vname = 'plane'
elif m.type in [mavutil.mavlink.MAV_TYPE_GROUND_ROVER]:
vname = 'rover'
elif m.type in [mavutil.mavlink.MAV_TYPE_SUBMARINE]:
vname = 'sub'
elif m.type in [mavutil.mavlink.MAV_TYPE_SURFACE_BOAT]:
vname = 'boat'
elif m.type in [mavutil.mavlink.MAV_TYPE_QUADROTOR,
mavutil.mavlink.MAV_TYPE_HEXAROTOR,
mavutil.mavlink.MAV_TYPE_OCTOROTOR,
mavutil.mavlink.MAV_TYPE_TRICOPTER]:
vname = 'copter'
elif m.type in [mavutil.mavlink.MAV_TYPE_COAXIAL]:
vname = 'singlecopter'
elif m.type in [mavutil.mavlink.MAV_TYPE_HELICOPTER]:
vname = 'heli'
elif m.type in [mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER]:
vname = 'antenna'
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" and self.map_settings.showsimpos:
self.create_vehicle_icon('Sim' + vehicle, 'green')
self.map.set_position('Sim' + vehicle, (m.lat*1.0e-7, m.lng*1.0e-7), rotation=math.degrees(m.yaw))
elif mtype == "AHRS2" and self.map_settings.showahrs2pos:
self.create_vehicle_icon('AHRS2' + vehicle, 'blue')
self.map.set_position('AHRS2' + vehicle, (m.lat*1.0e-7, m.lng*1.0e-7), rotation=math.degrees(m.yaw))
elif mtype == "AHRS3" and self.map_settings.showahrs3pos:
self.create_vehicle_icon('AHRS3' + vehicle, 'orange')
self.map.set_position('AHRS3' + vehicle, (m.lat*1.0e-7, m.lng*1.0e-7), rotation=math.degrees(m.yaw))
elif mtype == "GPS_RAW_INT" and self.map_settings.showgpspos:
(lat, lon) = (m.lat*1.0e-7, m.lon*1.0e-7)
if lat != 0 or lon != 0:
if m.vel > 300 or 'ATTITUDE' not in self.master.messages:
cog = m.cog*0.01
else:
cog = math.degrees(self.master.messages['ATTITUDE'].yaw)
self.create_vehicle_icon('GPS' + vehicle, 'blue')
self.map.set_position('GPS' + vehicle, (lat, lon), rotation=cog)
elif mtype == "GPS2_RAW" and self.map_settings.showgps2pos:
(lat, lon) = (m.lat*1.0e-7, m.lon*1.0e-7)
if lat != 0 or lon != 0:
self.create_vehicle_icon('GPS2' + vehicle, 'green')
self.map.set_position('GPS2' + vehicle, (lat, lon), rotation=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[m.get_srcSystem()] = (lat,lon)
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.is_primary_vehicle(m))
elif mtype == 'LOCAL_POSITION_NED' and not self.have_global_position:
(lat, lon) = mp_util.gps_offset(0, 0, m.x, m.y)
self.lat_lon[m.get_srcSystem()] = (lat,lon)
heading = math.degrees(math.atan2(m.vy, m.vx))
self.create_vehicle_icon('Pos' + vehicle, 'red', follow=True)
self.map.set_position('Pos' + vehicle, (lat, lon), rotation=heading)
self.map.set_follow_object('Pos' + vehicle, self.is_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" ] and
m.get_srcSystem() in self.lat_lon):
(lat,lon) = self.lat_lon[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)))
else:
self.map.add_object(mp_slipmap.SlipClearLayer(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:
return
tlayer = 'PostionTarget%u' % m.get_srcSystem()
(lat,lon) = self.lat_lon[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.is_primary_vehicle(m):
# the rest should only be done for the primary vehicle
return
# if the waypoints have changed, redisplay
last_wp_change = self.module('wp').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()
# if the fence has changed, redisplay
if self.fence_change_time != self.module('fence').fenceloader.last_change:
self.display_fence()
# if the rallypoints have changed, redisplay
if self.rally_change_time != self.module('rally').rallyloader.last_change:
self.rally_change_time = self.module('rally').rallyloader.last_change
icon = self.map.icon('rallypoint.png')
self.map.add_object(mp_slipmap.SlipClearLayer('RallyPoints'))
for i in range(self.module('rally').rallyloader.rally_count()):
rp = self.module('rally').rallyloader.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))
# check for any events from the map
self.map.check_events()
|
control kml reading
|
def cmd_param(self, args):
'''control kml reading'''
usage = "Usage: kml <clear | load (filename) | layers | toggle (layername) | fence (layername)>"
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] == "fence":
self.fencekml(args[1])
else:
print(usage)
return
|
snap waypoints to KML
|
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()
|
snap fence to KML
|
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')
loader = fencemod.fenceloader
changed = False
for i in range(0,loader.count()):
fp = loader.point(i)
lat = fp.lat
lon = fp.lng
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 best[0] != lat or best[1] != lon:
loader.move(i, best[0], best[1])
print("Snapping fence point %u to %f %f" % (i, best[0], best[1]))
changed = True
elif best is not None:
if best_dist <= (threshold+1)*3:
print("Not snapping fence point %u dist %.1f" % (i, best_dist))
if changed:
fencemod.send_fence()
|
set a layer as the geofence
|
def fencekml(self, layername):
'''set a layer as the geofence'''
#Strip quotation marks if neccessary
if layername.startswith('"') and layername.endswith('"'):
layername = layername[1:-1]
#for each point in the layer, add it in
for layer in self.allayers:
if layer.key == layername:
#clear the current fence
self.fenceloader.clear()
if len(layer.points) < 3:
return
self.fenceloader.target_system = self.target_system
self.fenceloader.target_component = self.target_component
#send centrepoint to fence[0] as the return point
bounds = mp_util.polygon_bounds(layer.points)
(lat, lon, width, height) = bounds
center = (lat+width/2, lon+height/2)
self.fenceloader.add_latlon(center[0], center[1])
for lat, lon in layer.points:
#add point
self.fenceloader.add_latlon(lat, lon)
#and send
self.send_fence()
|
toggle the display of a kml
|
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.mpstate.map.remove_object(layer)
self.curlayers.remove(layername)
if layername in self.curtextlayers:
for clayer in self.curtextlayers:
if clayer == layername:
self.mpstate.map.remove_object(clayer)
self.curtextlayers.remove(clayer)
#toggle layer on (plus associated text element)
else:
for layer in self.allayers:
if layer.key == layername:
self.mpstate.map.add_object(layer)
self.curlayers.append(layername)
for alayer in self.alltextlayers:
if alayer.key == layername:
self.mpstate.map.add_object(alayer)
self.curtextlayers.append(layername)
self.menu_needs_refreshing = True
|
Clear the kmls from the map
|
def clearkml(self):
'''Clear the kmls from the map'''
#go through all the current layers and remove them
for layer in self.curlayers:
self.mpstate.map.remove_object(layer)
for layer in self.curtextlayers:
self.mpstate.map.remove_object(layer)
self.allayers = []
self.curlayers = []
self.alltextlayers = []
self.curtextlayers = []
self.menu_needs_refreshing = True
|
Load a kml from file and put it on the map
|
def loadkml(self, filename):
'''Load a kml from file and put it on the map'''
#Open the zip file
nodes = self.readkmz(filename)
self.snap_points = []
#go through each object in the kml...
for n in nodes:
point = self.readObject(n)
#and place any polygons on the map
if self.mpstate.map is not None and point[0] == 'Polygon':
self.snap_points.extend(point[2])
#print("Adding " + point[1])
newcolour = (random.randint(0, 255), 0, random.randint(0, 255))
curpoly = mp_slipmap.SlipPolygon(point[1], point[2],
layer=2, linewidth=2, colour=newcolour)
self.mpstate.map.add_object(curpoly)
self.allayers.append(curpoly)
self.curlayers.append(point[1])
#and points - barrell image and text
if self.mpstate.map is not None and point[0] == 'Point':
#print("Adding " + point[1])
icon = self.mpstate.map.icon('barrell.png')
curpoint = mp_slipmap.SlipIcon(point[1], latlon = (point[2][0][0], point[2][0][1]), layer=3, img=icon, 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.mpstate.map.add_object(curpoint)
self.mpstate.map.add_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
|
handle GUI elements
|
def idle_task(self):
'''handle GUI elements'''
if not self.menu_needs_refreshing:
return
if self.module('map') is not None and not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu)
#(re)create the menu
if mp_util.has_wxpython and self.menu_added_map:
# 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 in self.curlayers and layer.key[-5:] != "-text":
self.menu.items.append(MPMenuCheckbox(layer.key, layer.key, '# kml toggle \"' + layer.key + '\"', checked=True))
elif layer.key[-5:] != "-text":
self.menu.items.append(MPMenuCheckbox(layer.key, layer.key, '# kml toggle \"' + layer.key + '\"', checked=False))
#and add the menu to the map popu menu
self.module('map').add_menu(self.menu)
self.menu_needs_refreshing = False
|
reads in a kmz file and returns xml nodes
|
def readkmz(self, filename):
'''reads in a kmz file and returns xml nodes'''
#Strip quotation marks if neccessary
filename.strip('"')
#Open the zip file (as applicable)
if filename[-4:] == '.kml':
fo = open(filename, "r")
fstring = fo.read()
fo.close()
elif filename[-4:] == '.kmz':
zip=ZipFile(filename)
for z in zip.filelist:
if z.filename[-4:] == '.kml':
fstring=zip.read(z)
break
else:
raise Exception("Could not find kml file in %s" % filename)
else:
raise Exception("Is not a valid kml or kmz file in %s" % filename)
#send into the xml parser
kmlstring = parseString(fstring)
#get all the placenames
nodes=kmlstring.getElementsByTagName('Placemark')
return nodes
|
reads in a node and returns as a tuple: (type, name, points[])
|
def readObject(self, innode):
'''reads in a node and returns as a tuple: (type, name, points[])'''
#get name
names=innode.getElementsByTagName('name')[0].childNodes[0].data.strip()
#get type
pointType = 'Unknown'
if len(innode.getElementsByTagName('LineString')) == 0 and len(innode.getElementsByTagName('Point')) == 0:
pointType = 'Polygon'
elif len(innode.getElementsByTagName('Polygon')) == 0 and len(innode.getElementsByTagName('Point')) == 0:
pointType = 'Polygon'
elif len(innode.getElementsByTagName('LineString')) == 0 and len(innode.getElementsByTagName('Polygon')) == 0:
pointType = 'Point'
#get coords
coords = innode.getElementsByTagName('coordinates')[0].childNodes[0].data.strip()
coordsSplit = coords.split()
ret_s = []
for j in coordsSplit:
jcoord = j.split(',')
if len(jcoord) == 3 and jcoord[0] != '' and jcoord[1] != '':
#print("Got lon " + jcoord[0] + " and lat " + jcoord[1])
ret_s.append((float(jcoord[1]), float(jcoord[0])))
#return tuple
return (str(pointType), str(names), ret_s)
|
asterix command parser
|
def cmd_asterix(self, args):
'''asterix command parser'''
usage = "usage: asterix <set|start|stop|restart|status>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
self.asterix_settings.command(args[1:])
elif args[0] == "start":
self.start_listener()
elif args[0] == "stop":
self.stop_listener()
elif args[0] == "restart":
self.stop_listener()
self.start_listener()
elif args[0] == "status":
self.print_status()
else:
print(usage)
|
start listening for packets
|
def start_listener(self):
'''start listening for packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', self.asterix_settings.port))
self.sock.setblocking(False)
print("Started on port %u" % self.asterix_settings.port)
|
stop listening for packets
|
def stop_listener(self):
'''stop listening for packets'''
if self.sock is not None:
self.sock.close()
self.sock = None
self.tracks = {}
|
store second vehicle position for filtering purposes
|
def set_secondary_vehicle_position(self, m):
'''store second vehicle position for filtering purposes'''
if m.get_type() != 'GLOBAL_POSITION_INT':
return
(lat, lon, heading) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01)
if abs(lat) < 1.0e-3 and abs(lon) < 1.0e-3:
return
self.vehicle2_pos = VehiclePos(m)
|
return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds
|
def could_collide_hor(self, vpos, adsb_pkt):
'''return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds'''
margin = self.asterix_settings.filter_dist_xy
timeout = self.asterix_settings.filter_time
alat = adsb_pkt.lat * 1.0e-7
alon = adsb_pkt.lon * 1.0e-7
avel = adsb_pkt.hor_velocity * 0.01
vvel = sqrt(vpos.vx**2 + vpos.vy**2)
dist = mp_util.gps_distance(vpos.lat, vpos.lon, alat, alon)
dist -= avel * timeout
dist -= vvel * timeout
if dist <= margin:
return True
return False
|
return true if vehicle could come within filter_dist_z meters of adsb vehicle in timeout seconds
|
def could_collide_ver(self, vpos, adsb_pkt):
'''return true if vehicle could come within filter_dist_z meters of adsb vehicle in timeout seconds'''
if adsb_pkt.emitter_type < 100 or adsb_pkt.emitter_type > 104:
return True
margin = self.asterix_settings.filter_dist_z
vtype = adsb_pkt.emitter_type - 100
valt = vpos.alt
aalt1 = adsb_pkt.altitude * 0.001
if vtype == 2:
# weather, always yes
return True
if vtype == 4:
# bird of prey, always true
return True
# planes and migrating birds have 150m margin
aalt2 = aalt1 + adsb_pkt.ver_velocity * 0.01 * self.asterix_settings.filter_time
altsep1 = abs(valt - aalt1)
altsep2 = abs(valt - aalt2)
if altsep1 > 150 + margin and altsep2 > 150 + margin:
return False
return True
|
called on idle
|
def idle_task(self):
'''called on idle'''
if self.sock is None:
return
try:
pkt = self.sock.recv(10240)
except Exception:
return
try:
if pkt.startswith(b'PICKLED:'):
pkt = pkt[8:]
# pickled packet
try:
amsg = [pickle.loads(pkt)]
except pickle.UnpicklingError:
amsg = asterix.parse(pkt)
else:
amsg = asterix.parse(pkt)
self.pkt_count += 1
self.console.set_status('ASTX', 'ASTX %u/%u' % (self.pkt_count, self.adsb_packets_sent), row=6)
except Exception:
print("bad packet")
return
try:
logpkt = b'AST:' + struct.pack('<dI', time.time(), len(pkt)) + pkt
self.logfile.write(logpkt)
except Exception:
pass
for m in amsg:
if self.asterix_settings.debug > 1:
print(m)
lat = m['I105']['Lat']['val']
lon = m['I105']['Lon']['val']
alt_f = m['I130']['Alt']['val']
climb_rate_fps = m['I220']['RoC']['val']
sac = m['I010']['SAC']['val']
sic = m['I010']['SIC']['val']
trkn = m['I040']['TrkN']['val']
# fake ICAO_address
icao_address = trkn & 0xFFFF
# use squawk for time in 0.1 second increments. This allows for old msgs to be discarded on vehicle
# when using more than one link to vehicle
squawk = (int(self.mpstate.attitude_time_s * 10) & 0xFFFF)
alt_m = alt_f * 0.3048
# asterix is WGS84, ArduPilot uses AMSL, which is EGM96
alt_m += self.asterix_settings.wgs84_to_AMSL
# consider filtering this packet out; if it's not close to
# either home or the vehicle position don't send it
adsb_pkt = self.master.mav.adsb_vehicle_encode(icao_address,
int(lat*1e7),
int(lon*1e7),
mavutil.mavlink.ADSB_ALTITUDE_TYPE_GEOMETRIC,
int(alt_m*1000), # mm
0, # heading
0, # hor vel
int(climb_rate_fps * 0.3048 * 100), # cm/s
"%08x" % icao_address,
100 + (trkn // 10000),
1.0,
(mavutil.mavlink.ADSB_FLAGS_VALID_COORDS |
mavutil.mavlink.ADSB_FLAGS_VALID_ALTITUDE |
mavutil.mavlink.ADSB_FLAGS_VALID_VELOCITY |
mavutil.mavlink.ADSB_FLAGS_VALID_HEADING),
squawk)
if icao_address in self.tracks:
self.tracks[icao_address].update(adsb_pkt, self.get_time())
else:
self.tracks[icao_address] = Track(adsb_pkt)
if self.asterix_settings.debug > 0:
print(adsb_pkt)
# send on all links
if self.should_send_adsb_pkt(adsb_pkt):
self.adsb_packets_sent += 1
for i in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[i]
#if adsb_pkt.hor_velocity < 1:
# print(adsb_pkt)
conn.mav.send(adsb_pkt)
else:
self.adsb_packets_not_sent += 1
adsb_mod = self.module('adsb')
if adsb_mod:
# the adsb module is loaded, display on the map
adsb_mod.mavlink_packet(adsb_pkt)
try:
for sysid in self.mpstate.sysid_outputs:
# fwd to sysid clients
adsb_pkt.pack(self.mpstate.sysid_outputs[sysid].mav)
self.mpstate.sysid_outputs[sysid].write(adsb_pkt.get_msgbuf())
except Exception:
pass
now = time.time()
delta = now - self.adsb_byterate_update_timestamp
if delta > 5:
self.adsb_byterate_update_timestamp = now
bytes_per_adsb_packet = 38 # FIXME: find constant
self.adsb_byterate = (self.adsb_packets_sent - self.adsb_last_packets_sent)/delta * bytes_per_adsb_packet
self.adsb_last_packets_sent = self.adsb_packets_sent
|
get time from mavlink ATTITUDE
|
def mavlink_packet(self, m):
'''get time from mavlink ATTITUDE'''
if m.get_type() == 'GLOBAL_POSITION_INT':
if abs(m.lat) < 1000 and abs(m.lon) < 1000:
return
self.vehicle_pos = VehiclePos(m)
|
control behaviour of the module
|
def cmd_system_time(self, args):
'''control behaviour of the module'''
if len(args) == 0:
print(self.usage())
elif args[0] == "status":
print(self.status())
elif args[0] == "set":
self.system_time_settings.command(args[1:])
else:
print(self.usage())
|
called rapidly by mavproxy
|
def idle_task(self):
'''called rapidly by mavproxy'''
now = time.time()
if now-self.last_sent > self.system_time_settings.interval:
self.last_sent = now
time_us = time.time() * 1000000
if self.system_time_settings.verbose:
print("ST: Sending system time: (%u/%u)" %
(time_us, self.uptime(),))
self.master.mav.system_time_send(time_us,
self.uptime())
if (now-self.last_sent_timesync >
self.system_time_settings.interval_timesync):
self.last_sent_timesync = now
time_ns = time.time() * 1000000000
time_ns += 1234
if self.system_time_settings.verbose:
print("ST: Sending timesync request")
self.master.mav.timesync_send(0, time_ns)
self.last_sent_ts1 = time_ns
|
handle mavlink packets
|
def mavlink_packet(self, m):
'''handle mavlink packets'''
if m.get_type() == 'SYSTEM_TIME':
if self.system_time_settings.verbose:
print("ST: Received from (%u/%u): %s" %
(m.get_srcSystem(), m.get_srcComponent(), m))
if m.get_type() == 'TIMESYNC':
if m.tc1 == 0:
# this is a request for a timesync response
time_ns = time.time() * 1000000000
time_ns += 1234
if True or self.system_time_settings.verbose:
if self.system_time_settings.verbose:
print("ST: received timesync; sending response: %u" %
(time_ns))
self.master.mav.timesync_send(time_ns,
m.ts1)
else:
if m.ts1 == self.last_sent_ts1:
# we sent this one!
now_ns = time.time() * 1000000000
now_ns += 1234
if self.system_time_settings.verbose:
print("ST: timesync response: sysid=%u latency=%fms" %
(m.get_srcSystem(),
(now_ns-self.last_sent_ts1)/1000000.0))
|
set relays
|
def cmd_relay(self, args):
'''set relays'''
if len(args) == 0 or args[0] not in ['set', 'repeat']:
print("Usage: relay <set|repeat>")
return
if args[0] == "set":
if len(args) < 3:
print("Usage: relay set <RELAY_NUM> <0|1>")
return
self.master.mav.command_long_send(self.target_system,
self.target_component,
mavutil.mavlink.MAV_CMD_DO_SET_RELAY, 0,
int(args[1]), int(args[2]),
0, 0, 0, 0, 0)
if args[0] == "repeat":
if len(args) < 4:
print("Usage: relay repeat <RELAY_NUM> <COUNT> <PERIOD>")
return
self.master.mav.command_long_send(self.target_system,
self.target_component,
mavutil.mavlink.MAV_CMD_DO_REPEAT_RELAY, 0,
int(args[1]), int(args[2]), float(args[3]),
0, 0, 0, 0)
|
set servos
|
def cmd_servo(self, args):
'''set servos'''
if len(args) == 0 or args[0] not in ['set', 'repeat']:
print("Usage: servo <set|repeat>")
return
if args[0] == "set":
if len(args) < 3:
print("Usage: servo set <SERVO_NUM> <PWM>")
return
self.master.mav.command_long_send(self.target_system,
self.target_component,
mavutil.mavlink.MAV_CMD_DO_SET_SERVO, 0,
int(args[1]), int(args[2]),
0, 0, 0, 0, 0)
if args[0] == "repeat":
if len(args) < 5:
print("Usage: servo repeat <SERVO_NUM> <PWM> <COUNT> <PERIOD>")
return
self.master.mav.command_long_send(self.target_system,
self.target_component,
mavutil.mavlink.MAV_CMD_DO_REPEAT_SERVO, 0,
int(args[1]), int(args[2]), int(args[3]), float(args[4]),
0, 0, 0)
|
return list of serial ports
|
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 ]
|
return list of links
|
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))
|
show link information
|
def show_link(self):
'''show link information'''
for master in self.mpstate.mav_master:
linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3
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)
except AttributeError as e:
# some mav objects may not have a "signing" attribute
pass
print("link %s %s (%u packets, %.2fs delay, %u lost, %.1f%% loss%s)" % (self.link_label(master),
status,
self.status.counters['MasterIn'][master.linknum],
linkdelay,
master.mav_loss,
master.packet_loss(),
sign_string))
|
return a dict based on some_json (empty if json invalid)
|
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 {}
|
parse e.g. 'udpin:127.0.0.1:9877:{"foo":"bar"}' into
python structure ("udpin:127.0.0.1:9877", {"foo":"bar"})
|
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)
|
add new link
|
def cmd_link_add(self, args):
'''add new link'''
descriptor = args[0]
print("Adding link %s" % descriptor)
self.link_add(descriptor)
|
change optional link attributes
|
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)
|
find a device based on number, name or label
|
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
|
remove an link
|
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)
# renumber the links
for j in range(len(self.mpstate.mav_master)):
conn = self.mpstate.mav_master[j]
conn.linknum = j
|
called on sending a message
|
def master_send_callback(self, m, master):
'''called on sending a message'''
if self.status.watch is not None:
for msg_type in self.status.watch:
if fnmatch.fnmatch(m.get_type().upper(), msg_type.upper()):
self.mpstate.console.writeln('> '+ str(m))
break
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()))
|
special handling for MAVLink packets with a time_boot_ms field
|
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 + 30000 < master.highest_msec:
self.say('Time has wrapped')
print('Time has wrapped', msec, master.highest_msec)
self.status.highest_msec = msec
for mm in self.mpstate.mav_master:
mm.link_delayed = False
mm.highest_msec = msec
return
# we want to detect when a link is delayed
master.highest_msec = msec
if msec > self.status.highest_msec:
self.status.highest_msec = msec
if msec < self.status.highest_msec and len(self.mpstate.mav_master) > 1 and self.mpstate.settings.checkdelay:
master.link_delayed = True
else:
master.link_delayed = False
|
possibly report a new altitude
|
def report_altitude(self, altitude):
'''possibly report a new altitude'''
master = self.master
if getattr(self.console, 'ElevationMap', None) is not None 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.console.ElevationMap.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))
self.say("height %u" % rounded_alt, priority='notification')
|
link message handling for an upstream link
|
def master_msg_handling(self, m, master):
'''link message handling for an upstream link'''
if self.settings.target_system != 0 and m.get_srcSystem() != self.settings.target_system:
# 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):
self.mpstate.console.write(str(m.data), 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 mtype == 'HEARTBEAT' and m.type != mavutil.mavlink.MAV_TYPE_GCS:
if self.settings.target_system == 0 and self.settings.target_system != m.get_srcSystem():
self.settings.target_system = m.get_srcSystem()
self.say("online system %u" % self.settings.target_system,'message')
for mav in self.mpstate.mav_master:
mav.target_system = self.settings.target_system
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 == mavutil.mavlink.MAV_TYPE_FIXED_WING:
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 mtype == 'STATUSTEXT':
if m.text != self.status.last_apm_msg or time.time() > self.status.last_apm_msg_time+2:
(fg, bg) = self.colors_for_severity(m.severity)
self.mpstate.console.writeln("APM: %s" % mp_util.null_term(m.text), bg=bg, fg=fg)
self.status.last_apm_msg = m.text
self.status.last_apm_msg_time = time.time()
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 in [ "COMMAND_ACK", "MISSION_ACK" ]:
self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
if mtype == "COMMAND_ACK" and 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_TEMPORARILY_REJECTED:
self.say("Calibration temporarily rejected")
else:
self.say("Calibration response (%u)" % m.result)
else:
#self.mpstate.console.writeln("Got MAVLink msg: %s" % m)
pass
if self.status.watch is not None:
for msg_type in self.status.watch:
if fnmatch.fnmatch(mtype.upper(), msg_type.upper()):
self.mpstate.console.writeln('< '+ str(m))
break
|
process mavlink message m on master, sending any messages to recipients
|
def master_callback(self, m, master):
'''process mavlink message m on master, sending any messages to recipients'''
# see if it is handled by a specialised sysid connection
sysid = m.get_srcSystem()
mtype = m.get_type()
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
if mtype not in self.status.msg_count:
self.status.msg_count[mtype] = 0
self.status.msg_count[mtype] += 1
if m.get_srcComponent() == mavutil.mavlink.MAV_COMP_ID_GIMBAL and mtype == 'HEARTBEAT':
# silence gimbal heartbeat packets for now
return
if getattr(m, 'time_boot_ms', None) is not None and self.settings.target_system == m.get_srcSystem():
# 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
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:
if self.mpstate.settings.moddebug == 1:
print(msg)
elif self.mpstate.settings.moddebug > 1:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
|
handle vehicle commands
|
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
self.mpstate.settings.link = best_link + 1
print("Set vehicle %s (link %u)" % (args[0], best_link+1))
|
device operations
|
def cmd_devop(self, args):
'''device operations'''
usage = "Usage: devop <read|write> <spi|i2c> name bus address"
if len(args) < 5:
print(usage)
return
if args[1] == 'spi':
bustype = mavutil.mavlink.DEVICE_OP_BUSTYPE_SPI
elif args[1] == 'i2c':
bustype = mavutil.mavlink.DEVICE_OP_BUSTYPE_I2C
else:
print(usage)
if args[0] == 'read':
self.devop_read(args[2:], bustype)
elif args[0] == 'write':
self.devop_write(args[2:], bustype)
else:
print(usage)
|
read from device
|
def devop_read(self, args, bustype):
'''read from device'''
if len(args) < 5:
print("Usage: devop read <spi|i2c> name bus address regstart count")
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0)
reg = int(args[3],base=0)
count = int(args[4],base=0)
self.master.mav.device_op_read_send(self.target_system,
self.target_component,
self.request_id,
bustype,
bus,
address,
name,
reg,
count)
self.request_id += 1
|
write to a device
|
def devop_write(self, args, bustype):
'''write to a device'''
usage = "Usage: devop write <spi|i2c> name bus address regstart count <bytes>"
if len(args) < 5:
print(usage)
return
name = args[0]
bus = int(args[1],base=0)
address = int(args[2],base=0)
reg = int(args[3],base=0)
count = int(args[4],base=0)
args = args[5:]
if len(args) < count:
print(usage)
return
bytes = [0]*128
for i in range(count):
bytes[i] = int(args[i],base=0)
self.master.mav.device_op_write_send(self.target_system,
self.target_component,
self.request_id,
bustype,
bus,
address,
name,
reg,
count,
bytes)
self.request_id += 1
|
Given a set of points geo referenced to this instance,
return the points as absolute values.
|
def get_absolute(self, points):
"""Given a set of points geo referenced to this instance,
return the points as absolute values.
"""
# remember if we got a list
is_list = isinstance(points, list)
points = ensure_numeric(points, num.float)
if len(points.shape) == 1:
# One point has been passed
msg = 'Single point must have two elements'
if not len(points) == 2:
raise ValueError(msg)
msg = 'Input must be an N x 2 array or list of (x,y) values. '
msg += 'I got an %d x %d array' %points.shape
if not points.shape[1] == 2:
raise ValueError(msg)
# Add geo ref to points
if not self.is_absolute():
points = copy.copy(points) # Don't destroy input
points[:,0] += self.xllcorner
points[:,1] += self.yllcorner
if is_list:
points = points.tolist()
return points
|
camera view commands
|
def cmd_cameraview(self, args):
'''camera view commands'''
state = self
if args and args[0] == 'set':
if len(args) < 3:
state.view_settings.show_all()
else:
state.view_settings.set(args[1], args[2])
state.update_col()
else:
print('usage: cameraview set')
|
scale a PWM value
|
def scale_rc(self, servo, min, max, param):
'''scale a PWM value'''
# default to servo range of 1000 to 2000
min_pwm = self.get_mav_param('%s_MIN' % param, 0)
max_pwm = self.get_mav_param('%s_MAX' % param, 0)
if min_pwm == 0 or max_pwm == 0:
return 0
if max_pwm == min_pwm:
p = 0.0
else:
p = (servo-min_pwm) / float(max_pwm-min_pwm)
v = min + p*(max-min)
if v < min:
v = min
if v > max:
v = max
return v
|
handle an incoming mavlink packet
|
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
state = self
mtype = m.get_type()
if mtype == 'GLOBAL_POSITION_INT':
state.lat, state.lon = m.lat*scale_latlon, m.lon*scale_latlon
state.hdg = m.hdg*scale_hdg
agl = state.elevation_model.GetElevation(state.lat, state.lon)
if agl is not None:
state.height = m.relative_alt*scale_relative_alt + state.home_height - agl
elif mtype == 'ATTITUDE':
state.roll, state.pitch, state.yaw = math.degrees(m.roll), math.degrees(m.pitch), math.degrees(m.yaw)
elif mtype in ['GPS_RAW', 'GPS_RAW_INT']:
if self.module('wp').wploader.count() > 0:
home = self.module('wp').wploader.wp(0).x, self.module('wp').wploader.wp(0).y
else:
home = [self.master.field('HOME', c)*scale_latlon for c in ['lat', 'lon']]
old = state.home_height # TODO TMP
agl = state.elevation_model.GetElevation(*home)
if agl is None:
return
state.home_height = agl
# TODO TMP
if state.home_height != old:
# tridge said to get home pos from wploader,
# but this is not the same as from master() below...!!
# using master() gives the right coordinates
# (i.e. matches GLOBAL_POSITION_INT coords, and $IMHOME in sim_arduplane.sh)
# and wploader is a bit off
print('home height changed from',old,'to',state.home_height)
elif mtype == 'SERVO_OUTPUT_RAW':
for (axis, attr) in [('ROLL', 'mount_roll'), ('TILT', 'mount_pitch'), ('PAN', 'mount_yaw')]:
channel = int(self.get_mav_param('MNT_RC_IN_{0}'.format(axis), 0))
if self.get_mav_param('MNT_STAB_{0}'.format(axis), 0) and channel:
# enabled stabilisation on this axis
# TODO just guessing that RC_IN_ROLL gives the servo number, but no idea if this is really the case
servo = 'servo{0}_raw'.format(channel)
centidegrees = self.scale_rc(getattr(m, servo),
self.get_mav_param('MNT_ANGMIN_{0}'.format(axis[:3])),
self.get_mav_param('MNT_ANGMAX_{0}'.format(axis[:3])),
param='RC{0}'.format(channel))
setattr(state, attr, centidegrees*0.01)
#state.mount_roll = min(max(-state.roll,-45),45)#TODO TMP
#state.mount_yaw = min(max(-state.yaw,-45),45)#TODO TMP
#state.mount_pitch = min(max(-state.pitch,-45),45)#TODO TMP
else:
return
if self.mpstate.map: # if the map module is loaded, redraw polygon
# get rid of the old polygon
self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('CameraView'))
# camera view polygon determined by projecting corner pixels of the image onto the ground
pixel_positions = [cuav_util.pixel_position(px[0],px[1], state.height, state.pitch+state.mount_pitch, state.roll+state.mount_roll, state.yaw+state.mount_yaw, state.camera_params) for px in [(0,0), (state.camera_params.xresolution,0), (state.camera_params.xresolution,state.camera_params.yresolution), (0,state.camera_params.yresolution)]]
if any(pixel_position is None for pixel_position in pixel_positions):
# at least one of the pixels is not on the ground
# so it doesn't make sense to try to draw the polygon
return
gps_positions = [mp_util.gps_newpos(state.lat, state.lon, math.degrees(math.atan2(*pixel_position)), math.hypot(*pixel_position)) for pixel_position in pixel_positions]
# draw new polygon
self.mpstate.map.add_object(mp_slipmap.SlipPolygon('cameraview', gps_positions+[gps_positions[0]], # append first element to close polygon
layer='CameraView', linewidth=2, colour=state.col))
|
Code due to Thomas Heller - published in Python Cookbook (O'Reilley)
|
def debug_on_error(type, value, tb):
"""Code due to Thomas Heller - published in Python Cookbook (O'Reilley)"""
traceback.print_exc(type, value, tb)
print()
pdb.pm()
|
Signal an error condition -- in a GUI, popup a error dialog
|
def error_msg_wx(msg, parent=None):
"""
Signal an error condition -- in a GUI, popup a error dialog
"""
dialog =wx.MessageDialog(parent = parent,
message = msg,
caption = 'Matplotlib backend_wx error',
style=wx.OK | wx.CENTRE)
dialog.ShowModal()
dialog.Destroy()
return None
|
msg is a return arg from a raise. Join with new lines
|
def raise_msg_to_str(msg):
"""msg is a return arg from a raise. Join with new lines"""
if not is_string_like(msg):
msg = '\n'.join(map(str, msg))
return msg
|
Creates a wx.App instance if it has not been created sofar.
|
def _create_wx_app():
"""
Creates a wx.App instance if it has not been created sofar.
"""
wxapp = wx.GetApp()
if wxapp is None:
wxapp = wx.App(False)
wxapp.SetExitOnFrameDelete(True)
# retain a reference to the app object so it does not get garbage
# collected and cause segmentation faults
_create_wx_app.theWxApp = wxapp
|
This should be overriden in a windowing environment if drawing
should be done in interactive python mode
|
def draw_if_interactive():
"""
This should be overriden in a windowing environment if drawing
should be done in interactive python mode
"""
DEBUG_MSG("draw_if_interactive()", 1, None)
if matplotlib.is_interactive():
figManager = Gcf.get_active()
if figManager is not None:
figManager.canvas.draw_idle()
|
Create a new figure manager instance
|
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
"""
# in order to expose the Figure constructor to the pylab
# interface we need to create the figure here
DEBUG_MSG("new_figure_manager()", 3, None)
_create_wx_app()
FigureClass = kwargs.pop('FigureClass', Figure)
fig = FigureClass(*args, **kwargs)
return new_figure_manager_given_figure(num, fig)
|
Create a new figure manager instance for the given figure.
|
def new_figure_manager_given_figure(num, figure):
"""
Create a new figure manager instance for the given figure.
"""
fig = figure
frame = FigureFrameWx(num, fig)
figmgr = frame.get_figure_manager()
if matplotlib.is_interactive():
figmgr.frame.Show()
return figmgr
|
Load a bitmap file from the backends/images subdirectory in which the
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.
Returns a wx.Bitmap object
|
def _load_bitmap(filename):
"""
Load a bitmap file from the backends/images subdirectory in which the
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.
Returns a wx.Bitmap object
"""
basedir = os.path.join(rcParams['datapath'],'images')
bmpFilename = os.path.normpath(os.path.join(basedir, filename))
if not os.path.exists(bmpFilename):
raise IOError('Could not find bitmap file "%s"; dying'%bmpFilename)
bmp = wx.Bitmap(bmpFilename)
return bmp
|
get the width and height in display coords of the string s
with FontPropertry prop
|
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
|
Return an instance of a GraphicsContextWx, and sets the current gc copy
|
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
|
Return a wx font. Cache instances in a font dictionary for
efficiency
|
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
|
Select the current bitmap into this wxDC instance
|
def select(self):
"""
Select the current bitmap into this wxDC instance
"""
if sys.platform=='win32':
self.dc.SelectObject(self.bitmap)
self.IsSelected = True
|
Select a Null bitmasp into this wxDC instance
|
def unselect(self):
"""
Select a Null bitmasp into this wxDC instance
"""
if sys.platform=='win32':
self.dc.SelectObject(wx.NullBitmap)
self.IsSelected = False
|
Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
|
def set_foreground(self, fg, isRGBA=None):
"""
Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
"""
# Implementation note: wxPython has a separate concept of pen and
# brush - the brush fills any outline trace left by the pen.
# Here we set both to the same colour - if a figure is not to be
# filled, the renderer will set the brush to be transparent
# Same goes for text foreground...
DEBUG_MSG("set_foreground()", 1, self)
self.select()
GraphicsContextBase.set_foreground(self, fg, isRGBA)
self._pen.SetColour(self.get_wxcolour(self.get_rgb()))
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
|
def set_graylevel(self, frac):
"""
Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
"""
DEBUG_MSG("set_graylevel()", 1, self)
self.select()
GraphicsContextBase.set_graylevel(self, frac)
self._pen.SetColour(self.get_wxcolour(self.get_rgb()))
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
Set the line width.
|
def set_linewidth(self, w):
"""
Set the line width.
"""
DEBUG_MSG("set_linewidth()", 1, self)
self.select()
if w>0 and w<1: w = 1
GraphicsContextBase.set_linewidth(self, w)
lw = int(self.renderer.points_to_pixels(self._linewidth))
if lw==0: lw = 1
self._pen.SetWidth(lw)
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
Set the capstyle as a string in ('butt', 'round', 'projecting')
|
def set_capstyle(self, cs):
"""
Set the capstyle as a string in ('butt', 'round', 'projecting')
"""
DEBUG_MSG("set_capstyle()", 1, self)
self.select()
GraphicsContextBase.set_capstyle(self, cs)
self._pen.SetCap(GraphicsContextWx._capd[self._capstyle])
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
Set the join style to be one of ('miter', 'round', 'bevel')
|
def set_joinstyle(self, js):
"""
Set the join style to be one of ('miter', 'round', 'bevel')
"""
DEBUG_MSG("set_joinstyle()", 1, self)
self.select()
GraphicsContextBase.set_joinstyle(self, js)
self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle])
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
Set the line style to be one of
|
def set_linestyle(self, ls):
"""
Set the line style to be one of
"""
DEBUG_MSG("set_linestyle()", 1, self)
self.select()
GraphicsContextBase.set_linestyle(self, ls)
try:
self._style = GraphicsContextWx._dashd_wx[ls]
except KeyError:
self._style = wx.LONG_DASH# Style not used elsewhere...
# On MS Windows platform, only line width of 1 allowed for dash lines
if wx.Platform == '__WXMSW__':
self.set_linewidth(1)
self._pen.SetStyle(self._style)
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
return a wx.Colour from RGB format
|
def get_wxcolour(self, color):
"""return a wx.Colour from RGB format"""
DEBUG_MSG("get_wx_color()", 1, self)
if len(color) == 3:
r, g, b = color
r *= 255
g *= 255
b *= 255
return wx.Colour(red=int(r), green=int(g), blue=int(b))
else:
r, g, b, a = color
r *= 255
g *= 255
b *= 255
a *= 255
return wx.Colour(red=int(r), green=int(g), blue=int(b), alpha=int(a))
|
copy bitmap of canvas to system clipboard
|
def Copy_to_Clipboard(self, event=None):
"copy bitmap of canvas to system clipboard"
bmp_obj = wx.BitmapDataObject()
bmp_obj.SetBitmap(self.bitmap)
if not wx.TheClipboard.IsOpened():
open_success = wx.TheClipboard.Open()
if open_success:
wx.TheClipboard.SetData(bmp_obj)
wx.TheClipboard.Close()
wx.TheClipboard.Flush()
|
Delay rendering until the GUI is idle.
|
def draw_idle(self):
"""
Delay rendering until the GUI is idle.
"""
DEBUG_MSG("draw_idle()", 1, self)
self._isDrawn = False # Force redraw
# Create a timer for handling draw_idle requests
# If there are events pending when the timer is
# complete, reset the timer and continue. The
# alternative approach, binding to wx.EVT_IDLE,
# doesn't behave as nicely.
if hasattr(self,'_idletimer'):
self._idletimer.Restart(IDLE_DELAY)
else:
self._idletimer = wx.FutureCall(IDLE_DELAY,self._onDrawIdle)
|
Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.
|
def draw(self, drawDC=None):
"""
Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.
"""
DEBUG_MSG("draw()", 1, self)
self.renderer = RendererWx(self.bitmap, self.figure.dpi)
self.figure.draw(self.renderer)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC)
|
Start an event loop. This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events. This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.
Call signature::
start_event_loop(self,timeout=0)
This call blocks until a callback function triggers
stop_event_loop() or *timeout* is reached. If *timeout* is
<=0, never timeout.
Raises RuntimeError if event loop is already running.
|
def start_event_loop(self, timeout=0):
"""
Start an event loop. This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events. This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.
Call signature::
start_event_loop(self,timeout=0)
This call blocks until a callback function triggers
stop_event_loop() or *timeout* is reached. If *timeout* is
<=0, never timeout.
Raises RuntimeError if event loop is already running.
"""
if hasattr(self, '_event_loop'):
raise RuntimeError("Event loop already running")
id = wx.NewId()
timer = wx.Timer(self, id=id)
if timeout > 0:
timer.Start(timeout*1000, oneShot=True)
bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id)
# Event loop handler for start/stop event loop
self._event_loop = wx.EventLoop()
self._event_loop.Run()
timer.Stop()
|
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
Call signature::
stop_event_loop_default(self)
|
def stop_event_loop(self, event=None):
"""
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
Call signature::
stop_event_loop_default(self)
"""
if hasattr(self,'_event_loop'):
if self._event_loop.IsRunning():
self._event_loop.Exit()
del self._event_loop
|
return the wildcard string for the filesave dialog
|
def _get_imagesave_wildcards(self):
'return the wildcard string for the filesave dialog'
default_filetype = self.get_default_filetype()
filetypes = self.get_supported_filetypes_grouped()
sorted_filetypes = filetypes.items()
sorted_filetypes.sort()
wildcards = []
extensions = []
filter_index = 0
for i, (name, exts) in enumerate(sorted_filetypes):
ext_list = ';'.join(['*.%s' % ext for ext in exts])
extensions.append(exts[0])
wildcard = '%s (%s)|%s' % (name, ext_list, ext_list)
if default_filetype in exts:
filter_index = i
wildcards.append(wildcard)
wildcards = '|'.join(wildcards)
return wildcards, extensions, filter_index
|
Performs update of the displayed image on the GUI canvas, using the
supplied device context. If drawDC is None, a ClientDC will be used to
redraw the image.
|
def gui_repaint(self, drawDC=None):
"""
Performs update of the displayed image on the GUI canvas, using the
supplied device context. If drawDC is None, a ClientDC will be used to
redraw the image.
"""
DEBUG_MSG("gui_repaint()", 1, self)
if self.IsShownOnScreen():
if drawDC is None:
drawDC=wx.ClientDC(self)
#drawDC.BeginDrawing()
drawDC.DrawBitmap(self.bitmap, 0, 0)
#drawDC.EndDrawing()
#wx.GetApp().Yield()
else:
pass
|
Called when wxPaintEvt is generated
|
def _onPaint(self, evt):
"""
Called when wxPaintEvt is generated
"""
DEBUG_MSG("_onPaint()", 1, self)
drawDC = wx.PaintDC(self)
if not self._isDrawn:
self.draw(drawDC=drawDC)
else:
self.gui_repaint(drawDC=drawDC)
evt.Skip()
|
Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.
|
def _onSize(self, evt):
"""
Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.
"""
DEBUG_MSG("_onSize()", 2, self)
# Create a new, correctly sized bitmap
self._width, self._height = self.GetClientSize()
self.bitmap =wx.EmptyBitmap(self._width, self._height)
self._isDrawn = False
if self._width <= 1 or self._height <= 1: return # Empty figure
dpival = self.figure.dpi
winch = self._width/dpival
hinch = self._height/dpival
self.figure.set_size_inches(winch, hinch)
# Rendering will happen on the associated paint event
# so no need to do anything here except to make sure
# the whole background is repainted.
self.Refresh(eraseBackground=False)
FigureCanvasBase.resize_event(self)
|
a GUI idle event
|
def _onIdle(self, evt):
'a GUI idle event'
evt.Skip()
FigureCanvasBase.idle_event(self, guiEvent=evt)
|
Capture key press.
|
def _onKeyDown(self, evt):
"""Capture key press."""
key = self._get_key(evt)
evt.Skip()
FigureCanvasBase.key_press_event(self, key, guiEvent=evt)
|
Release key.
|
def _onKeyUp(self, evt):
"""Release key."""
key = self._get_key(evt)
#print 'release key', key
evt.Skip()
FigureCanvasBase.key_release_event(self, key, guiEvent=evt)
|
Start measuring on an axis.
|
def _onLeftButtonDown(self, evt):
"""Start measuring on an axis."""
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
evt.Skip()
self.CaptureMouse()
FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt)
|
Start measuring on an axis.
|
def _onLeftButtonDClick(self, evt):
"""Start measuring on an axis."""
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
evt.Skip()
self.CaptureMouse()
FigureCanvasBase.button_press_event(self, x, y, 1, dblclick=True, guiEvent=evt)
|
End measuring on an axis.
|
def _onLeftButtonUp(self, evt):
"""End measuring on an axis."""
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
#print 'release button', 1
evt.Skip()
if self.HasCapture(): self.ReleaseMouse()
FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt)
|
Translate mouse wheel events into matplotlib events
|
def _onMouseWheel(self, evt):
"""Translate mouse wheel events into matplotlib events"""
# Determine mouse location
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
# Convert delta/rotation/rate into a floating point step size
delta = evt.GetWheelDelta()
rotation = evt.GetWheelRotation()
rate = evt.GetLinesPerAction()
#print "delta,rotation,rate",delta,rotation,rate
step = rate*float(rotation)/delta
# Done handling event
evt.Skip()
# Mac is giving two events for every wheel event
# Need to skip every second one
if wx.Platform == '__WXMAC__':
if not hasattr(self,'_skipwheelevent'):
self._skipwheelevent = True
elif self._skipwheelevent:
self._skipwheelevent = False
return # Return without processing event
else:
self._skipwheelevent = True
# Convert to mpl event
FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt)
|
Start measuring on an axis.
|
def _onMotion(self, evt):
"""Start measuring on an axis."""
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
evt.Skip()
FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt)
|
Mouse has left the window.
|
def _onLeave(self, evt):
"""Mouse has left the window."""
evt.Skip()
FigureCanvasBase.leave_notify_event(self, guiEvent = evt)
|
Set the canvas size in pixels
|
def resize(self, width, height):
'Set the canvas size in pixels'
self.canvas.SetInitialSize(wx.Size(width, height))
self.window.GetSizer().Fit(self.window)
|
Handle menu button pressed.
|
def _onMenuButton(self, evt):
"""Handle menu button pressed."""
x, y = self.GetPositionTuple()
w, h = self.GetSizeTuple()
self.PopupMenuXY(self._menu, x, y+h-4)
# When menu returned, indicate selection in button
evt.Skip()
|
Called when the 'select all axes' menu item is selected.
|
def _handleSelectAllAxes(self, evt):
"""Called when the 'select all axes' menu item is selected."""
if len(self._axisId) == 0:
return
for i in range(len(self._axisId)):
self._menu.Check(self._axisId[i], True)
self._toolbar.set_active(self.getActiveAxes())
evt.Skip()
|
Called when the invert all menu item is selected
|
def _handleInvertAxesSelected(self, evt):
"""Called when the invert all menu item is selected"""
if len(self._axisId) == 0: return
for i in range(len(self._axisId)):
if self._menu.IsChecked(self._axisId[i]):
self._menu.Check(self._axisId[i], False)
else:
self._menu.Check(self._axisId[i], True)
self._toolbar.set_active(self.getActiveAxes())
evt.Skip()
|
Called whenever one of the specific axis menu items is selected
|
def _onMenuItemSelected(self, evt):
"""Called whenever one of the specific axis menu items is selected"""
current = self._menu.IsChecked(evt.GetId())
if current:
new = False
else:
new = True
self._menu.Check(evt.GetId(), new)
# Lines above would be deleted based on svn tracker ID 2841525;
# not clear whether this matters or not.
self._toolbar.set_active(self.getActiveAxes())
evt.Skip()
|
Ensures that there are entries for max_axis axes in the menu
(selected by default).
|
def updateAxes(self, maxAxis):
"""Ensures that there are entries for max_axis axes in the menu
(selected by default)."""
if maxAxis > len(self._axisId):
for i in range(len(self._axisId) + 1, maxAxis + 1, 1):
menuId =wx.NewId()
self._axisId.append(menuId)
self._menu.Append(menuId, "Axis %d" % i, "Select axis %d" % i, True)
self._menu.Check(menuId, True)
bind(self, wx.EVT_MENU, self._onMenuItemSelected, id=menuId)
elif maxAxis < len(self._axisId):
for menuId in self._axisId[maxAxis:]:
self._menu.Delete(menuId)
self._axisId = self._axisId[:maxAxis]
self._toolbar.set_active(range(maxAxis))
|
Return a list of the selected axes.
|
def getActiveAxes(self):
"""Return a list of the selected axes."""
active = []
for i in range(len(self._axisId)):
if self._menu.IsChecked(self._axisId[i]):
active.append(i)
return active
|
Update the list of selected axes in the menu button
|
def updateButtonText(self, lst):
"""Update the list of selected axes in the menu button"""
axis_txt = ''
for e in lst:
axis_txt += '%d,' % (e+1)
# remove trailing ',' and add to button string
self.SetLabel("Axes: %s" % axis_txt[:-1])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.