INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
called on idle
|
def idle_task(self):
'''called on idle'''
if self.module('console') is not None and not self.menu_added_console:
self.menu_added_console = True
self.module('console').add_menu(self.menu)
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)
|
Enable or disable fence
|
def set_fence_enabled(self, do_enable):
'''Enable or disable fence'''
self.master.mav.command_long_send(
self.target_system,
self.target_component,
mavutil.mavlink.MAV_CMD_DO_FENCE_ENABLE, 0,
do_enable, 0, 0, 0, 0, 0, 0)
|
handle fencepoint move
|
def cmd_fence_move(self, args):
'''handle fencepoint move'''
if len(args) < 1:
print("Usage: fence move FENCEPOINTNUM")
return
if not self.have_list:
print("Please list fence points first")
return
idx = int(args[0])
if idx <= 0 or idx > self.fenceloader.count():
print("Invalid fence point number %u" % idx)
return
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
return
# note we don't subtract 1, as first fence point is the return point
self.fenceloader.move(idx, latlon[0], latlon[1])
if self.send_fence():
print("Moved fence point %u" % idx)
|
handle fencepoint remove
|
def cmd_fence_remove(self, args):
'''handle fencepoint remove'''
if len(args) < 1:
print("Usage: fence remove FENCEPOINTNUM")
return
if not self.have_list:
print("Please list fence points first")
return
idx = int(args[0])
if idx <= 0 or idx > self.fenceloader.count():
print("Invalid fence point number %u" % idx)
return
# note we don't subtract 1, as first fence point is the return point
self.fenceloader.remove(idx)
if self.send_fence():
print("Removed fence point %u" % idx)
else:
print("Failed to remove fence point %u" % idx)
|
fence commands
|
def cmd_fence(self, args):
'''fence commands'''
if len(args) < 1:
self.print_usage()
return
if args[0] == "enable":
self.set_fence_enabled(1)
elif args[0] == "disable":
self.set_fence_enabled(0)
elif args[0] == "load":
if len(args) != 2:
print("usage: fence load <filename>")
return
self.load_fence(args[1])
elif args[0] == "list":
self.list_fence(None)
elif args[0] == "move":
self.cmd_fence_move(args[1:])
elif args[0] == "remove":
self.cmd_fence_remove(args[1:])
elif args[0] == "save":
if len(args) != 2:
print("usage: fence save <filename>")
return
self.list_fence(args[1])
elif args[0] == "show":
if len(args) != 2:
print("usage: fence show <filename>")
return
self.fenceloader.load(args[1])
self.have_list = True
elif args[0] == "draw":
if not 'draw_lines' in self.mpstate.map_functions:
print("No map drawing available")
return
self.mpstate.map_functions['draw_lines'](self.fence_draw_callback)
print("Drawing fence on map")
elif args[0] == "clear":
self.param_set('FENCE_TOTAL', 0, 3)
else:
self.print_usage()
|
send fence points from fenceloader
|
def send_fence(self):
'''send fence points from fenceloader'''
# must disable geo-fencing when loading
self.fenceloader.target_system = self.target_system
self.fenceloader.target_component = self.target_component
self.fenceloader.reindex()
action = self.get_mav_param('FENCE_ACTION', mavutil.mavlink.FENCE_ACTION_NONE)
self.param_set('FENCE_ACTION', mavutil.mavlink.FENCE_ACTION_NONE, 3)
self.param_set('FENCE_TOTAL', self.fenceloader.count(), 3)
for i in range(self.fenceloader.count()):
p = self.fenceloader.point(i)
self.master.mav.send(p)
p2 = self.fetch_fence_point(i)
if p2 is None:
self.param_set('FENCE_ACTION', action, 3)
return False
if (p.idx != p2.idx or
abs(p.lat - p2.lat) >= 0.00003 or
abs(p.lng - p2.lng) >= 0.00003):
print("Failed to send fence point %u" % i)
self.param_set('FENCE_ACTION', action, 3)
return False
self.param_set('FENCE_ACTION', action, 3)
return True
|
fetch one fence point
|
def fetch_fence_point(self ,i):
'''fetch one fence point'''
self.master.mav.fence_fetch_point_send(self.target_system,
self.target_component, i)
tstart = time.time()
p = None
while time.time() - tstart < 3:
p = self.master.recv_match(type='FENCE_POINT', blocking=False)
if p is not None:
break
time.sleep(0.1)
continue
if p is None:
self.console.error("Failed to fetch point %u" % i)
return None
return p
|
callback from drawing a fence
|
def fence_draw_callback(self, points):
'''callback from drawing a fence'''
self.fenceloader.clear()
if len(points) < 3:
return
self.fenceloader.target_system = self.target_system
self.fenceloader.target_component = self.target_component
bounds = mp_util.polygon_bounds(points)
(lat, lon, width, height) = bounds
center = (lat+width/2, lon+height/2)
self.fenceloader.add_latlon(center[0], center[1])
for p in points:
self.fenceloader.add_latlon(p[0], p[1])
# close it
self.fenceloader.add_latlon(points[0][0], points[0][1])
self.send_fence()
self.have_list = True
|
add a new menu
|
def add_menu(self, menu):
'''add a new menu'''
self.menu.add(menu)
self.mpstate.console.set_menu(self.menu, self.menu_callback)
|
unload module
|
def unload(self):
'''unload module'''
self.mpstate.console.close()
self.mpstate.console = textconsole.SimpleConsole()
|
called on menu selection
|
def menu_callback(self, m):
'''called on menu selection'''
if m.returnkey.startswith('# '):
cmd = m.returnkey[2:]
if m.handler is not None:
if m.handler_result is None:
return
cmd += m.handler_result
self.mpstate.functions.process_stdin(cmd)
if m.returnkey == 'menuSettings':
wxsettings.WXSettings(self.settings)
|
estimate time remaining in mission in seconds
|
def estimated_time_remaining(self, lat, lon, wpnum, speed):
'''estimate time remaining in mission in seconds'''
idx = wpnum
if wpnum >= self.module('wp').wploader.count():
return 0
distance = 0
done = set()
while idx < self.module('wp').wploader.count():
if idx in done:
break
done.add(idx)
w = self.module('wp').wploader.wp(idx)
if w.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
idx = int(w.param1)
continue
idx += 1
if (w.x != 0 or w.y != 0) and w.command in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT,
mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM,
mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS,
mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME,
mavutil.mavlink.MAV_CMD_NAV_LAND,
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF]:
distance += mp_util.gps_distance(lat, lon, w.x, w.y)
lat = w.x
lon = w.y
if w.command == mavutil.mavlink.MAV_CMD_NAV_LAND:
break
return distance / speed
|
handle an incoming mavlink packet
|
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if not isinstance(self.console, wxconsole.MessageConsole):
return
if not self.console.is_alive():
self.mpstate.console = textconsole.SimpleConsole()
return
type = msg.get_type()
master = self.master
# add some status fields
if type in [ 'GPS_RAW', 'GPS_RAW_INT' ]:
if type == "GPS_RAW":
num_sats1 = master.field('GPS_STATUS', 'satellites_visible', 0)
else:
num_sats1 = msg.satellites_visible
num_sats2 = master.field('GPS2_RAW', 'satellites_visible', -1)
if num_sats2 == -1:
sats_string = "%u" % num_sats1
else:
sats_string = "%u/%u" % (num_sats1, num_sats2)
if ((msg.fix_type == 3 and master.mavlink10()) or
(msg.fix_type == 2 and not master.mavlink10())):
self.console.set_status('GPS', 'GPS: OK (%s)' % sats_string, fg='green')
else:
self.console.set_status('GPS', 'GPS: %u (%s)' % (msg.fix_type, sats_string), fg='red')
if master.mavlink10():
gps_heading = int(self.mpstate.status.msgs['GPS_RAW_INT'].cog * 0.01)
else:
gps_heading = self.mpstate.status.msgs['GPS_RAW'].hdg
self.console.set_status('Heading', 'Hdg %s/%u' % (master.field('VFR_HUD', 'heading', '-'), gps_heading))
elif type == 'VFR_HUD':
if master.mavlink10():
alt = master.field('GPS_RAW_INT', 'alt', 0) / 1.0e3
else:
alt = master.field('GPS_RAW', 'alt', 0)
if self.module('wp').wploader.count() > 0:
wp = self.module('wp').wploader.wp(0)
home_lat = wp.x
home_lng = wp.y
else:
home_lat = master.field('HOME', 'lat') * 1.0e-7
home_lng = master.field('HOME', 'lon') * 1.0e-7
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1.0e-7
lng = master.field('GLOBAL_POSITION_INT', 'lon', 0) * 1.0e-7
rel_alt = master.field('GLOBAL_POSITION_INT', 'relative_alt', 0) * 1.0e-3
agl_alt = None
if self.settings.basealt != 0:
agl_alt = self.console.ElevationMap.GetElevation(lat, lng)
if agl_alt is not None:
agl_alt = self.settings.basealt - agl_alt
else:
try:
agl_alt_home = self.console.ElevationMap.GetElevation(home_lat, home_lng)
except Exception as ex:
print(ex)
agl_alt_home = None
if agl_alt_home is not None:
agl_alt = self.console.ElevationMap.GetElevation(lat, lng)
if agl_alt is not None:
agl_alt = agl_alt_home - agl_alt
if agl_alt is not None:
agl_alt += rel_alt
vehicle_agl = master.field('TERRAIN_REPORT', 'current_height', None)
if vehicle_agl is None:
vehicle_agl = '---'
else:
vehicle_agl = int(vehicle_agl)
self.console.set_status('AGL', 'AGL %u/%s' % (agl_alt, vehicle_agl))
self.console.set_status('Alt', 'Alt %u' % rel_alt)
self.console.set_status('AirSpeed', 'AirSpeed %u' % msg.airspeed)
self.console.set_status('GPSSpeed', 'GPSSpeed %u' % msg.groundspeed)
self.console.set_status('Thr', 'Thr %u' % msg.throttle)
t = time.localtime(msg._timestamp)
flying = False
if self.mpstate.vehicle_type == 'copter':
flying = self.master.motors_armed()
else:
flying = msg.groundspeed > 3
if flying and not self.in_air:
self.in_air = True
self.start_time = time.mktime(t)
elif flying and self.in_air:
self.total_time = time.mktime(t) - self.start_time
self.console.set_status('FlightTime', 'FlightTime %u:%02u' % (int(self.total_time)/60, int(self.total_time)%60))
elif not flying and self.in_air:
self.in_air = False
self.total_time = time.mktime(t) - self.start_time
self.console.set_status('FlightTime', 'FlightTime %u:%02u' % (int(self.total_time)/60, int(self.total_time)%60))
elif type == 'ATTITUDE':
self.console.set_status('Roll', 'Roll %u' % math.degrees(msg.roll))
self.console.set_status('Pitch', 'Pitch %u' % math.degrees(msg.pitch))
elif 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,
'RC' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_RC_RECEIVER,
'TERR' : mavutil.mavlink.MAV_SYS_STATUS_TERRAIN,
'RNG' : mavutil.mavlink.MAV_SYS_STATUS_SENSOR_LASER_POSITION}
announce = [ 'RC' ]
for s in sensors.keys():
bits = sensors[s]
present = ((msg.onboard_control_sensors_enabled & bits) == bits)
healthy = ((msg.onboard_control_sensors_health & bits) == bits)
if not present:
fg = 'grey'
elif not healthy:
fg = 'red'
else:
fg = 'green'
# for terrain show yellow if still loading
if s == 'TERR' and fg == 'green' and master.field('TERRAIN_REPORT', 'pending', 0) != 0:
fg = 'yellow'
self.console.set_status(s, s, fg=fg)
for s in announce:
bits = sensors[s]
present = ((msg.onboard_control_sensors_enabled & bits) == bits)
healthy = ((msg.onboard_control_sensors_health & bits) == bits)
was_healthy = ((self.last_sys_status_health & bits) == bits)
if present and not healthy and was_healthy:
self.say("%s fail" % s)
self.last_sys_status_health = msg.onboard_control_sensors_health
elif type == 'WIND':
self.console.set_status('Wind', 'Wind %u/%.2f' % (msg.direction, msg.speed))
elif type == 'EKF_STATUS_REPORT':
highest = 0.0
vars = ['velocity_variance',
'pos_horiz_variance',
'pos_vert_variance',
'compass_variance',
'terrain_alt_variance']
for var in vars:
v = getattr(msg, var, 0)
highest = max(v, highest)
if highest >= 1.0:
fg = 'red'
elif highest >= 0.5:
fg = 'orange'
else:
fg = 'green'
self.console.set_status('EKF', 'EKF', fg=fg)
elif type == 'HWSTATUS':
if msg.Vcc >= 4600 and msg.Vcc <= 5300:
fg = 'green'
else:
fg = 'red'
self.console.set_status('Vcc', 'Vcc %.2f' % (msg.Vcc * 0.001), fg=fg)
elif type == 'POWER_STATUS':
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_CHANGED:
fg = 'red'
else:
fg = 'green'
status = 'PWR:'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_USB_CONNECTED:
status += 'U'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_BRICK_VALID:
status += 'B'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_SERVO_VALID:
status += 'S'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_PERIPH_OVERCURRENT:
status += 'O1'
if msg.flags & mavutil.mavlink.MAV_POWER_STATUS_PERIPH_HIPOWER_OVERCURRENT:
status += 'O2'
self.console.set_status('PWR', status, fg=fg)
self.console.set_status('Srv', 'Srv %.2f' % (msg.Vservo*0.001), fg='green')
elif type in ['RADIO', 'RADIO_STATUS']:
if msg.rssi < msg.noise+10 or msg.remrssi < msg.remnoise+10:
fg = 'red'
else:
fg = 'black'
self.console.set_status('Radio', 'Radio %u/%u %u/%u' % (msg.rssi, msg.noise, msg.remrssi, msg.remnoise), fg=fg)
elif type == 'HEARTBEAT':
self.console.set_status('Mode', '%s' % master.flightmode, fg='blue')
if self.master.motors_armed():
arm_colour = 'green'
else:
arm_colour = 'red'
self.console.set_status('ARM', 'ARM', fg=arm_colour)
if self.max_link_num != len(self.mpstate.mav_master):
for i in range(self.max_link_num):
self.console.set_status('Link%u'%(i+1), '', row=1)
self.max_link_num = len(self.mpstate.mav_master)
for m in self.mpstate.mav_master:
linkdelay = (self.mpstate.status.highest_msec - m.highest_msec)*1.0e-3
linkline = "Link %u " % (m.linknum+1)
if m.linkerror:
linkline += "down"
fg = 'red'
else:
packets_rcvd_percentage = 100
if (m.mav_loss != 0): #avoid divide-by-zero
packets_rcvd_percentage = (1.0 - (float(m.mav_loss) / float(m.mav_count))) * 100.0
linkline += "OK (%u pkts, %.2fs delay, %u lost) %u%%" % (m.mav_count, linkdelay, m.mav_loss, packets_rcvd_percentage)
if linkdelay > 1:
fg = 'orange'
else:
fg = 'dark green'
self.console.set_status('Link%u'%m.linknum, linkline, row=1, fg=fg)
elif type in ['WAYPOINT_CURRENT', 'MISSION_CURRENT']:
self.console.set_status('WP', 'WP %u' % msg.seq)
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0) * 1.0e-7
lng = master.field('GLOBAL_POSITION_INT', 'lon', 0) * 1.0e-7
if lat != 0 and lng != 0:
airspeed = master.field('VFR_HUD', 'airspeed', 30)
if abs(airspeed - self.speed) > 5:
self.speed = airspeed
else:
self.speed = 0.98*self.speed + 0.02*airspeed
self.speed = max(1, self.speed)
time_remaining = int(self.estimated_time_remaining(lat, lng, msg.seq, self.speed))
self.console.set_status('ETR', 'ETR %u:%02u' % (time_remaining/60, time_remaining%60))
elif type == 'NAV_CONTROLLER_OUTPUT':
self.console.set_status('WPDist', 'Distance %u' % msg.wp_dist)
self.console.set_status('WPBearing', 'Bearing %u' % msg.target_bearing)
if msg.alt_error > 0:
alt_error_sign = "L"
else:
alt_error_sign = "H"
if msg.aspd_error > 0:
aspd_error_sign = "L"
else:
aspd_error_sign = "H"
self.console.set_status('AltError', 'AltError %d%s' % (msg.alt_error, alt_error_sign))
self.console.set_status('AspdError', 'AspdError %.1f%s' % (msg.aspd_error*0.01, aspd_error_sign))
|
return the angle between this vector and another vector
|
def angle(self, v):
'''return the angle between this vector and another vector'''
return acos((self * v) / (self.length() * v.length()))
|
fill the matrix from Euler angles in radians
|
def from_euler(self, roll, pitch, yaw):
'''fill the matrix from Euler angles in radians'''
cp = cos(pitch)
sp = sin(pitch)
sr = sin(roll)
cr = cos(roll)
sy = sin(yaw)
cy = cos(yaw)
self.a.x = cp * cy
self.a.y = (sr * sp * cy) - (cr * sy)
self.a.z = (cr * sp * cy) + (sr * sy)
self.b.x = cp * sy
self.b.y = (sr * sp * sy) + (cr * cy)
self.b.z = (cr * sp * sy) - (sr * cy)
self.c.x = -sp
self.c.y = sr * cp
self.c.z = cr * cp
|
find Euler angles (321 convention) for the matrix
|
def to_euler(self):
'''find Euler angles (321 convention) for the matrix'''
if self.c.x >= 1.0:
pitch = pi
elif self.c.x <= -1.0:
pitch = -pi
else:
pitch = -asin(self.c.x)
roll = atan2(self.c.y, self.c.z)
yaw = atan2(self.b.x, self.a.x)
return (roll, pitch, yaw)
|
find Euler angles (312 convention) for the matrix.
See http://www.atacolorado.com/eulersequences.doc
|
def to_euler312(self):
'''find Euler angles (312 convention) for the matrix.
See http://www.atacolorado.com/eulersequences.doc
'''
T21 = self.a.y
T22 = self.b.y
T23 = self.c.y
T13 = self.c.x
T33 = self.c.z
yaw = atan2(-T21, T22)
roll = asin(T23)
pitch = atan2(-T13, T33)
return (roll, pitch, yaw)
|
fill the matrix from Euler angles in radians in 312 convention
|
def from_euler312(self, roll, pitch, yaw):
'''fill the matrix from Euler angles in radians in 312 convention'''
c3 = cos(pitch)
s3 = sin(pitch)
s2 = sin(roll)
c2 = cos(roll)
s1 = sin(yaw)
c1 = cos(yaw)
self.a.x = c1 * c3 - s1 * s2 * s3
self.b.y = c1 * c2
self.c.z = c3 * c2
self.a.y = -c2*s1
self.a.z = s3*c1 + c3*s2*s1
self.b.x = c3*s1 + s3*s2*c1
self.b.z = s1*s3 - s2*c1*c3
self.c.x = -s3*c2
self.c.y = s2
|
rotate the matrix by a given amount on 3 axes
|
def rotate(self, g):
'''rotate the matrix by a given amount on 3 axes'''
temp_matrix = Matrix3()
a = self.a
b = self.b
c = self.c
temp_matrix.a.x = a.y * g.z - a.z * g.y
temp_matrix.a.y = a.z * g.x - a.x * g.z
temp_matrix.a.z = a.x * g.y - a.y * g.x
temp_matrix.b.x = b.y * g.z - b.z * g.y
temp_matrix.b.y = b.z * g.x - b.x * g.z
temp_matrix.b.z = b.x * g.y - b.y * g.x
temp_matrix.c.x = c.y * g.z - c.z * g.y
temp_matrix.c.y = c.z * g.x - c.x * g.z
temp_matrix.c.z = c.x * g.y - c.y * g.x
self.a += temp_matrix.a
self.b += temp_matrix.b
self.c += temp_matrix.c
|
re-normalise a rotation matrix
|
def normalize(self):
'''re-normalise a rotation matrix'''
error = self.a * self.b
t0 = self.a - (self.b * (0.5 * error))
t1 = self.b - (self.a * (0.5 * error))
t2 = t0 % t1
self.a = t0 * (1.0 / t0.length())
self.b = t1 * (1.0 / t1.length())
self.c = t2 * (1.0 / t2.length())
|
the trace of the matrix
|
def trace(self):
'''the trace of the matrix'''
return self.a.x + self.b.y + self.c.z
|
create a rotation matrix from axis and angle
|
def from_axis_angle(self, axis, angle):
'''create a rotation matrix from axis and angle'''
ux = axis.x
uy = axis.y
uz = axis.z
ct = cos(angle)
st = sin(angle)
self.a.x = ct + (1-ct) * ux**2
self.a.y = ux*uy*(1-ct) - uz*st
self.a.z = ux*uz*(1-ct) + uy*st
self.b.x = uy*ux*(1-ct) + uz*st
self.b.y = ct + (1-ct) * uy**2
self.b.z = uy*uz*(1-ct) - ux*st
self.c.x = uz*ux*(1-ct) - uy*st
self.c.y = uz*uy*(1-ct) + ux*st
self.c.z = ct + (1-ct) * uz**2
|
get a rotation matrix from two vectors.
This returns a rotation matrix which when applied to vec1
will produce a vector pointing in the same direction as vec2
|
def from_two_vectors(self, vec1, vec2):
'''get a rotation matrix from two vectors.
This returns a rotation matrix which when applied to vec1
will produce a vector pointing in the same direction as vec2'''
angle = vec1.angle(vec2)
cross = vec1 % vec2
if cross.length() == 0:
# the two vectors are colinear
return self.from_euler(0,0,angle)
cross.normalize()
return self.from_axis_angle(cross, angle)
|
return point where line intersects with a plane
|
def plane_intersection(self, plane, forward_only=False):
'''return point where line intersects with a plane'''
l_dot_n = self.vector * plane.normal
if l_dot_n == 0.0:
# line is parallel to the plane
return None
d = ((plane.point - self.point) * plane.normal) / l_dot_n
if forward_only and d < 0:
return None
return (self.vector * d) + self.point
|
Updates Image.
|
def update(self):
'''
Updates Image.
'''
if self.hasproxy():
img = Rgbd()
data = self.proxy.getData()
img.color.data = np.frombuffer(data.color.pixelData, dtype=np.uint8)
img.color.data.shape = data.color.description.height, data.color.description.width, 3
img.color.height = data.color.description.height
img.color.width = data.color.description.width
img.color.format = data.color.description.format
img.depth.data = np.frombuffer(data.depth.pixelData, dtype=np.uint8)
img.depth.data.shape = data.depth.description.height, data.depth.description.width, 3
img.depth.height = data.depth.description.height
img.depth.width = data.depth.description.width
img.depth.format = data.depth.description.format
img.timeStamp = data.timeStamp.seconds + data.timeStamp.useconds * 1e-9
self.lock.acquire()
self.image = img
self.lock.release()
|
Returns last Rgbd.
@return last JdeRobotTypes Rgbd saved
|
def getRgbd(self):
'''
Returns last Rgbd.
@return last JdeRobotTypes Rgbd saved
'''
img = Rgb()
if self.hasproxy():
self.lock.acquire()
img = self.image
self.lock.release()
return img
|
called in idle time
|
def idle_task(self):
'''called in idle time'''
try:
data = self.port.recv(200)
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return
raise
if len(data) > 110:
print("DGPS data too large: %u bytes" % len(data))
return
try:
self.master.mav.gps_inject_data_send(
self.target_system,
self.target_component,
len(data),
bytearray(data.ljust(110, '\0')))
except Exception(e):
print ("DGPS Failed:", e)
|
graph command
|
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])
else:
# start a new graph
self.graphs.append(Graph(self, args[:]))
|
handle an incoming mavlink packet
|
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)
|
add data to the graph
|
def add_mavlink_packet(self, msg):
'''add data to the graph'''
mtype = msg.get_type()
if mtype not in self.msg_types:
return
for i in range(len(self.fields)):
if mtype not in self.field_types[i]:
continue
f = self.fields[i]
self.values[i] = mavutil.evaluate_expression(f, self.state.master.messages)
if self.livegraph is not None:
self.livegraph.add_values(self.values)
|
Generate the implementations of the classes representing MAVLink messages.
|
def generate_classes(outf, msgs):
"""
Generate the implementations of the classes representing MAVLink messages.
"""
print("Generating class definitions")
wrapper = textwrap.TextWrapper(initial_indent="", subsequent_indent="")
outf.write("\nmavlink.messages = {};\n\n");
def field_descriptions(fields):
ret = ""
for f in fields:
ret += " %-18s : %s (%s)\n" % (f.name, f.description.strip(), f.type)
return ret
for m in msgs:
comment = "%s\n\n%s" % (wrapper.fill(m.description.strip()), field_descriptions(m.fields))
selffieldnames = 'self, '
for f in m.fields:
# if f.omit_arg:
# selffieldnames += '%s=%s, ' % (f.name, f.const_value)
#else:
# -- Omitting the code above because it is rarely used (only once?) and would need some special handling
# in javascript. Specifically, inside the method definition, it needs to check for a value then assign
# a default.
selffieldnames += '%s, ' % f.name
selffieldnames = selffieldnames[:-2]
sub = {'NAMELOWER' : m.name.lower(),
'SELFFIELDNAMES' : selffieldnames,
'COMMENT' : comment,
'FIELDNAMES' : ", ".join(m.fieldnames)}
t.write(outf, """
/*
${COMMENT}
*/
""", sub)
# function signature + declaration
outf.write("mavlink.messages.%s = function(" % (m.name.lower()))
if len(m.fields) != 0:
outf.write(", ".join(m.fieldnames))
outf.write(") {")
# body: set message type properties
outf.write("""
this.format = '%s';
this.id = mavlink.MAVLINK_MSG_ID_%s;
this.order_map = %s;
this.crc_extra = %u;
this.name = '%s';
""" % (m.fmtstr, m.name.upper(), m.order_map, m.crc_extra, m.name.upper()))
# body: set own properties
if len(m.fieldnames) != 0:
outf.write(" this.fieldnames = ['%s'];\n" % "', '".join(m.fieldnames))
outf.write("""
this.set(arguments);
}
""")
# inherit methods from the base message class
outf.write("""
mavlink.messages.%s.prototype = new mavlink.message;
""" % m.name.lower())
# Implement the pack() function for this message
outf.write("""
mavlink.messages.%s.prototype.pack = function(mav) {
return mavlink.message.prototype.pack.call(this, mav, this.crc_extra, jspack.Pack(this.format""" % m.name.lower())
if len(m.fields) != 0:
outf.write(", [ this." + ", this.".join(m.ordered_fieldnames) + ']')
outf.write("));\n}\n\n")
|
work out the struct format for a type
|
def mavfmt(field):
'''work out the struct format for a type'''
map = {
'float' : 'f',
'double' : 'd',
'char' : 'c',
'int8_t' : 'b',
'uint8_t' : 'B',
'uint8_t_mavlink_version' : 'B',
'int16_t' : 'h',
'uint16_t' : 'H',
'int32_t' : 'i',
'uint32_t' : 'I',
'int64_t' : 'q',
'uint64_t' : 'Q',
}
if field.array_length:
if field.type in ['char', 'int8_t', 'uint8_t']:
return str(field.array_length)+'s'
return str(field.array_length)+map[field.type]
return map[field.type]
|
generate complete javascript implementation
|
def generate(basename, xml):
'''generate complete javascript implementation'''
if basename.endswith('.js'):
filename = basename
else:
filename = basename + '.js'
msgs = []
enums = []
filelist = []
for x in xml:
msgs.extend(x.message)
enums.extend(x.enum)
filelist.append(os.path.basename(x.filename))
for m in msgs:
if xml[0].little_endian:
m.fmtstr = '<'
else:
m.fmtstr = '>'
for f in m.ordered_fields:
m.fmtstr += mavfmt(f)
m.order_map = [ 0 ] * len(m.fieldnames)
for i in range(0, len(m.fieldnames)):
m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i])
print("Generating %s" % filename)
outf = open(filename, "w")
generate_preamble(outf, msgs, filelist, xml[0])
generate_enums(outf, enums)
generate_message_ids(outf, msgs)
generate_classes(outf, msgs)
generate_mavlink_class(outf, msgs, xml[0])
generate_footer(outf)
outf.close()
print("Generated %s OK" % filename)
|
child process - this holds GUI elements
|
def child_task(self, q, l, gq, gl):
'''child process - this holds GUI elements'''
mp_util.child_close_fds()
from ..lib import wx_processguard
from ..lib.wx_loader import wx
from MAVProxy.modules.mavproxy_misseditor import missionEditorFrame
self.app = wx.App(False)
self.app.frame = missionEditorFrame.MissionEditorFrame(parent=None,id=wx.ID_ANY)
self.app.frame.set_event_queue(q)
self.app.frame.set_event_queue_lock(l)
self.app.frame.set_gui_event_queue(gq)
self.app.frame.set_gui_event_queue_lock(gl)
self.app.frame.Show()
self.app.MainLoop()
|
close the Mission Editor window
|
def close(self):
'''close the Mission Editor window'''
self.close_window.set()
if self.child.is_alive():
self.child.join(1)
self.child.terminate()
self.event_queue_lock.acquire()
self.event_queue.put(MissionEditorEvent(me_event.MEE_TIME_TO_QUIT));
self.event_queue_lock.release()
|
Trigger Camera
|
def __vCmdCamTrigger(self, args):
'''Trigger Camera'''
#print(self.camera_list)
for cam in self.camera_list:
cam.take_picture()
print("Trigger Cam %s" % cam)
|
ToDo: Validate the argument as a valid port
|
def __vCmdConnectCameras(self, args):
'''ToDo: Validate the argument as a valid port'''
if len(args) >= 1:
self.WirelessPort = args[0]
print ("Connecting to Cameras on %s" % self.WirelessPort)
self.__vRegisterCameras()
|
ToDo: Validate CAM number and Valid Mode Values
|
def __vCmdSetCamExposureMode(self, args):
'''ToDo: Validate CAM number and Valid Mode Values'''
if len(args) == 1:
for cam in self.camera_list:
cam.boSetExposureMode(args[0])
elif len(args) == 2:
cam = self.camera_list[int(args[1])]
cam.boSetExposureMode(args[0])
else:
print ("Usage: setCamExposureMode MODE [CAMNUMBER], Valid values for MODE: Program Auto, Aperture, Shutter, Manual, Intelligent Auto, Superior Auto")
|
ToDo: Validate CAM number and Valid Aperture Value
|
def __vCmdSetCamAperture(self, args):
'''ToDo: Validate CAM number and Valid Aperture Value'''
if len(args) == 1:
for cam in self.camera_list:
cam.boSetAperture(int(args[0]))
elif len(args) == 2:
cam = self.camera_list[int(args[1])]
cam.boSetAperture(int(args[0]))
else:
print ("Usage: setCamAperture APERTURE [CAMNUMBER], APERTURE is value x10")
|
ToDo: Validate CAM number and Valid Shutter Speed
|
def __vCmdSetCamShutterSpeed(self, args):
'''ToDo: Validate CAM number and Valid Shutter Speed'''
if len(args) == 1:
for cam in self.camera_list:
cam.boSetShutterSpeed(int(args[0]))
elif len(args) == 2:
cam = self.camera_list[int(args[1])]
cam.boSetShutterSpeed(int(args[0]))
else:
print ("Usage: setCamShutterSpeed SHUTTERVALUE [CAMNUMBER], Shutter value is the devisor in 1/x (only works for values smaller than 1)")
|
ToDo: Validate CAM number and Valid ISO Value
|
def __vCmdSetCamISO(self, args):
'''ToDo: Validate CAM number and Valid ISO Value'''
if len(args) == 1:
for cam in self.camera_list:
cam.boSetISO(int(args[0]))
elif len(args) == 2:
cam = self.camera_list[int(args[1])]
cam.boSetISO(int(args[0]))
else:
print ("Usage: setCamISO ISOVALUE [CAMNUMBER]")
|
Shutter Speed
|
def __vDecodeDIGICAMConfigure(self, mCommand_Long):
if mCommand_Long.param1 != 0:
print ("Exposure Mode = %d" % mCommand_Long.param1)
if mCommand_Long.param1 == self.ProgramAuto:
self.__vCmdSetCamExposureMode(["Program Auto"])
elif mCommand_Long.param1 == self.Aperture:
self.__vCmdSetCamExposureMode(["Aperture"])
elif mCommand_Long.param1 == self.Shutter:
self.__vCmdSetCamExposureMode(["Shutter"])
'''Shutter Speed'''
if mCommand_Long.param2 != 0:
print ("Shutter Speed= %d" % mCommand_Long.param2)
self.__vCmdSetCamShutterSpeed([mCommand_Long.param2])
'''Aperture'''
if mCommand_Long.param3 != 0:
print ("Aperture = %d" % mCommand_Long.param3)
self.__vCmdSetCamAperture([mCommand_Long.param3])
'''ISO'''
if mCommand_Long.param4 != 0:
print ("ISO = %d" % mCommand_Long.param4)
self.__vCmdSetCamISO([mCommand_Long.param4])
'''Exposure Type'''
if mCommand_Long.param5 != 0:
print ("Exposure type= %d" % mCommand_Long.param5)
|
Session
|
def __vDecodeDIGICAMControl(self, mCommand_Long):
'''Session'''
if mCommand_Long.param1 != 0:
print ("Session = %d" % mCommand_Long.param1)
'''Zooming Step Value'''
if mCommand_Long.param2 != 0:
print ("Zooming Step = %d" % mCommand_Long.param2)
'''Zooming Step Value'''
if mCommand_Long.param3 != 0:
print ("Zooming Value = %d" % mCommand_Long.param3)
if (mCommand_Long.param3 == 1):
self.__vCmdCamZoomIn()
elif (mCommand_Long.param3 == -1):
self.__vCmdCamZoomOut()
else:
print ("Invalid Zoom Value")
'''Focus 0=Unlock/1=Lock/2=relock'''
if mCommand_Long.param4 != 0:
print ("Focus = %d" % mCommand_Long.param4)
'''Trigger'''
if mCommand_Long.param5 != 0:
print ("Trigger = %d" % mCommand_Long.param5)
self.__vCmdCamTrigger(mCommand_Long)
|
handle a mavlink packet
|
def mavlink_packet(self, m):
'''handle a mavlink packet'''
mtype = m.get_type()
if mtype == "CAMERA_STATUS":
print ("Got Message camera_status")
if mtype == "CAMERA_FEEDBACK":
print ("Got Message camera_feedback")
'''self.__vCmdCamTrigger(m)'''
if mtype == "COMMAND_LONG":
if m.command == mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONFIGURE:
print ("Got Message Digicam_configure")
self.__vDecodeDIGICAMConfigure(m)
elif m.command == mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL:
print ("Got Message Digicam_control")
self.__vDecodeDIGICAMControl(m)
|
show flight modes for a log file
|
def flight_modes(logfile):
'''show flight modes for a log file'''
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename)
mode = ""
previous_mode = ""
mode_start_timestamp = -1
time_in_mode = {}
previous_percent = -1
seconds_per_percent = -1
filesize = os.path.getsize(filename)
while True:
m = mlog.recv_match(type=['SYS_STATUS','HEARTBEAT','MODE'],
condition='MAV.flightmode!="%s"' % mlog.flightmode)
if m is None:
break
print('%s MAV.flightmode=%-12s (MAV.timestamp=%u %u%%)' % (
time.asctime(time.localtime(m._timestamp)),
mlog.flightmode,
m._timestamp, mlog.percent))
mode = mlog.flightmode
if (mode not in time_in_mode):
time_in_mode[mode] = 0
if (mode_start_timestamp == -1):
mode_start_timestamp = m._timestamp
elif (previous_mode != "" and previous_mode != mode):
time_in_mode[previous_mode] = time_in_mode[previous_mode] + (m._timestamp - mode_start_timestamp)
#figure out how many seconds per percentage point so I can
#caculate how many seconds for the final mode
if (seconds_per_percent == -1 and previous_percent != -1
and previous_percent != mlog.percent):
seconds_per_percent = (m._timestamp - mode_start_timestamp) / (mlog.percent - previous_percent)
mode_start_timestamp = m._timestamp
previous_mode = mode
previous_percent = mlog.percent
#put a whitespace line before the per-mode report
print()
print("Time per mode:")
#need to get the time in the final mode
if (seconds_per_percent != -1):
seconds_remaining = (100.0 - previous_percent) * seconds_per_percent
time_in_mode[previous_mode] = time_in_mode[previous_mode] + seconds_remaining
total_flight_time = 0
for key, value in time_in_mode.iteritems():
total_flight_time = total_flight_time + value
for key, value in time_in_mode.iteritems():
print('%-12s %s %.2f%%' % (key, str(datetime.timedelta(seconds=int(value))), (value / total_flight_time) * 100.0))
else:
#can't print time in mode if only one mode during flight
print(previous_mode, " 100% of flight time")
|
return true if we have a graph of the given name
|
def have_graph(name):
'''return true if we have a graph of the given name'''
for g in mestate.graphs:
if g.name == name:
return True
return False
|
called on menu selection
|
def menu_callback(m):
'''called on menu selection'''
if m.returnkey.startswith('# '):
cmd = m.returnkey[2:]
if m.handler is not None:
if m.handler_result is None:
return
cmd += m.handler_result
process_stdin(cmd)
elif m.returnkey == 'menuSettings':
wxsettings.WXSettings(mestate.settings)
elif m.returnkey.startswith("mode-"):
idx = int(m.returnkey[5:])
mestate.flightmode_selections[idx] = m.IsChecked()
else:
print('Unknown menu selection: %s' % m.returnkey)
|
construct flightmode menu
|
def flightmode_menu():
'''construct flightmode menu'''
modes = mestate.mlog.flightmode_list()
ret = []
idx = 0
for (mode,t1,t2) in modes:
modestr = "%s %us" % (mode, (t2-t1))
ret.append(MPMenuCheckbox(modestr, modestr, 'mode-%u' % idx))
idx += 1
mestate.flightmode_selections.append(False)
return ret
|
return menu tree for graphs (recursive)
|
def graph_menus():
'''return menu tree for graphs (recursive)'''
ret = MPMenuSubMenu('Graphs', [])
for i in range(len(mestate.graphs)):
g = mestate.graphs[i]
path = g.name.split('/')
name = path[-1]
path = path[:-1]
ret.add_to_submenu(path, MPMenuItem(name, name, '# graph :%u' % i))
return ret
|
setup console menus
|
def setup_menus():
'''setup console menus'''
menu = MPMenuTop([])
menu.add(MPMenuSubMenu('MAVExplorer',
items=[MPMenuItem('Settings', 'Settings', 'menuSettings'),
MPMenuItem('Map', 'Map', '# map'),
MPMenuItem('Save Graph', 'Save', '# save'),
MPMenuItem('Reload Graphs', 'Reload', '# reload')]))
menu.add(graph_menus())
menu.add(MPMenuSubMenu('FlightMode', items=flightmode_menu()))
mestate.console.set_menu(menu, menu_callback)
|
return True if an expression is OK with current messages
|
def expression_ok(expression):
'''return True if an expression is OK with current messages'''
expression_ok = True
fields = expression.split()
for f in fields:
try:
if f.endswith(':2'):
f = f[:-2]
if mavutil.evaluate_expression(f, mestate.status.msgs) is None:
expression_ok = False
except Exception:
expression_ok = False
break
return expression_ok
|
load a graph from one xml string
|
def load_graph_xml(xml, filename, load_all=False):
'''load a graph from one xml string'''
ret = []
try:
root = objectify.fromstring(xml)
except Exception:
return []
if root.tag != 'graphs':
return []
if not hasattr(root, 'graph'):
return []
for g in root.graph:
name = g.attrib['name']
expressions = [e.text for e in g.expression]
if load_all:
ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
continue
if have_graph(name):
continue
for e in expressions:
if expression_ok(e):
ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
break
return ret
|
load graphs from mavgraphs.xml
|
def load_graphs():
'''load graphs from mavgraphs.xml'''
mestate.graphs = []
gfiles = ['mavgraphs.xml']
if 'HOME' in os.environ:
for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")):
for filename in filenames:
if filename.lower().endswith('.xml'):
gfiles.append(os.path.join(dirname, filename))
for file in gfiles:
if not os.path.exists(file):
continue
graphs = load_graph_xml(open(file).read(), file)
if graphs:
mestate.graphs.extend(graphs)
mestate.console.writeln("Loaded %s" % file)
# also load the built in graphs
dlist = pkg_resources.resource_listdir("MAVProxy", "tools/graphs")
for f in dlist:
raw = pkg_resources.resource_stream("MAVProxy", "tools/graphs/%s" % f).read()
graphs = load_graph_xml(raw, None)
if graphs:
mestate.graphs.extend(graphs)
mestate.console.writeln("Loaded %s" % f)
mestate.graphs = sorted(mestate.graphs, key=lambda g: g.name)
|
process for a graph
|
def graph_process(fields):
'''process for a graph'''
mestate.mlog.reduce_by_flightmodes(mestate.flightmode_selections)
mg = grapher.MavGraph()
mg.set_marker(mestate.settings.marker)
mg.set_condition(mestate.settings.condition)
mg.set_xaxis(mestate.settings.xaxis)
mg.set_linestyle(mestate.settings.linestyle)
mg.set_flightmode(mestate.settings.flightmode)
mg.set_legend(mestate.settings.legend)
mg.add_mav(mestate.mlog)
for f in fields:
mg.add_field(f)
mg.process()
mg.show()
|
display a graph
|
def display_graph(graphdef):
'''display a graph'''
mestate.console.write("Expression: %s\n" % ' '.join(graphdef.expression.split()))
child = multiprocessing.Process(target=graph_process, args=[graphdef.expression.split()])
child.start()
|
graph command
|
def cmd_graph(args):
'''graph command'''
usage = "usage: graph <FIELD...>"
if len(args) < 1:
print(usage)
return
if args[0][0] == ':':
i = int(args[0][1:])
g = mestate.graphs[i]
expression = g.expression
args = expression.split()
mestate.console.write("Added graph: %s\n" % g.name)
if g.description:
mestate.console.write("%s\n" % g.description, fg='blue')
mestate.rl.add_history("graph %s" % ' '.join(expression.split()))
mestate.last_graph = g
else:
expression = ' '.join(args)
mestate.last_graph = GraphDefinition('Untitled', expression, '', [expression], None)
display_graph(mestate.last_graph)
|
process for a graph
|
def map_process(args):
'''process for a graph'''
from mavflightview import mavflightview_mav, mavflightview_options
mestate.mlog.reduce_by_flightmodes(mestate.flightmode_selections)
options = mavflightview_options()
options.condition = mestate.settings.condition
if len(args) > 0:
options.types = ','.join(args)
mavflightview_mav(mestate.mlog, options)
|
map command
|
def cmd_map(args):
'''map command'''
child = multiprocessing.Process(target=map_process, args=[args])
child.start()
|
control MAVExporer conditions
|
def cmd_condition(args):
'''control MAVExporer conditions'''
if len(args) == 0:
print("condition is: %s" % mestate.settings.condition)
return
mestate.settings.condition = ' '.join(args)
if len(mestate.settings.condition) == 0 or mestate.settings.condition == 'clear':
mestate.settings.condition = None
|
reload graphs
|
def cmd_reload(args):
'''reload graphs'''
mestate.console.writeln('Reloading graphs', fg='blue')
load_graphs()
setup_menus()
mestate.console.write("Loaded %u graphs\n" % len(mestate.graphs))
|
save a graph as XML
|
def save_graph(graphdef):
'''save a graph as XML'''
if graphdef.filename is None:
if 'HOME' in os.environ:
dname = os.path.join(os.environ['HOME'], '.mavproxy')
mp_util.mkdir_p(dname)
graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
else:
graphdef.filename = 'mavgraphs.xml'
if graphdef.filename is None:
mestate.console.writeln("No file to save graph to", fg='red')
return
graphs = load_graph_xml(open(graphdef.filename).read(), graphdef.filename, load_all=True)
found_name = False
for i in range(len(graphs)):
if graphs[i].name == graphdef.name:
graphs[i] = graphdef
found_name = True
break
if not found_name:
graphs.append(graphdef)
mestate.console.writeln("Saving %u graphs to %s" % (len(graphs), graphdef.filename))
f = open(graphdef.filename, "w")
f.write("<graphs>\n\n")
for g in graphs:
f.write(" <graph name='%s'>\n" % g.name.strip())
if g.description is None:
g.description = ''
f.write(" <description>%s</description>\n" % g.description.strip())
for e in g.expressions:
f.write(" <expression>%s</expression>\n" % e.strip())
f.write(" </graph>\n\n")
f.write("</graphs>\n")
f.close()
|
callback from save thread
|
def save_callback(operation, graphdef):
'''callback from save thread'''
if operation == 'test':
for e in graphdef.expressions:
if expression_ok(e):
graphdef.expression = e
display_graph(graphdef)
return
mestate.console.writeln('Invalid graph expressions', fg='red')
return
if operation == 'save':
save_graph(graphdef)
|
process for saving a graph
|
def save_process():
'''process for saving a graph'''
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxgrapheditor import GraphDialog
app = wx.App(False)
frame = GraphDialog('Graph Editor',
mestate.last_graph,
save_callback)
frame.ShowModal()
frame.Destroy()
|
show parameters
|
def cmd_param(args):
'''show parameters'''
if len(args) > 0:
wildcard = args[0]
else:
wildcard = '*'
k = sorted(mestate.mlog.params.keys())
for p in k:
if fnmatch.fnmatch(str(p).upper(), wildcard.upper()):
print("%-16.16s %f" % (str(p), mestate.mlog.params[p]))
|
main processing loop, display graphs and maps
|
def main_loop():
'''main processing loop, display graphs and maps'''
while True:
if mestate is None or mestate.exit:
return
while not mestate.input_queue.empty():
line = mestate.input_queue.get()
cmds = line.split(';')
for c in cmds:
process_stdin(c)
time.sleep(0.1)
|
Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 : b_f[0] (float)
accel_1 : b_f[1] (float)
accel_2 : b_f[2] (float)
gyro_0 : b_f[0] (float)
gyro_1 : b_f[1] (float)
gyro_2 : b_f[2] (float)
|
def nav_filter_bias_encode(self, usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2):
'''
Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 : b_f[0] (float)
accel_1 : b_f[1] (float)
accel_2 : b_f[2] (float)
gyro_0 : b_f[0] (float)
gyro_1 : b_f[1] (float)
gyro_2 : b_f[2] (float)
'''
return MAVLink_nav_filter_bias_message(usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2)
|
Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 : b_f[0] (float)
accel_1 : b_f[1] (float)
accel_2 : b_f[2] (float)
gyro_0 : b_f[0] (float)
gyro_1 : b_f[1] (float)
gyro_2 : b_f[2] (float)
|
def nav_filter_bias_send(self, usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2, force_mavlink1=False):
'''
Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 : b_f[0] (float)
accel_1 : b_f[1] (float)
accel_2 : b_f[2] (float)
gyro_0 : b_f[0] (float)
gyro_1 : b_f[1] (float)
gyro_2 : b_f[2] (float)
'''
return self.send(self.nav_filter_bias_encode(usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2), force_mavlink1=force_mavlink1)
|
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator : Elevator setpoints: nose down, center, nose up (uint16_t)
rudder : Rudder setpoints: nose left, center, nose right (uint16_t)
gyro : Tail gyro mode/gain setpoints: heading hold, rate mode (uint16_t)
pitch : Pitch curve setpoints (every 25%) (uint16_t)
throttle : Throttle curve setpoints (every 25%) (uint16_t)
|
def radio_calibration_encode(self, aileron, elevator, rudder, gyro, pitch, throttle):
'''
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator : Elevator setpoints: nose down, center, nose up (uint16_t)
rudder : Rudder setpoints: nose left, center, nose right (uint16_t)
gyro : Tail gyro mode/gain setpoints: heading hold, rate mode (uint16_t)
pitch : Pitch curve setpoints (every 25%) (uint16_t)
throttle : Throttle curve setpoints (every 25%) (uint16_t)
'''
return MAVLink_radio_calibration_message(aileron, elevator, rudder, gyro, pitch, throttle)
|
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator : Elevator setpoints: nose down, center, nose up (uint16_t)
rudder : Rudder setpoints: nose left, center, nose right (uint16_t)
gyro : Tail gyro mode/gain setpoints: heading hold, rate mode (uint16_t)
pitch : Pitch curve setpoints (every 25%) (uint16_t)
throttle : Throttle curve setpoints (every 25%) (uint16_t)
|
def radio_calibration_send(self, aileron, elevator, rudder, gyro, pitch, throttle, force_mavlink1=False):
'''
Complete set of calibration parameters for the radio
aileron : Aileron setpoints: left, center, right (uint16_t)
elevator : Elevator setpoints: nose down, center, nose up (uint16_t)
rudder : Rudder setpoints: nose left, center, nose right (uint16_t)
gyro : Tail gyro mode/gain setpoints: heading hold, rate mode (uint16_t)
pitch : Pitch curve setpoints (every 25%) (uint16_t)
throttle : Throttle curve setpoints (every 25%) (uint16_t)
'''
return self.send(self.radio_calibration_encode(aileron, elevator, rudder, gyro, pitch, throttle), force_mavlink1=force_mavlink1)
|
System status specific to ualberta uav
mode : System mode, see UALBERTA_AUTOPILOT_MODE ENUM (uint8_t)
nav_mode : Navigation mode, see UALBERTA_NAV_MODE ENUM (uint8_t)
pilot : Pilot mode, see UALBERTA_PILOT_MODE (uint8_t)
|
def ualberta_sys_status_send(self, mode, nav_mode, pilot, force_mavlink1=False):
'''
System status specific to ualberta uav
mode : System mode, see UALBERTA_AUTOPILOT_MODE ENUM (uint8_t)
nav_mode : Navigation mode, see UALBERTA_NAV_MODE ENUM (uint8_t)
pilot : Pilot mode, see UALBERTA_PILOT_MODE (uint8_t)
'''
return self.send(self.ualberta_sys_status_encode(mode, nav_mode, pilot), force_mavlink1=force_mavlink1)
|
The RAW values of the servo outputs (for RC input from the remote, use
the RC_CHANNELS messages). The standard PPM modulation
is as follows: 1000 microseconds: 0%, 2000
microseconds: 100%.
time_usec : Timestamp (microseconds since system boot) (uint32_t)
port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows to encode more than 8 servos. (uint8_t)
servo1_raw : Servo output 1 value, in microseconds (uint16_t)
servo2_raw : Servo output 2 value, in microseconds (uint16_t)
servo3_raw : Servo output 3 value, in microseconds (uint16_t)
servo4_raw : Servo output 4 value, in microseconds (uint16_t)
servo5_raw : Servo output 5 value, in microseconds (uint16_t)
servo6_raw : Servo output 6 value, in microseconds (uint16_t)
servo7_raw : Servo output 7 value, in microseconds (uint16_t)
servo8_raw : Servo output 8 value, in microseconds (uint16_t)
servo9_raw : Servo output 9 value, in microseconds (uint16_t)
servo10_raw : Servo output 10 value, in microseconds (uint16_t)
servo11_raw : Servo output 11 value, in microseconds (uint16_t)
servo12_raw : Servo output 12 value, in microseconds (uint16_t)
servo13_raw : Servo output 13 value, in microseconds (uint16_t)
servo14_raw : Servo output 14 value, in microseconds (uint16_t)
servo15_raw : Servo output 15 value, in microseconds (uint16_t)
servo16_raw : Servo output 16 value, in microseconds (uint16_t)
|
def servo_output_raw_encode(self, time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw, servo10_raw, servo11_raw, servo12_raw, servo13_raw, servo14_raw, servo15_raw, servo16_raw):
'''
The RAW values of the servo outputs (for RC input from the remote, use
the RC_CHANNELS messages). The standard PPM modulation
is as follows: 1000 microseconds: 0%, 2000
microseconds: 100%.
time_usec : Timestamp (microseconds since system boot) (uint32_t)
port : Servo output port (set of 8 outputs = 1 port). Most MAVs will just use one, but this allows to encode more than 8 servos. (uint8_t)
servo1_raw : Servo output 1 value, in microseconds (uint16_t)
servo2_raw : Servo output 2 value, in microseconds (uint16_t)
servo3_raw : Servo output 3 value, in microseconds (uint16_t)
servo4_raw : Servo output 4 value, in microseconds (uint16_t)
servo5_raw : Servo output 5 value, in microseconds (uint16_t)
servo6_raw : Servo output 6 value, in microseconds (uint16_t)
servo7_raw : Servo output 7 value, in microseconds (uint16_t)
servo8_raw : Servo output 8 value, in microseconds (uint16_t)
servo9_raw : Servo output 9 value, in microseconds (uint16_t)
servo10_raw : Servo output 10 value, in microseconds (uint16_t)
servo11_raw : Servo output 11 value, in microseconds (uint16_t)
servo12_raw : Servo output 12 value, in microseconds (uint16_t)
servo13_raw : Servo output 13 value, in microseconds (uint16_t)
servo14_raw : Servo output 14 value, in microseconds (uint16_t)
servo15_raw : Servo output 15 value, in microseconds (uint16_t)
servo16_raw : Servo output 16 value, in microseconds (uint16_t)
'''
return MAVLink_servo_output_raw_message(time_usec, port, servo1_raw, servo2_raw, servo3_raw, servo4_raw, servo5_raw, servo6_raw, servo7_raw, servo8_raw, servo9_raw, servo10_raw, servo11_raw, servo12_raw, servo13_raw, servo14_raw, servo15_raw, servo16_raw)
|
Setup a MAVLink2 signing key. If called with secret_key of all zero
and zero initial_timestamp will disable signing
target_system : system id of the target (uint8_t)
target_component : component ID of the target (uint8_t)
secret_key : signing key (uint8_t)
initial_timestamp : initial timestamp (uint64_t)
|
def setup_signing_encode(self, target_system, target_component, secret_key, initial_timestamp):
'''
Setup a MAVLink2 signing key. If called with secret_key of all zero
and zero initial_timestamp will disable signing
target_system : system id of the target (uint8_t)
target_component : component ID of the target (uint8_t)
secret_key : signing key (uint8_t)
initial_timestamp : initial timestamp (uint64_t)
'''
return MAVLink_setup_signing_message(target_system, target_component, secret_key, initial_timestamp)
|
Setup a MAVLink2 signing key. If called with secret_key of all zero
and zero initial_timestamp will disable signing
target_system : system id of the target (uint8_t)
target_component : component ID of the target (uint8_t)
secret_key : signing key (uint8_t)
initial_timestamp : initial timestamp (uint64_t)
|
def setup_signing_send(self, target_system, target_component, secret_key, initial_timestamp, force_mavlink1=False):
'''
Setup a MAVLink2 signing key. If called with secret_key of all zero
and zero initial_timestamp will disable signing
target_system : system id of the target (uint8_t)
target_component : component ID of the target (uint8_t)
secret_key : signing key (uint8_t)
initial_timestamp : initial timestamp (uint64_t)
'''
return self.send(self.setup_signing_encode(target_system, target_component, secret_key, initial_timestamp), force_mavlink1=force_mavlink1)
|
Report button state change
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
last_change_ms : Time of last change of button state (uint32_t)
state : Bitmap state of buttons (uint8_t)
|
def button_change_send(self, time_boot_ms, last_change_ms, state, force_mavlink1=False):
'''
Report button state change
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
last_change_ms : Time of last change of button state (uint32_t)
state : Bitmap state of buttons (uint8_t)
'''
return self.send(self.button_change_encode(time_boot_ms, last_change_ms, state), force_mavlink1=force_mavlink1)
|
Control vehicle tone generation (buzzer)
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
tune : tune in board specific format (char)
|
def play_tune_send(self, target_system, target_component, tune, force_mavlink1=False):
'''
Control vehicle tone generation (buzzer)
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
tune : tune in board specific format (char)
'''
return self.send(self.play_tune_encode(target_system, target_component, tune), force_mavlink1=force_mavlink1)
|
Convert latitude and longitude data to UTM as a list of coordinates.
Input
points: list of points given in decimal degrees (latitude, longitude) or
latitudes: list of latitudes and
longitudes: list of longitudes
false_easting (optional)
false_northing (optional)
Output
points: List of converted points
zone: Common UTM zone for converted points
Notes
Assume the false_easting and false_northing are the same for each list.
If points end up in different UTM zones, an ANUGAerror is thrown.
|
def convert_from_latlon_to_utm(points=None,
latitudes=None,
longitudes=None,
false_easting=None,
false_northing=None):
"""Convert latitude and longitude data to UTM as a list of coordinates.
Input
points: list of points given in decimal degrees (latitude, longitude) or
latitudes: list of latitudes and
longitudes: list of longitudes
false_easting (optional)
false_northing (optional)
Output
points: List of converted points
zone: Common UTM zone for converted points
Notes
Assume the false_easting and false_northing are the same for each list.
If points end up in different UTM zones, an ANUGAerror is thrown.
"""
old_geo = Geo_reference()
utm_points = []
if points == None:
assert len(latitudes) == len(longitudes)
points = map(None, latitudes, longitudes)
for point in points:
zone, easting, northing = redfearn(float(point[0]),
float(point[1]),
false_easting=false_easting,
false_northing=false_northing)
new_geo = Geo_reference(zone)
old_geo.reconcile_zones(new_geo)
utm_points.append([easting, northing])
return utm_points, old_geo.get_zone()
|
convert a mavlink log file to a GPX file
|
def mav_to_gpx(infilename, outfilename):
'''convert a mavlink log file to a GPX file'''
mlog = mavutil.mavlink_connection(infilename)
outf = open(outfilename, mode='w')
def process_packet(timestamp, lat, lon, alt, hdg, v):
t = time.localtime(timestamp)
outf.write('''<trkpt lat="%s" lon="%s">
<ele>%s</ele>
<time>%s</time>
<course>%s</course>
<speed>%s</speed>
<fix>3d</fix>
</trkpt>
''' % (lat, lon, alt,
time.strftime("%Y-%m-%dT%H:%M:%SZ", t),
hdg, v))
def add_header():
outf.write('''<?xml version="1.0" encoding="UTF-8"?>
<gpx
version="1.0"
creator="pymavlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/0"
xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">
<trk>
<trkseg>
''')
def add_footer():
outf.write('''</trkseg>
</trk>
</gpx>
''')
add_header()
count=0
lat=0
lon=0
fix=0
while True:
m = mlog.recv_match(type=['GPS_RAW', 'GPS_RAW_INT', 'GPS', 'GPS2'], condition=args.condition)
if m is None:
break
if m.get_type() == 'GPS_RAW_INT':
lat = m.lat/1.0e7
lon = m.lon/1.0e7
alt = m.alt/1.0e3
v = m.vel/100.0
hdg = m.cog/100.0
timestamp = m._timestamp
fix = m.fix_type
elif m.get_type() == 'GPS_RAW':
lat = m.lat
lon = m.lon
alt = m.alt
v = m.v
hdg = m.hdg
timestamp = m._timestamp
fix = m.fix_type
elif m.get_type() == 'GPS' or m.get_type() == 'GPS2':
lat = m.Lat
lon = m.Lng
alt = m.Alt
v = m.Spd
hdg = m.GCrs
timestamp = m._timestamp
fix = m.Status
else:
pass
if fix < 2 and not args.nofixcheck:
continue
if lat == 0.0 or lon == 0.0:
continue
process_packet(timestamp, lat, lon, alt, hdg, v)
count += 1
add_footer()
print("Created %s with %u points" % (outfilename, count))
|
Get the quaternion
:returns: array containing the quaternion elements
|
def q(self):
"""
Get the quaternion
:returns: array containing the quaternion elements
"""
if self._q is None:
if self._euler is not None:
# get q from euler
self._q = self._euler_to_q(self.euler)
elif self._dcm is not None:
# get q from DCM
self._q = self._dcm_to_q(self.dcm)
return self._q
|
Set the quaternion
:param q: list or array of quaternion values [w, x, y, z]
|
def q(self, q):
"""
Set the quaternion
:param q: list or array of quaternion values [w, x, y, z]
"""
self._q = np.array(q)
# mark other representations as outdated, will get generated on next
# read
self._euler = None
self._dcm = None
|
Get the euler angles.
The convention is Tait-Bryan (ZY'X'')
:returns: array containing the euler angles [roll, pitch, yaw]
|
def euler(self):
"""
Get the euler angles.
The convention is Tait-Bryan (ZY'X'')
:returns: array containing the euler angles [roll, pitch, yaw]
"""
if self._euler is None:
if self._q is not None:
# try to get euler angles from q via DCM
self._dcm = self._q_to_dcm(self.q)
self._euler = self._dcm_to_euler(self.dcm)
elif self._dcm is not None:
# get euler angles from DCM
self._euler = self._dcm_to_euler(self.dcm)
return self._euler
|
Set the euler angles
:param euler: list or array of the euler angles [roll, pitch, yaw]
|
def euler(self, euler):
"""
Set the euler angles
:param euler: list or array of the euler angles [roll, pitch, yaw]
"""
assert(len(euler) == 3)
self._euler = np.array(euler)
# mark other representations as outdated, will get generated on next
# read
self._q = None
self._dcm = None
|
Get the DCM
:returns: 3x3 array
|
def dcm(self):
"""
Get the DCM
:returns: 3x3 array
"""
if self._dcm is None:
if self._q is not None:
# try to get dcm from q
self._dcm = self._q_to_dcm(self.q)
elif self._euler is not None:
# try to get get dcm from euler
self._dcm = self._euler_to_dcm(self._euler)
return self._dcm
|
Set the DCM
:param dcm: 3x3 array
|
def dcm(self, dcm):
"""
Set the DCM
:param dcm: 3x3 array
"""
assert(len(dcm) == 3)
for sub in dcm:
assert(len(sub) == 3)
self._dcm = np.array(dcm)
# mark other representations as outdated, will get generated on next
# read
self._q = None
self._euler = None
|
Calculates the vector transformed by this quaternion
:param v: array with len 3 to be transformed
:returns: transformed vector
|
def transform(self, v):
"""
Calculates the vector transformed by this quaternion
:param v: array with len 3 to be transformed
:returns: transformed vector
"""
assert(len(v) == 3)
assert(np.allclose(self.norm, 1))
# perform transformation t = q * [0, v] * q^-1 but avoid multiplication
# because terms cancel out
q0 = self.q[0]
qi = self.q[1:4]
ui = np.array(v)
a = q0 * ui + np.cross(qi, ui)
t = np.dot(qi, ui) * qi + q0 * a - np.cross(a, qi)
return t
|
Equality test with tolerance
(same orientation, not necessarily same rotation)
:param other: a QuaternionBase
:returns: true if the quaternions are almost equal
|
def close(self, other):
"""
Equality test with tolerance
(same orientation, not necessarily same rotation)
:param other: a QuaternionBase
:returns: true if the quaternions are almost equal
"""
if isinstance(other, QuaternionBase):
return np.allclose(self.q, other.q) or np.allclose(self.q, -other.q)
return NotImplemented
|
Normalizes the list with len 4 so that it can be used as quaternion
:param q: array of len 4
:returns: normalized array
|
def normalize_array(q):
"""
Normalizes the list with len 4 so that it can be used as quaternion
:param q: array of len 4
:returns: normalized array
"""
assert(len(q) == 4)
q = np.array(q)
n = QuaternionBase.norm_array(q)
return q / n
|
Calculate quaternion norm on array q
:param quaternion: array of len 4
:returns: norm (scalar)
|
def norm_array(q):
"""
Calculate quaternion norm on array q
:param quaternion: array of len 4
:returns: norm (scalar)
"""
assert(len(q) == 4)
return np.sqrt(np.dot(q, q))
|
Performs multiplication of the 2 quaterniona arrays p and q
:param p: array of len 4
:param q: array of len 4
:returns: array of len, result of p * q (with p, q quaternions)
|
def _mul_array(self, p, q):
"""
Performs multiplication of the 2 quaterniona arrays p and q
:param p: array of len 4
:param q: array of len 4
:returns: array of len, result of p * q (with p, q quaternions)
"""
assert(len(q) == len(p) == 4)
p0 = p[0]
pi = p[1:4]
q0 = q[0]
qi = q[1:4]
res = np.zeros(4)
res[0] = p0 * q0 - np.dot(pi, qi)
res[1:4] = p0 * qi + q0 * pi + np.cross(pi, qi)
return res
|
Create q array from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: array q which represents a quaternion [w, x, y, z]
|
def _euler_to_q(self, euler):
"""
Create q array from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: array q which represents a quaternion [w, x, y, z]
"""
assert(len(euler) == 3)
phi = euler[0]
theta = euler[1]
psi = euler[2]
c_phi_2 = np.cos(phi / 2)
s_phi_2 = np.sin(phi / 2)
c_theta_2 = np.cos(theta / 2)
s_theta_2 = np.sin(theta / 2)
c_psi_2 = np.cos(psi / 2)
s_psi_2 = np.sin(psi / 2)
q = np.zeros(4)
q[0] = (c_phi_2 * c_theta_2 * c_psi_2 +
s_phi_2 * s_theta_2 * s_psi_2)
q[1] = (s_phi_2 * c_theta_2 * c_psi_2 -
c_phi_2 * s_theta_2 * s_psi_2)
q[2] = (c_phi_2 * s_theta_2 * c_psi_2 +
s_phi_2 * c_theta_2 * s_psi_2)
q[3] = (c_phi_2 * c_theta_2 * s_psi_2 -
s_phi_2 * s_theta_2 * c_psi_2)
return q
|
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
|
def _q_to_dcm(self, q):
"""
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
"""
assert(len(q) == 4)
assert(np.allclose(QuaternionBase.norm_array(q), 1))
dcm = np.zeros([3, 3])
a = q[0]
b = q[1]
c = q[2]
d = q[3]
a_sq = a * a
b_sq = b * b
c_sq = c * c
d_sq = d * d
dcm[0][0] = a_sq + b_sq - c_sq - d_sq
dcm[0][1] = 2 * (b * c - a * d)
dcm[0][2] = 2 * (a * c + b * d)
dcm[1][0] = 2 * (b * c + a * d)
dcm[1][1] = a_sq - b_sq + c_sq - d_sq
dcm[1][2] = 2 * (c * d - a * b)
dcm[2][0] = 2 * (b * d - a * c)
dcm[2][1] = 2 * (a * b + c * d)
dcm[2][2] = a_sq - b_sq - c_sq + d_sq
return dcm
|
Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array
|
def _dcm_to_q(self, dcm):
"""
Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array
"""
assert(dcm.shape == (3, 3))
q = np.zeros(4)
tr = np.trace(dcm)
if tr > 0:
s = np.sqrt(tr + 1.0)
q[0] = s * 0.5
s = 0.5 / s
q[1] = (dcm[2][1] - dcm[1][2]) * s
q[2] = (dcm[0][2] - dcm[2][0]) * s
q[3] = (dcm[1][0] - dcm[0][1]) * s
else:
dcm_i = np.argmax(np.diag(dcm))
dcm_j = (dcm_i + 1) % 3
dcm_k = (dcm_i + 2) % 3
s = np.sqrt((dcm[dcm_i][dcm_i] - dcm[dcm_j][dcm_j] -
dcm[dcm_k][dcm_k]) + 1.0)
q[dcm_i + 1] = s * 0.5
s = 0.5 / s
q[dcm_j + 1] = (dcm[dcm_i][dcm_j] + dcm[dcm_j][dcm_i]) * s
q[dcm_k + 1] = (dcm[dcm_k][dcm_i] + dcm[dcm_i][dcm_k]) * s
q[0] = (dcm[dcm_k][dcm_j] - dcm[dcm_j][dcm_k]) * s
return q
|
Create DCM from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: 3x3 dcm array
|
def _euler_to_dcm(self, euler):
"""
Create DCM from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: 3x3 dcm array
"""
assert(len(euler) == 3)
phi = euler[0]
theta = euler[1]
psi = euler[2]
dcm = np.zeros([3, 3])
c_phi = np.cos(phi)
s_phi = np.sin(phi)
c_theta = np.cos(theta)
s_theta = np.sin(theta)
c_psi = np.cos(psi)
s_psi = np.sin(psi)
dcm[0][0] = c_theta * c_psi
dcm[0][1] = -c_phi * s_psi + s_phi * s_theta * c_psi
dcm[0][2] = s_phi * s_psi + c_phi * s_theta * c_psi
dcm[1][0] = c_theta * s_psi
dcm[1][1] = c_phi * c_psi + s_phi * s_theta * s_psi
dcm[1][2] = -s_phi * c_psi + c_phi * s_theta * s_psi
dcm[2][0] = -s_theta
dcm[2][1] = s_phi * c_theta
dcm[2][2] = c_phi * c_theta
return dcm
|
Set the DCM
:param dcm: Matrix3
|
def dcm(self, dcm):
"""
Set the DCM
:param dcm: Matrix3
"""
assert(isinstance(dcm, Matrix3))
self._dcm = dcm.copy()
# mark other representations as outdated, will get generated on next
# read
self._q = None
self._euler = None
|
Create DCM from euler angles
:param dcm: 3x3 dcm array
:returns: array [roll, pitch, yaw] in rad
|
def _dcm_to_euler(self, dcm):
"""
Create DCM from euler angles
:param dcm: 3x3 dcm array
:returns: array [roll, pitch, yaw] in rad
"""
assert(dcm.shape == (3, 3))
theta = np.arcsin(min(1, max(-1, -dcm[2][0])))
if abs(theta - np.pi/2) < 1.0e-3:
phi = 0.0
psi = (np.arctan2(dcm[1][2] - dcm[0][1],
dcm[0][2] + dcm[1][1]) + phi)
elif abs(theta + np.pi/2) < 1.0e-3:
phi = 0.0
psi = np.arctan2(dcm[1][2] - dcm[0][1],
dcm[0][2] + dcm[1][1] - phi)
else:
phi = np.arctan2(dcm[2][1], dcm[2][2])
psi = np.arctan2(dcm[1][0], dcm[0][0])
return np.array([phi, theta, psi])
|
Calculates the vector transformed by this quaternion
:param v3: Vector3 to be transformed
:returns: transformed vector
|
def transform(self, v3):
"""
Calculates the vector transformed by this quaternion
:param v3: Vector3 to be transformed
:returns: transformed vector
"""
if isinstance(v3, Vector3):
t = super(Quaternion, self).transform([v3.x, v3.y, v3.z])
return Vector3(t[0], t[1], t[2])
elif len(v3) == 3:
return super(Quaternion, self).transform(v3)
else:
raise TypeError("param v3 is not a vector type")
|
Converts dcm array into Matrix3
:param dcm: 3x3 dcm array
:returns: Matrix3
|
def _dcm_array_to_matrix3(self, dcm):
"""
Converts dcm array into Matrix3
:param dcm: 3x3 dcm array
:returns: Matrix3
"""
assert(dcm.shape == (3, 3))
a = Vector3(dcm[0][0], dcm[0][1], dcm[0][2])
b = Vector3(dcm[1][0], dcm[1][1], dcm[1][2])
c = Vector3(dcm[2][0], dcm[2][1], dcm[2][2])
return Matrix3(a, b, c)
|
Converts Matrix3 in an array
:param m: Matrix3
:returns: 3x3 array
|
def _matrix3_to_dcm_array(self, m):
"""
Converts Matrix3 in an array
:param m: Matrix3
:returns: 3x3 array
"""
assert(isinstance(m, Matrix3))
return np.array([[m.a.x, m.a.y, m.a.z],
[m.b.x, m.b.y, m.b.z],
[m.c.x, m.c.y, m.c.z]])
|
Create DCM (Matrix3) from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: Matrix3
|
def _q_to_dcm(self, q):
"""
Create DCM (Matrix3) from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: Matrix3
"""
assert(len(q) == 4)
arr = super(Quaternion, self)._q_to_dcm(q)
return self._dcm_array_to_matrix3(arr)
|
Create q from dcm (Matrix3)
:param dcm: Matrix3
:returns: array q which represents a quaternion [w, x, y, z]
|
def _dcm_to_q(self, dcm):
"""
Create q from dcm (Matrix3)
:param dcm: Matrix3
:returns: array q which represents a quaternion [w, x, y, z]
"""
assert(isinstance(dcm, Matrix3))
arr = self._matrix3_to_dcm_array(dcm)
return super(Quaternion, self)._dcm_to_q(arr)
|
Create DCM (Matrix3) from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: Matrix3
|
def _euler_to_dcm(self, euler):
"""
Create DCM (Matrix3) from euler angles
:param euler: array [roll, pitch, yaw] in rad
:returns: Matrix3
"""
assert(len(euler) == 3)
m = Matrix3()
m.from_euler(*euler)
return m
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.