INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
wrapper for waypoint_request_list_send
|
def waypoint_request_list_send(self):
'''wrapper for waypoint_request_list_send'''
if self.mavlink10():
self.mav.mission_request_list_send(self.target_system, self.target_component)
else:
self.mav.waypoint_request_list_send(self.target_system, self.target_component)
|
wrapper for waypoint_clear_all_send
|
def waypoint_clear_all_send(self):
'''wrapper for waypoint_clear_all_send'''
if self.mavlink10():
self.mav.mission_clear_all_send(self.target_system, self.target_component)
else:
self.mav.waypoint_clear_all_send(self.target_system, self.target_component)
|
wrapper for waypoint_request_send
|
def waypoint_request_send(self, seq):
'''wrapper for waypoint_request_send'''
if self.mavlink10():
self.mav.mission_request_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_request_send(self.target_system, self.target_component, seq)
|
wrapper for waypoint_set_current_send
|
def waypoint_set_current_send(self, seq):
'''wrapper for waypoint_set_current_send'''
if self.mavlink10():
self.mav.mission_set_current_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_set_current_send(self.target_system, self.target_component, seq)
|
return current waypoint
|
def waypoint_current(self):
'''return current waypoint'''
if self.mavlink10():
m = self.recv_match(type='MISSION_CURRENT', blocking=True)
else:
m = self.recv_match(type='WAYPOINT_CURRENT', blocking=True)
return m.seq
|
wrapper for waypoint_count_send
|
def waypoint_count_send(self, seq):
'''wrapper for waypoint_count_send'''
if self.mavlink10():
self.mav.mission_count_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_count_send(self.target_system, self.target_component, seq)
|
Enables/ disables MAV_MODE_FLAG
@param flag The mode flag,
see MAV_MODE_FLAG enum
@param enable Enable the flag, (True/False)
|
def set_mode_flag(self, flag, enable):
'''
Enables/ disables MAV_MODE_FLAG
@param flag The mode flag,
see MAV_MODE_FLAG enum
@param enable Enable the flag, (True/False)
'''
if self.mavlink10():
mode = self.base_mode
if (enable == True):
mode = mode | flag
elif (enable == False):
mode = mode & ~flag
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0,
mode,
0, 0, 0, 0, 0, 0)
else:
print("Set mode flag not supported")
|
enter auto mode
|
def set_mode_auto(self):
'''enter auto mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_MISSION_START, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_SET_AUTO = 13
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_AUTO)
|
return dictionary mapping mode names to numbers, or None if unknown
|
def mode_mapping(self):
'''return dictionary mapping mode names to numbers, or None if unknown'''
mav_type = self.field('HEARTBEAT', 'type', self.mav_type)
mav_autopilot = self.field('HEARTBEAT', 'autopilot', None)
if mav_autopilot == mavlink.MAV_AUTOPILOT_PX4:
return px4_map
if mav_type is None:
return None
map = None
if mav_type in [mavlink.MAV_TYPE_QUADROTOR,
mavlink.MAV_TYPE_HELICOPTER,
mavlink.MAV_TYPE_HEXAROTOR,
mavlink.MAV_TYPE_OCTOROTOR,
mavlink.MAV_TYPE_COAXIAL,
mavlink.MAV_TYPE_TRICOPTER]:
map = mode_mapping_acm
if mav_type == mavlink.MAV_TYPE_FIXED_WING:
map = mode_mapping_apm
if mav_type == mavlink.MAV_TYPE_GROUND_ROVER:
map = mode_mapping_rover
if mav_type == mavlink.MAV_TYPE_ANTENNA_TRACKER:
map = mode_mapping_tracker
if map is None:
return None
inv_map = dict((a, b) for (b, a) in list(map.items()))
return inv_map
|
enter arbitrary mode
|
def set_mode_apm(self, mode, custom_mode = 0, custom_sub_mode = 0):
'''enter arbitrary mode'''
if isinstance(mode, str):
mode_map = self.mode_mapping()
if mode_map is None or mode not in mode_map:
print("Unknown mode '%s'" % mode)
return
mode = mode_map[mode]
# set mode by integer mode number for ArduPilot
self.mav.set_mode_send(self.target_system,
mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,
mode)
|
enter arbitrary mode
|
def set_mode_px4(self, mode, custom_mode, custom_sub_mode):
'''enter arbitrary mode'''
if isinstance(mode, str):
mode_map = self.mode_mapping()
if mode_map is None or mode not in mode_map:
print("Unknown mode '%s'" % mode)
return
# PX4 uses two fields to define modes
mode, custom_mode, custom_sub_mode = px4_map[mode]
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0, mode, custom_mode, custom_sub_mode, 0, 0, 0, 0)
|
set arbitrary flight mode
|
def set_mode(self, mode, custom_mode = 0, custom_sub_mode = 0):
'''set arbitrary flight mode'''
mav_autopilot = self.field('HEARTBEAT', 'autopilot', None)
if mav_autopilot == mavlink.MAV_AUTOPILOT_PX4:
self.set_mode_px4(mode, custom_mode, custom_sub_mode)
else:
self.set_mode_apm(mode)
|
enter RTL mode
|
def set_mode_rtl(self):
'''enter RTL mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_RETURN = 3
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_RETURN)
|
enter MANUAL mode
|
def set_mode_manual(self):
'''enter MANUAL mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0,
mavlink.MAV_MODE_MANUAL_ARMED,
0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_SET_MANUAL = 12
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_SET_MANUAL)
|
enter FBWA mode
|
def set_mode_fbwa(self):
'''enter FBWA mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_MODE, 0,
mavlink.MAV_MODE_STABILIZE_ARMED,
0, 0, 0, 0, 0, 0)
else:
print("Forcing FBWA not supported")
|
enter LOITER mode
|
def set_mode_loiter(self):
'''enter LOITER mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_NAV_LOITER_UNLIM, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_LOITER = 27
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_LOITER)
|
set a servo value
|
def set_servo(self, channel, pwm):
'''set a servo value'''
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_DO_SET_SERVO, 0,
channel, pwm,
0, 0, 0, 0, 0)
|
Set relay_pin to value of state
|
def set_relay(self, relay_pin=0, state=True):
'''Set relay_pin to value of state'''
if self.mavlink10():
self.mav.command_long_send(
self.target_system, # target_system
self.target_component, # target_component
mavlink.MAV_CMD_DO_SET_RELAY, # command
0, # Confirmation
relay_pin, # Relay Number
int(state), # state (1 to indicate arm)
0, # param3 (all other params meaningless)
0, # param4
0, # param5
0, # param6
0) # param7
else:
print("Setting relays not supported.")
|
calibrate accels (1D version)
|
def calibrate_level(self):
'''calibrate accels (1D version)'''
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
1, 1, 0, 0, 0, 0, 0)
|
calibrate pressure
|
def calibrate_pressure(self):
'''calibrate pressure'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 1, 0, 0, 0, 0)
else:
MAV_ACTION_CALIBRATE_PRESSURE = 20
self.mav.action_send(self.target_system, self.target_component, MAV_ACTION_CALIBRATE_PRESSURE)
|
reboot the autopilot
|
def reboot_autopilot(self, hold_in_bootloader=False):
'''reboot the autopilot'''
if self.mavlink10():
if hold_in_bootloader:
param1 = 3
else:
param1 = 1
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0,
param1, 0, 0, 0, 0, 0, 0)
# send an old style reboot immediately afterwards in case it is an older firmware
# that doesn't understand the new convention
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0,
1, 0, 0, 0, 0, 0, 0)
|
return current location
|
def location(self, relative_alt=False):
'''return current location'''
self.wait_gps_fix()
# wait for another VFR_HUD, to ensure we have correct altitude
self.recv_match(type='VFR_HUD', blocking=True)
self.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if relative_alt:
alt = self.messages['GLOBAL_POSITION_INT'].relative_alt*0.001
else:
alt = self.messages['VFR_HUD'].alt
return location(self.messages['GPS_RAW_INT'].lat*1.0e-7,
self.messages['GPS_RAW_INT'].lon*1.0e-7,
alt,
self.messages['VFR_HUD'].heading)
|
arm motors (arducopter only)
|
def arducopter_arm(self):
'''arm motors (arducopter only)'''
if self.mavlink10():
self.mav.command_long_send(
self.target_system, # target_system
self.target_component,
mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command
0, # confirmation
1, # param1 (1 to indicate arm)
0, # param2 (all other params meaningless)
0, # param3
0, # param4
0, # param5
0, # param6
0)
|
return true if motors armed
|
def motors_armed(self):
'''return true if motors armed'''
if not 'HEARTBEAT' in self.messages:
return False
m = self.messages['HEARTBEAT']
return (m.base_mode & mavlink.MAV_MODE_FLAG_SAFETY_ARMED) != 0
|
convenient function for returning an arbitrary MAVLink
field with a default
|
def field(self, type, field, default=None):
'''convenient function for returning an arbitrary MAVLink
field with a default'''
if not type in self.messages:
return default
return getattr(self.messages[type], field, default)
|
setup for MAVLink2 signing
|
def setup_signing(self, secret_key, sign_outgoing=True, allow_unsigned_callback=None, initial_timestamp=None, link_id=None):
'''setup for MAVLink2 signing'''
self.mav.signing.secret_key = secret_key
self.mav.signing.sign_outgoing = sign_outgoing
self.mav.signing.allow_unsigned_callback = allow_unsigned_callback
if link_id is None:
# auto-increment the link_id for each link
global global_link_id
link_id = global_link_id
global_link_id = min(global_link_id + 1, 255)
self.mav.signing.link_id = link_id
if initial_timestamp is None:
# timestamp is time since 1/1/2015
epoch_offset = 1420070400
now = max(time.time(), epoch_offset)
initial_timestamp = now - epoch_offset
initial_timestamp = int(initial_timestamp * 100 * 1000)
# initial_timestamp is in 10usec units
self.mav.signing.timestamp = initial_timestamp
|
disable MAVLink2 signing
|
def disable_signing(self):
'''disable MAVLink2 signing'''
self.mav.signing.secret_key = None
self.mav.signing.sign_outgoing = False
self.mav.signing.allow_unsigned_callback = None
self.mav.signing.link_id = 0
self.mav.signing.timestamp = 0
|
enable/disable RTS/CTS if applicable
|
def set_rtscts(self, enable):
'''enable/disable RTS/CTS if applicable'''
try:
self.port.setRtsCts(enable)
except Exception:
self.port.rtscts = enable
self.rtscts = enable
|
set baudrate
|
def set_baudrate(self, baudrate):
'''set baudrate'''
try:
self.port.setBaudrate(baudrate)
except Exception:
# for pySerial 3.0, which doesn't have setBaudrate()
self.port.baudrate = baudrate
|
scan forward looking in a tlog for a timestamp in a reasonable range
|
def scan_timestamp(self, tbuf):
'''scan forward looking in a tlog for a timestamp in a reasonable range'''
while True:
(tusec,) = struct.unpack('>Q', tbuf)
t = tusec * 1.0e-6
if abs(t - self._last_timestamp) <= 3*24*60*60:
break
c = self.f.read(1)
if len(c) != 1:
break
tbuf = tbuf[1:] + c
return t
|
read timestamp if needed
|
def pre_message(self):
'''read timestamp if needed'''
# read the timestamp
if self.filesize != 0:
self.percent = (100.0 * self.f.tell()) / self.filesize
if self.notimestamps:
return
if self.planner_format:
tbuf = self.f.read(21)
if len(tbuf) != 21 or tbuf[0] != '-' or tbuf[20] != ':':
raise RuntimeError('bad planner timestamp %s' % tbuf)
hnsec = self._two64 + float(tbuf[0:20])
t = hnsec * 1.0e-7 # convert to seconds
t -= 719163 * 24 * 60 * 60 # convert to 1970 base
self._link = 0
else:
tbuf = self.f.read(8)
if len(tbuf) != 8:
return
(tusec,) = struct.unpack('>Q', tbuf)
t = tusec * 1.0e-6
if (self._last_timestamp is not None and
self._last_message.get_type() == "BAD_DATA" and
abs(t - self._last_timestamp) > 3*24*60*60):
t = self.scan_timestamp(tbuf)
self._link = tusec & 0x3
self._timestamp = t
|
message receive routine
|
def recv_msg(self):
'''message receive routine'''
if self._index >= self._count:
return None
m = self._msgs[self._index]
self._index += 1
self.percent = (100.0 * self._index) / self._count
self.messages[m.get_type()] = m
return m
|
add timestamp to message
|
def post_message(self, msg):
'''add timestamp to message'''
# read the timestamp
super(mavlogfile, self).post_message(msg)
if self.planner_format:
self.f.read(1) # trailing newline
self.timestamp = msg._timestamp
self._last_message = msg
if msg.get_type() != "BAD_DATA":
self._last_timestamp = msg._timestamp
msg._link = self._link
|
return True if we should trigger now
|
def trigger(self):
'''return True if we should trigger now'''
tnow = time.time()
if tnow < self.last_time:
print("Warning, time moved backwards. Restarting timer.")
self.last_time = tnow
if self.last_time + (1.0/self.frequency) <= tnow:
self.last_time = tnow
return True
return False
|
add in some more bytes
|
def accumulate(self, buf):
'''add in some more bytes'''
bytes = array.array('B')
if isinstance(buf, array.array):
bytes.extend(buf)
else:
bytes.fromstring(buf)
accum = self.crc
for b in bytes:
tmp = b ^ (accum & 0xff)
tmp = (tmp ^ (tmp<<4)) & 0xFF
accum = (accum>>8) ^ (tmp<<8) ^ (tmp<<3) ^ (tmp>>4)
accum = accum & 0xFFFF
self.crc = accum
|
write some bytes
|
def write(self, b):
'''write some bytes'''
from . import mavutil
self.debug("sending '%s' (0x%02x) of len %u\n" % (b, ord(b[0]), len(b)), 2)
while len(b) > 0:
n = len(b)
if n > 70:
n = 70
buf = [ord(x) for x in b[:n]]
buf.extend([0]*(70-len(buf)))
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |
mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,
0,
0,
n,
buf)
b = b[n:]
|
read some bytes into self.buf
|
def _recv(self):
'''read some bytes into self.buf'''
from . import mavutil
start_time = time.time()
while time.time() < start_time + self.timeout:
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
type='SERIAL_CONTROL', blocking=False, timeout=0)
if m is not None and m.count != 0:
break
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE |
mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND,
0,
0,
0, [0]*70)
m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0',
type='SERIAL_CONTROL', blocking=True, timeout=0.01)
if m is not None and m.count != 0:
break
if m is not None:
if self._debug > 2:
print(m)
data = m.data[:m.count]
self.buf += ''.join(str(chr(x)) for x in data)
|
read some bytes
|
def read(self, n):
'''read some bytes'''
if len(self.buf) == 0:
self._recv()
if len(self.buf) > 0:
if n > len(self.buf):
n = len(self.buf)
ret = self.buf[:n]
self.buf = self.buf[n:]
if self._debug >= 2:
for b in ret:
self.debug("read 0x%x" % ord(b), 2)
return ret
return ''
|
flush any pending input
|
def flushInput(self):
'''flush any pending input'''
self.buf = ''
saved_timeout = self.timeout
self.timeout = 0.5
self._recv()
self.timeout = saved_timeout
self.buf = ''
self.debug("flushInput")
|
set baudrate
|
def setBaudrate(self, baudrate):
'''set baudrate'''
from . import mavutil
if self.baudrate == baudrate:
return
self.baudrate = baudrate
self.mav.mav.serial_control_send(self.port,
mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE,
0,
self.baudrate,
0, [0]*70)
self.flushInput()
self.debug("Changed baudrate %u" % self.baudrate)
|
handle an incoming mavlink packet
|
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'SERIAL_CONTROL':
data = m.data[:m.count]
if m.count > 0:
s = ''.join(str(chr(x)) for x in data)
if self.mpstate.system == 'Windows':
# strip nsh ansi codes
s = s.replace("\033[K","")
sys.stdout.write(s)
self.last_packet = time.time()
|
stop nsh input
|
def stop(self):
'''stop nsh input'''
self.mpstate.rl.set_prompt(self.status.flightmode + "> ")
self.mpstate.functions.input_handler = None
self.started = False
# unlock the port
mav = self.master.mav
mav.serial_control_send(self.serial_settings.port,
0,
0, self.serial_settings.baudrate,
0, [0]*70)
|
send some bytes
|
def send(self, line):
'''send some bytes'''
line = line.strip()
if line == ".":
self.stop()
return
mav = self.master.mav
if line != '+++':
line += "\r\n"
buf = [ord(x) for x in line]
buf.extend([0]*(70-len(buf)))
flags = mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_MULTI
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
mav.serial_control_send(self.serial_settings.port,
flags,
0, self.serial_settings.baudrate,
len(line), buf)
|
handle mavlink packets
|
def idle_task(self):
'''handle mavlink packets'''
if not self.started:
return
now = time.time()
if now - self.last_packet < 1:
timeout = 0.05
else:
timeout = 0.2
if now - self.last_check > timeout:
self.last_check = now
mav = self.master.mav
flags = mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_MULTI
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
mav.serial_control_send(self.serial_settings.port,
flags,
0, self.serial_settings.baudrate,
0, [0]*70)
|
nsh shell commands
|
def cmd_nsh(self, args):
'''nsh shell commands'''
usage = "Usage: nsh <start|stop|set>"
if len(args) < 1:
print(usage)
return
if args[0] == "start":
self.mpstate.functions.input_handler = self.send
self.started = True
self.mpstate.rl.set_prompt("")
elif args[0] == "stop":
self.stop()
elif args[0] == "set":
self.serial_settings.command(args[1:])
else:
print(usage)
|
handle an incoming mavlink packet
|
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
mtype = m.get_type()
if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']:
if self.wp_op is None:
self.console.error("No waypoint load started")
else:
self.wploader.clear()
self.wploader.expected_count = m.count
self.console.writeln("Requesting %u waypoints t=%s now=%s" % (m.count,
time.asctime(time.localtime(m._timestamp)),
time.asctime()))
self.master.waypoint_request_send(0)
elif mtype in ['WAYPOINT', 'MISSION_ITEM'] and self.wp_op != None:
if m.seq > self.wploader.count():
self.console.writeln("Unexpected waypoint number %u - expected %u" % (m.seq, self.wploader.count()))
elif m.seq < self.wploader.count():
# a duplicate
pass
else:
self.wploader.add(m)
if m.seq+1 < self.wploader.expected_count:
self.master.waypoint_request_send(m.seq+1)
else:
if self.wp_op == 'list':
for i in range(self.wploader.count()):
w = self.wploader.wp(i)
print("%u %u %.10f %.10f %f p1=%.1f p2=%.1f p3=%.1f p4=%.1f cur=%u auto=%u" % (
w.command, w.frame, w.x, w.y, w.z,
w.param1, w.param2, w.param3, w.param4,
w.current, w.autocontinue))
if self.logdir != None:
waytxt = os.path.join(self.logdir, 'way.txt')
self.save_waypoints(waytxt)
print("Saved waypoints to %s" % waytxt)
elif self.wp_op == "save":
self.save_waypoints(self.wp_save_filename)
self.wp_op = None
elif mtype in ["WAYPOINT_REQUEST", "MISSION_REQUEST"]:
self.process_waypoint_request(m, self.master)
elif mtype in ["WAYPOINT_CURRENT", "MISSION_CURRENT"]:
if m.seq != self.last_waypoint:
self.last_waypoint = m.seq
if self.settings.wpupdates:
self.say("waypoint %u" % m.seq,priority='message')
|
process a waypoint request from the master
|
def process_waypoint_request(self, m, master):
'''process a waypoint request from the master'''
if (not self.loading_waypoints or
time.time() > self.loading_waypoint_lasttime + 10.0):
self.loading_waypoints = False
self.console.error("not loading waypoints")
return
if m.seq >= self.wploader.count():
self.console.error("Request for bad waypoint %u (max %u)" % (m.seq, self.wploader.count()))
return
wp = self.wploader.wp(m.seq)
wp.target_system = self.target_system
wp.target_component = self.target_component
self.master.mav.send(self.wploader.wp(m.seq))
self.loading_waypoint_lasttime = time.time()
self.console.writeln("Sent waypoint %u : %s" % (m.seq, self.wploader.wp(m.seq)))
if m.seq == self.wploader.count() - 1:
self.loading_waypoints = False
self.console.writeln("Sent all %u waypoints" % self.wploader.count())
|
handle missing waypoints
|
def idle_task(self):
'''handle missing waypoints'''
if self.wp_period.trigger():
# cope with packet loss fetching mission
if self.master is not None and self.master.time_since('MISSION_ITEM') >= 2 and self.wploader.count() < getattr(self.wploader,'expected_count',0):
seq = self.wploader.count()
print("re-requesting WP %u" % seq)
self.master.waypoint_request_send(seq)
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)
|
send all waypoints to vehicle
|
def send_all_waypoints(self):
'''send all waypoints to vehicle'''
self.master.waypoint_clear_all_send()
if self.wploader.count() == 0:
return
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.waypoint_count_send(self.wploader.count())
|
load waypoints from a file
|
def load_waypoints(self, filename):
'''load waypoints from a file'''
self.wploader.target_system = self.target_system
self.wploader.target_component = self.target_component
try:
self.wploader.load(filename)
except Exception as msg:
print("Unable to load %s - %s" % (filename, msg))
return
print("Loaded %u waypoints from %s" % (self.wploader.count(), filename))
self.send_all_waypoints()
|
update waypoints from a file
|
def update_waypoints(self, filename, wpnum):
'''update waypoints from a file'''
self.wploader.target_system = self.target_system
self.wploader.target_component = self.target_component
try:
self.wploader.load(filename)
except Exception as msg:
print("Unable to load %s - %s" % (filename, msg))
return
if self.wploader.count() == 0:
print("No waypoints found in %s" % filename)
return
if wpnum == -1:
print("Loaded %u updated waypoints from %s" % (self.wploader.count(), filename))
elif wpnum >= self.wploader.count():
print("Invalid waypoint number %u" % wpnum)
return
else:
print("Loaded updated waypoint %u from %s" % (wpnum, filename))
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
if wpnum == -1:
start = 0
end = self.wploader.count()-1
else:
start = wpnum
end = wpnum
self.master.mav.mission_write_partial_list_send(self.target_system,
self.target_component,
start, end)
|
default frame for waypoints
|
def get_default_frame(self):
'''default frame for waypoints'''
if self.settings.terrainalt == 'Auto':
if self.get_mav_param('TERRAIN_FOLLOW',0) == 1:
return mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT
return mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT
if self.settings.terrainalt == 'True':
return mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT
return mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT
|
callback from drawing waypoints
|
def wp_draw_callback(self, points):
'''callback from drawing waypoints'''
if len(points) < 3:
return
from MAVProxy.modules.lib import mp_util
home = self.wploader.wp(0)
self.wploader.clear()
self.wploader.target_system = self.target_system
self.wploader.target_component = self.target_component
self.wploader.add(home)
if self.get_default_frame() == mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT:
use_terrain = True
else:
use_terrain = False
for p in points:
self.wploader.add_latlonalt(p[0], p[1], self.settings.wpalt, terrain_alt=use_terrain)
self.send_all_waypoints()
|
close the loop on a mission
|
def wp_loop(self):
'''close the loop on a mission'''
loader = self.wploader
if loader.count() < 2:
print("Not enough waypoints (%u)" % loader.count())
return
wp = loader.wp(loader.count()-2)
if wp.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
print("Mission is already looped")
return
wp = mavutil.mavlink.MAVLink_mission_item_message(0, 0, 0, 0, mavutil.mavlink.MAV_CMD_DO_JUMP,
0, 1, 1, -1, 0, 0, 0, 0, 0)
loader.add(wp)
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.waypoint_count_send(self.wploader.count())
print("Closed loop on mission")
|
set home location from last map click
|
def set_home_location(self):
'''set home location from last map click'''
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
lat = float(latlon[0])
lon = float(latlon[1])
if self.wploader.count() == 0:
self.wploader.add_latlonalt(lat, lon, 0)
w = self.wploader.wp(0)
w.x = lat
w.y = lon
self.wploader.set(w, 0)
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.mav.mission_write_partial_list_send(self.target_system,
self.target_component,
0, 0)
|
handle wp move
|
def cmd_wp_move(self, args):
'''handle wp move'''
if len(args) != 1:
print("usage: wp move WPNUM")
return
idx = int(args[0])
if idx < 1 or idx > self.wploader.count():
print("Invalid wp 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
wp = self.wploader.wp(idx)
# setup for undo
self.undo_wp = copy.copy(wp)
self.undo_wp_idx = idx
self.undo_type = "move"
(lat, lon) = latlon
if getattr(self.console, 'ElevationMap', None) is not None and wp.frame != mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT:
alt1 = self.console.ElevationMap.GetElevation(lat, lon)
alt2 = self.console.ElevationMap.GetElevation(wp.x, wp.y)
if alt1 is not None and alt2 is not None:
wp.z += alt1 - alt2
wp.x = lat
wp.y = lon
wp.target_system = self.target_system
wp.target_component = self.target_component
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.mav.mission_write_partial_list_send(self.target_system,
self.target_component,
idx, idx)
self.wploader.set(wp, idx)
print("Moved WP %u to %f, %f at %.1fm" % (idx, lat, lon, wp.z))
|
handle wp move of multiple waypoints
|
def cmd_wp_movemulti(self, args):
'''handle wp move of multiple waypoints'''
if len(args) < 3:
print("usage: wp movemulti WPNUM WPSTART WPEND <rotation>")
return
idx = int(args[0])
if idx < 1 or idx > self.wploader.count():
print("Invalid wp number %u" % idx)
return
wpstart = int(args[1])
if wpstart < 1 or wpstart > self.wploader.count():
print("Invalid wp number %u" % wpstart)
return
wpend = int(args[2])
if wpend < 1 or wpend > self.wploader.count():
print("Invalid wp number %u" % wpend)
return
if idx < wpstart or idx > wpend:
print("WPNUM must be between WPSTART and WPEND")
return
# optional rotation about center point
if len(args) > 3:
rotation = float(args[3])
else:
rotation = 0
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
wp = self.wploader.wp(idx)
if not self.wploader.is_location_command(wp.command):
print("WP must be a location command")
return
(lat, lon) = latlon
distance = mp_util.gps_distance(wp.x, wp.y, lat, lon)
bearing = mp_util.gps_bearing(wp.x, wp.y, lat, lon)
for wpnum in range(wpstart, wpend+1):
wp = self.wploader.wp(wpnum)
if not self.wploader.is_location_command(wp.command):
continue
(newlat, newlon) = mp_util.gps_newpos(wp.x, wp.y, bearing, distance)
if wpnum != idx and rotation != 0:
# add in rotation
d2 = mp_util.gps_distance(lat, lon, newlat, newlon)
b2 = mp_util.gps_bearing(lat, lon, newlat, newlon)
(newlat, newlon) = mp_util.gps_newpos(lat, lon, b2+rotation, d2)
if getattr(self.console, 'ElevationMap', None) is not None and wp.frame != mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT:
alt1 = self.console.ElevationMap.GetElevation(newlat, newlon)
alt2 = self.console.ElevationMap.GetElevation(wp.x, wp.y)
if alt1 is not None and alt2 is not None:
wp.z += alt1 - alt2
wp.x = newlat
wp.y = newlon
wp.target_system = self.target_system
wp.target_component = self.target_component
self.wploader.set(wp, wpnum)
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.mav.mission_write_partial_list_send(self.target_system,
self.target_component,
wpstart, wpend+1)
print("Moved WPs %u:%u to %f, %f rotation=%.1f" % (wpstart, wpend, lat, lon, rotation))
|
handle wp parameter change
|
def cmd_wp_param(self, args):
'''handle wp parameter change'''
if len(args) < 2:
print("usage: wp param WPNUM PNUM <VALUE>")
return
idx = int(args[0])
if idx < 1 or idx > self.wploader.count():
print("Invalid wp number %u" % idx)
return
wp = self.wploader.wp(idx)
param = [wp.param1, wp.param2, wp.param3, wp.param4]
pnum = int(args[1])
if pnum < 1 or pnum > 4:
print("Invalid param number %u" % pnum)
return
if len(args) == 2:
print("Param %u: %f" % (pnum, param[pnum-1]))
return
param[pnum-1] = float(args[2])
wp.param1 = param[0]
wp.param2 = param[1]
wp.param3 = param[2]
wp.param4 = param[3]
wp.target_system = self.target_system
wp.target_component = self.target_component
self.loading_waypoints = True
self.loading_waypoint_lasttime = time.time()
self.master.mav.mission_write_partial_list_send(self.target_system,
self.target_component,
idx, idx)
self.wploader.set(wp, idx)
print("Set param %u for %u to %f" % (pnum, idx, param[pnum-1]))
|
waypoint commands
|
def cmd_wp(self, args):
'''waypoint commands'''
usage = "usage: wp <list|load|update|save|set|clear|loop|remove|move>"
if len(args) < 1:
print(usage)
return
if args[0] == "load":
if len(args) != 2:
print("usage: wp load <filename>")
return
self.load_waypoints(args[1])
elif args[0] == "update":
if len(args) < 2:
print("usage: wp update <filename> <wpnum>")
return
if len(args) == 3:
wpnum = int(args[2])
else:
wpnum = -1
self.update_waypoints(args[1], wpnum)
elif args[0] == "list":
self.wp_op = "list"
self.master.waypoint_request_list_send()
elif args[0] == "save":
if len(args) != 2:
print("usage: wp save <filename>")
return
self.wp_save_filename = args[1]
self.wp_op = "save"
self.master.waypoint_request_list_send()
elif args[0] == "savelocal":
if len(args) != 2:
print("usage: wp savelocal <filename>")
return
self.wploader.save(args[1])
elif args[0] == "show":
if len(args) != 2:
print("usage: wp show <filename>")
return
self.wploader.load(args[1])
elif args[0] == "move":
self.cmd_wp_move(args[1:])
elif args[0] == "movemulti":
self.cmd_wp_movemulti(args[1:])
elif args[0] == "param":
self.cmd_wp_param(args[1:])
elif args[0] == "remove":
self.cmd_wp_remove(args[1:])
elif args[0] == "undo":
self.cmd_wp_undo()
elif args[0] == "set":
if len(args) != 2:
print("usage: wp set <wpindex>")
return
self.master.waypoint_set_current_send(int(args[1]))
elif args[0] == "clear":
self.master.waypoint_clear_all_send()
self.wploader.clear()
elif args[0] == "draw":
if not 'draw_lines' in self.mpstate.map_functions:
print("No map drawing available")
return
if self.wploader.count() == 0:
print("Need home location - refresh waypoints")
return
if len(args) > 1:
self.settings.wpalt = int(args[1])
self.mpstate.map_functions['draw_lines'](self.wp_draw_callback)
print("Drawing waypoints on map at altitude %d" % self.settings.wpalt)
elif args[0] == "sethome":
self.set_home_location()
elif args[0] == "loop":
self.wp_loop()
else:
print(usage)
|
Translates from Distance Image format to RGB. Inf values are represented by NaN, when converting to RGB, NaN passed to 0
@param float_img_buff: ROS Image to translate
@type img: ros image
@return a Opencv RGB image
|
def depthToRGB8(float_img_buff, encoding):
'''
Translates from Distance Image format to RGB. Inf values are represented by NaN, when converting to RGB, NaN passed to 0
@param float_img_buff: ROS Image to translate
@type img: ros image
@return a Opencv RGB image
'''
gray_image = None
if (encoding[-3:-2]== "U"):
gray_image = float_img_buff
else:
float_img = np.zeros((float_img_buff.shape[0], float_img_buff.shape[1], 1), dtype = "float32")
float_img.data = float_img_buff.data
gray_image=cv2.convertScaleAbs(float_img, alpha=255/MAXRANGE)
cv_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2RGB)
return cv_image
|
Callback function to receive and save Images.
@param img: ROS Image received
@type img: sensor_msgs.msg.Image
|
def __callback (self, img):
'''
Callback function to receive and save Images.
@param img: ROS Image received
@type img: sensor_msgs.msg.Image
'''
image = imageMsg2Image(img, self.bridge)
self.lock.acquire()
self.data = image
self.lock.release()
|
Starts (Subscribes) the client.
|
def start (self):
'''
Starts (Subscribes) the client.
'''
self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback)
|
Returns last Image.
@return last JdeRobotTypes Image saved
|
def getImage(self):
'''
Returns last Image.
@return last JdeRobotTypes Image saved
'''
self.lock.acquire()
image = self.data
self.lock.release()
return image
|
a noise vector
|
def noise():
'''a noise vector'''
from random import gauss
v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
v.normalize()
return v * args.noise
|
find mag offsets by applying Bills "offsets revisited" algorithm
on the data
This is an implementation of the algorithm from:
http://gentlenav.googlecode.com/files/MagnetometerOffsetNullingRevisited.pdf
|
def find_offsets(data, ofs):
'''find mag offsets by applying Bills "offsets revisited" algorithm
on the data
This is an implementation of the algorithm from:
http://gentlenav.googlecode.com/files/MagnetometerOffsetNullingRevisited.pdf
'''
# a limit on the maximum change in each step
max_change = args.max_change
# the gain factor for the algorithm
gain = args.gain
data2 = []
for d in data:
d = d.copy() + noise()
d.x = float(int(d.x + 0.5))
d.y = float(int(d.y + 0.5))
d.z = float(int(d.z + 0.5))
data2.append(d)
data = data2
history_idx = 0
mag_history = data[0:args.history]
for i in range(args.history, len(data)):
B1 = mag_history[history_idx] + ofs
B2 = data[i] + ofs
diff = B2 - B1
diff_length = diff.length()
if diff_length <= args.min_diff:
# the mag vector hasn't changed enough - we don't get any
# information from this
history_idx = (history_idx+1) % args.history
continue
mag_history[history_idx] = data[i]
history_idx = (history_idx+1) % args.history
# equation 6 of Bills paper
delta = diff * (gain * (B2.length() - B1.length()) / diff_length)
# limit the change from any one reading. This is to prevent
# single crazy readings from throwing off the offsets for a long
# time
delta_length = delta.length()
if max_change != 0 and delta_length > max_change:
delta *= max_change / delta_length
# set the new offsets
ofs = ofs - delta
if args.verbose:
print(ofs)
return ofs
|
find best magnetometer offset fit to a log file
|
def magfit(logfile):
'''find best magnetometer offset fit to a log file'''
print("Processing log %s" % filename)
# open the log file
mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps)
data = []
mag = None
offsets = Vector3(0,0,0)
# now gather all the data
while True:
# get the next MAVLink message in the log
m = mlog.recv_match(condition=args.condition)
if m is None:
break
if m.get_type() == "SENSOR_OFFSETS":
# update offsets that were used during this flight
offsets = Vector3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z)
if m.get_type() == "RAW_IMU" and offsets != None:
# extract one mag vector, removing the offsets that were
# used during that flight to get the raw sensor values
mag = Vector3(m.xmag, m.ymag, m.zmag) - offsets
data.append(mag)
print("Extracted %u data points" % len(data))
print("Current offsets: %s" % offsets)
# run the fitting algorithm
ofs = offsets
ofs = Vector3(0,0,0)
for r in range(args.repeat):
ofs = find_offsets(data, ofs)
print('Loop %u offsets %s' % (r, ofs))
sys.stdout.flush()
print("New offsets: %s" % ofs)
|
child process - this holds all the GUI elements
|
def child_task(self):
'''child process - this holds all the GUI elements'''
mp_util.child_close_fds()
from wx_loader import wx
state = self
self.app = wx.App(False)
self.app.frame = MPImageFrame(state=self)
self.app.frame.Show()
self.app.MainLoop()
|
set the currently displayed image
|
def set_image(self, img, bgr=False):
'''set the currently displayed image'''
if not self.is_alive():
return
if bgr:
img = cv.CloneImage(img)
cv.CvtColor(img, img, cv.CV_BGR2RGB)
self.in_queue.put(MPImageData(img))
|
set a MPTopMenu on the frame
|
def set_menu(self, menu):
'''set a MPTopMenu on the frame'''
self.menu = menu
self.in_queue.put(MPImageMenu(menu))
|
set a popup menu on the frame
|
def set_popup_menu(self, menu):
'''set a popup menu on the frame'''
self.popup_menu = menu
self.in_queue.put(MPImagePopupMenu(menu))
|
check for events a list of events
|
def events(self):
'''check for events a list of events'''
ret = []
while self.out_queue.qsize():
ret.append(self.out_queue.get())
return ret
|
given a point in window coordinates, calculate image coordinates
|
def image_coordinates(self, point):
'''given a point in window coordinates, calculate image coordinates'''
# the dragpos is the top left position in image coordinates
ret = wx.Point(int(self.dragpos.x + point.x/self.zoom),
int(self.dragpos.y + point.y/self.zoom))
return ret
|
redraw the image with current settings
|
def redraw(self):
'''redraw the image with current settings'''
state = self.state
if self.img is None:
self.mainSizer.Fit(self)
self.Refresh()
state.frame.Refresh()
self.SetFocus()
return
# get the current size of the containing window frame
size = self.frame.GetSize()
(width, height) = (self.img.GetWidth(), self.img.GetHeight())
rect = wx.Rect(self.dragpos.x, self.dragpos.y, int(size.x/self.zoom), int(size.y/self.zoom))
#print("redraw", self.zoom, self.dragpos, size, rect);
if rect.x > width-1:
rect.x = width-1
if rect.y > height-1:
rect.y = height-1
if rect.width > width - rect.x:
rect.width = width - rect.x
if rect.height > height - rect.y:
rect.height = height - rect.y
scaled_image = self.img.Copy()
scaled_image = scaled_image.GetSubImage(rect);
scaled_image = scaled_image.Rescale(int(rect.width*self.zoom), int(rect.height*self.zoom))
if state.brightness != 1.0:
try:
from PIL import Image
pimg = mp_util.wxToPIL(scaled_image)
pimg = Image.eval(pimg, lambda x: int(x * state.brightness))
scaled_image = mp_util.PILTowx(pimg)
except Exception:
if not self.done_PIL_warning:
print("Please install PIL for brightness control")
self.done_PIL_warning = True
# ignore lack of PIL library
pass
self.imagePanel.set_image(scaled_image)
self.need_redraw = False
self.mainSizer.Fit(self)
self.Refresh()
state.frame.Refresh()
self.SetFocus()
'''
from guppy import hpy
h = hpy()
print h.heap()
'''
|
the redraw timer ensures we show new map tiles as they
are downloaded
|
def on_redraw_timer(self, event):
'''the redraw timer ensures we show new map tiles as they
are downloaded'''
state = self.state
while state.in_queue.qsize():
obj = state.in_queue.get()
if isinstance(obj, MPImageData):
img = wx.EmptyImage(obj.width, obj.height)
img.SetData(obj.data)
self.img = img
self.need_redraw = True
if state.auto_size:
client_area = state.frame.GetClientSize()
total_area = state.frame.GetSize()
bx = max(total_area.x - client_area.x,0)
by = max(total_area.y - client_area.y,0)
state.frame.SetSize(wx.Size(obj.width+bx, obj.height+by))
if isinstance(obj, MPImageTitle):
state.frame.SetTitle(obj.title)
if isinstance(obj, MPImageMenu):
self.set_menu(obj.menu)
if isinstance(obj, MPImagePopupMenu):
self.set_popup_menu(obj.menu)
if isinstance(obj, MPImageBrightness):
state.brightness = obj.brightness
self.need_redraw = True
if isinstance(obj, MPImageFullSize):
self.full_size()
if isinstance(obj, MPImageFitToWindow):
self.fit_to_window()
if self.need_redraw:
self.redraw()
|
handle window size changes
|
def on_size(self, event):
'''handle window size changes'''
state = self.state
self.need_redraw = True
if state.report_size_changes:
# tell owner the new size
size = self.frame.GetSize()
if size != self.last_size:
self.last_size = size
state.out_queue.put(MPImageNewSize(size))
|
limit dragpos to sane values
|
def limit_dragpos(self):
'''limit dragpos to sane values'''
if self.dragpos.x < 0:
self.dragpos.x = 0
if self.dragpos.y < 0:
self.dragpos.y = 0
if self.img is None:
return
if self.dragpos.x >= self.img.GetWidth():
self.dragpos.x = self.img.GetWidth()-1
if self.dragpos.y >= self.img.GetHeight():
self.dragpos.y = self.img.GetHeight()-1
|
handle mouse wheel zoom changes
|
def on_mouse_wheel(self, event):
'''handle mouse wheel zoom changes'''
state = self.state
if not state.can_zoom:
return
mousepos = self.image_coordinates(event.GetPosition())
rotation = event.GetWheelRotation() / event.GetWheelDelta()
oldzoom = self.zoom
if rotation > 0:
self.zoom /= 1.0/(1.1 * rotation)
elif rotation < 0:
self.zoom /= 1.1 * (-rotation)
if self.zoom > 10:
self.zoom = 10
elif self.zoom < 0.1:
self.zoom = 0.1
if oldzoom < 1 and self.zoom > 1:
self.zoom = 1
if oldzoom > 1 and self.zoom < 1:
self.zoom = 1
self.need_redraw = True
new = self.image_coordinates(event.GetPosition())
# adjust dragpos so the zoom doesn't change what pixel is under the mouse
self.dragpos = wx.Point(self.dragpos.x - (new.x-mousepos.x), self.dragpos.y - (new.y-mousepos.y))
self.limit_dragpos()
|
handle mouse drags
|
def on_drag_event(self, event):
'''handle mouse drags'''
state = self.state
if not state.can_drag:
return
newpos = self.image_coordinates(event.GetPosition())
dx = -(newpos.x - self.mouse_down.x)
dy = -(newpos.y - self.mouse_down.y)
self.dragpos = wx.Point(self.dragpos.x+dx,self.dragpos.y+dy)
self.limit_dragpos()
self.mouse_down = newpos
self.need_redraw = True
self.redraw()
|
show a popup menu
|
def show_popup_menu(self, pos):
'''show a popup menu'''
self.popup_pos = self.image_coordinates(pos)
self.frame.PopupMenu(self.wx_popup_menu, pos)
|
handle mouse events
|
def on_mouse_event(self, event):
'''handle mouse events'''
pos = event.GetPosition()
if event.RightDown() and self.popup_menu is not None:
self.show_popup_menu(pos)
return
if event.Leaving():
self.mouse_pos = None
else:
self.mouse_pos = pos
if event.LeftDown():
self.mouse_down = self.image_coordinates(pos)
if event.Dragging() and event.ButtonIsDown(wx.MOUSE_BTN_LEFT):
self.on_drag_event(event)
|
handle key events
|
def on_key_event(self, event):
'''handle key events'''
keycode = event.GetKeyCode()
if keycode == wx.WXK_HOME:
self.zoom = 1.0
self.dragpos = wx.Point(0, 0)
self.need_redraw = True
|
pass events to the parent
|
def on_event(self, event):
'''pass events to the parent'''
state = self.state
if isinstance(event, wx.MouseEvent):
self.on_mouse_event(event)
if isinstance(event, wx.KeyEvent):
self.on_key_event(event)
if (isinstance(event, wx.MouseEvent) and
not event.ButtonIsDown(wx.MOUSE_BTN_ANY) and
event.GetWheelRotation() == 0):
# don't flood the queue with mouse movement
return
evt = mp_util.object_container(event)
pt = self.image_coordinates(wx.Point(evt.X,evt.Y))
evt.X = pt.x
evt.Y = pt.y
state.out_queue.put(evt)
|
called on menu event
|
def on_menu(self, event):
'''called on menu event'''
state = self.state
if self.popup_menu is not None:
ret = self.popup_menu.find_selected(event)
if ret is not None:
ret.popup_pos = self.popup_pos
if ret.returnkey == 'fitWindow':
self.fit_to_window()
elif ret.returnkey == 'fullSize':
self.full_size()
else:
state.out_queue.put(ret)
return
if self.menu is not None:
ret = self.menu.find_selected(event)
if ret is not None:
state.out_queue.put(ret)
return
|
add a menu from the parent
|
def set_menu(self, menu):
'''add a menu from the parent'''
self.menu = menu
wx_menu = menu.wx_menu()
self.frame.SetMenuBar(wx_menu)
self.frame.Bind(wx.EVT_MENU, self.on_menu)
|
add a popup menu from the parent
|
def set_popup_menu(self, menu):
'''add a popup menu from the parent'''
self.popup_menu = menu
if menu is None:
self.wx_popup_menu = None
else:
self.wx_popup_menu = menu.wx_menu()
self.frame.Bind(wx.EVT_MENU, self.on_menu)
|
fit image to window
|
def fit_to_window(self):
'''fit image to window'''
state = self.state
self.dragpos = wx.Point(0, 0)
client_area = state.frame.GetClientSize()
self.zoom = min(float(client_area.x) / self.img.GetWidth(),
float(client_area.y) / self.img.GetHeight())
self.need_redraw = True
|
extract mavlink mission
|
def mavmission(logfile):
'''extract mavlink mission'''
mlog = mavutil.mavlink_connection(filename)
wp = mavwp.MAVWPLoader()
while True:
m = mlog.recv_match(type=['MISSION_ITEM','CMD','WAYPOINT'])
if m is None:
break
if m.get_type() == 'CMD':
m = mavutil.mavlink.MAVLink_mission_item_message(0,
0,
m.CNum,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
m.CId,
0, 1,
m.Prm1, m.Prm2, m.Prm3, m.Prm4,
m.Lat, m.Lng, m.Alt)
if m.current >= 2:
continue
while m.seq > wp.count():
print("Adding dummy WP %u" % wp.count())
wp.set(m, wp.count())
wp.set(m, m.seq)
wp.save(args.output)
print("Saved %u waypoints to %s" % (wp.count(), args.output))
|
show image at full size
|
def full_size(self):
'''show image at full size'''
self.dragpos = wx.Point(0, 0)
self.zoom = 1.0
self.need_redraw = True
|
calculate a 8-bit checksum of the key fields of a message, so we
can detect incompatible XML changes
|
def message_checksum(msg):
'''calculate a 8-bit checksum of the key fields of a message, so we
can detect incompatible XML changes'''
from .mavcrc import x25crc
crc = x25crc()
crc.accumulate_str(msg.name + ' ')
# in order to allow for extensions the crc does not include
# any field extensions
crc_end = msg.base_fields()
for i in range(crc_end):
f = msg.ordered_fields[i]
crc.accumulate_str(f.type + ' ')
crc.accumulate_str(f.name + ' ')
if f.array_length:
crc.accumulate([f.array_length])
return (crc.crc&0xFF) ^ (crc.crc>>8)
|
merge enums between XML files
|
def merge_enums(xml):
'''merge enums between XML files'''
emap = {}
for x in xml:
newenums = []
for enum in x.enum:
if enum.name in emap:
emapitem = emap[enum.name]
# check for possible conflicting auto-assigned values after merge
if (emapitem.start_value <= enum.highest_value and emapitem.highest_value >= enum.start_value):
for entry in emapitem.entry:
# correct the value if necessary, but only if it was auto-assigned to begin with
if entry.value <= enum.highest_value and entry.autovalue == True:
entry.value = enum.highest_value + 1
enum.highest_value = entry.value
# merge the entries
emapitem.entry.extend(enum.entry)
if not emapitem.description:
emapitem.description = enum.description
print("Merged enum %s" % enum.name)
else:
newenums.append(enum)
emap[enum.name] = enum
x.enum = newenums
for e in emap:
# sort by value
emap[e].entry = sorted(emap[e].entry,
key=operator.attrgetter('value'),
reverse=False)
# add a ENUM_END
emap[e].entry.append(MAVEnumEntry("%s_ENUM_END" % emap[e].name,
emap[e].entry[-1].value+1, end_marker=True))
|
check for duplicate message IDs
|
def check_duplicates(xml):
'''check for duplicate message IDs'''
merge_enums(xml)
msgmap = {}
enummap = {}
for x in xml:
for m in x.message:
key = m.id
if key in msgmap:
print("ERROR: Duplicate message id %u for %s (%s:%u) also used by %s" % (
m.id,
m.name,
x.filename, m.linenumber,
msgmap[key]))
return True
fieldset = set()
for f in m.fields:
if f.name in fieldset:
print("ERROR: Duplicate field %s in message %s (%s:%u)" % (
f.name, m.name,
x.filename, m.linenumber))
return True
fieldset.add(f.name)
msgmap[key] = '%s (%s:%u)' % (m.name, x.filename, m.linenumber)
for enum in x.enum:
for entry in enum.entry:
if entry.autovalue == True and "common.xml" not in entry.origin_file:
print("Note: An enum value was auto-generated: %s = %u" % (entry.name, entry.value))
s1 = "%s.%s" % (enum.name, entry.name)
s2 = "%s.%s" % (enum.name, entry.value)
if s1 in enummap or s2 in enummap:
print("ERROR: Duplicate enum %s:\n\t%s = %s @ %s:%u\n\t%s" % (
"names" if s1 in enummap else "values",
s1, entry.value, entry.origin_file, entry.origin_line,
enummap.get(s1) or enummap.get(s2)))
return True
enummap[s1] = enummap[s2] = "%s.%s = %s @ %s:%u" % (enum.name, entry.name, entry.value, entry.origin_file, entry.origin_line)
return False
|
count total number of msgs
|
def total_msgs(xml):
'''count total number of msgs'''
count = 0
for x in xml:
count += len(x.message)
return count
|
return number of non-extended fields
|
def base_fields(self):
'''return number of non-extended fields'''
if self.extensions_start is None:
return len(self.fields)
return len(self.fields[:self.extensions_start])
|
Calculate some interesting datapoints of the file
|
def PrintSummary(logfile):
'''Calculate some interesting datapoints of the file'''
# Open the log file
mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps, dialect=args.dialect)
autonomous_sections = 0 # How many different autonomous sections there are
autonomous = False # Whether the vehicle is currently autonomous at this point in the logfile
auto_time = 0.0 # The total time the vehicle was autonomous/guided (seconds)
start_time = None # The datetime of the first received message (seconds since epoch)
total_dist = 0.0 # The total ground distance travelled (meters)
last_gps_msg = None # The first GPS message received
first_gps_msg = None # The last GPS message received
true_time = None # Track the first timestamp found that corresponds to a UNIX timestamp
while True:
m = mlog.recv_match(condition=args.condition)
# If there's no match, it means we're done processing the log.
if m is None:
break
# Ignore any failed messages
if m.get_type() == 'BAD_DATA':
continue
# Keep track of the latest timestamp for various calculations
timestamp = getattr(m, '_timestamp', 0.0)
# Log the first message time
if start_time is None:
start_time = timestamp
# Log the first timestamp found that is a true timestamp. We first try
# to get the groundstation timestamp from the log directly. If that fails
# we try to find a message that outputs a Unix time-since-epoch.
if true_time is None:
if not args.notimestamps and timestamp >= 1230768000:
true_time = timestamp
elif 'time_unix_usec' in m.__dict__ and m.time_unix_usec >= 1230768000:
true_time = m.time_unix_usec * 1.0e-6
elif 'time_usec' in m.__dict__ and m.time_usec >= 1230768000:
true_time = m.time_usec * 1.0e-6
# Track the vehicle's speed and status
if m.get_type() == 'GPS_RAW_INT':
# Ignore GPS messages without a proper fix
if m.fix_type < 3 or m.lat == 0 or m.lon == 0:
continue
# Log the first GPS location found, being sure to skip GPS fixes
# that are bad (at lat/lon of 0,0)
if first_gps_msg is None:
first_gps_msg = m
# Track the distance travelled, being sure to skip GPS fixes
# that are bad (at lat/lon of 0,0)
if last_gps_msg is None or m.time_usec > last_gps_msg.time_usec or m.time_usec+30e6 < last_gps_msg.time_usec:
if last_gps_msg is not None:
total_dist += distance_two(last_gps_msg, m)
# Save this GPS message to do simple distance calculations with
last_gps_msg = m
elif m.get_type() == 'HEARTBEAT':
if m.type == mavutil.mavlink.MAV_TYPE_GCS:
continue
if (m.base_mode & mavutil.mavlink.MAV_MODE_FLAG_GUIDED_ENABLED or
m.base_mode & mavutil.mavlink.MAV_MODE_FLAG_AUTO_ENABLED) and autonomous == False:
autonomous = True
autonomous_sections += 1
start_auto_time = timestamp
elif (not m.base_mode & mavutil.mavlink.MAV_MODE_FLAG_GUIDED_ENABLED and
not m.base_mode & mavutil.mavlink.MAV_MODE_FLAG_AUTO_ENABLED) and autonomous == True:
autonomous = False
auto_time += timestamp - start_auto_time
# If there were no messages processed, say so
if start_time is None:
print("ERROR: No messages found.")
return
# If the vehicle ends in autonomous mode, make sure we log the total time
if autonomous == True:
auto_time += timestamp - start_auto_time
# Compute the total logtime, checking that timestamps are 2009 or newer for validity
# (MAVLink didn't exist until 2009)
if true_time:
start_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(true_time))
print("Log started at about {}".format(start_time_str))
else:
print("Warning: No absolute timestamp found in datastream. No starting time can be provided for this log.")
# Print location data
if last_gps_msg is not None:
first_gps_position = (first_gps_msg.lat / 1e7, first_gps_msg.lon / 1e7)
last_gps_position = (last_gps_msg.lat / 1e7, last_gps_msg.lon / 1e7)
print("Travelled from ({0[0]}, {0[1]}) to ({1[0]}, {1[1]})".format(first_gps_position, last_gps_position))
print("Total distance : {:0.2f}m".format(total_dist))
else:
print("Warning: No GPS data found, can't give position summary.")
# Print out the rest of the results.
total_time = timestamp - start_time
print("Total time (mm:ss): {:3.0f}:{:02.0f}".format(total_time / 60, total_time % 60))
# The autonomous time should be good, as a steady HEARTBEAT is required for MAVLink operation
print("Autonomous sections: {}".format(autonomous_sections))
if autonomous_sections > 0:
print("Autonomous time (mm:ss): {:3.0f}:{:02.0f}".format(auto_time / 60, auto_time % 60))
totals.time += total_time
totals.distance += total_dist
totals.flights += 1
|
control behaviour of the module
|
def cmd_dataflash_logger(self, args):
'''control behaviour of the module'''
if len(args) == 0:
print (self.usage())
elif args[0] == "status":
print (self.status())
elif args[0] == "stop":
self.new_log_started = False
self.stopped = True
elif args[0] == "start":
self.stopped = False
elif args[0] == "set":
self.log_settings.command(args[1:])
else:
print (self.usage())
|
returns directory path to store DF logs in. May be relative
|
def _dataflash_dir(self, mpstate):
'''returns directory path to store DF logs in. May be relative'''
if mpstate.settings.state_basedir is None:
ret = 'dataflash'
else:
ret = os.path.join(mpstate.settings.state_basedir,'dataflash')
try:
os.makedirs(ret)
except OSError as e:
if e.errno != errno.EEXIST:
print("DFLogger: OSError making (%s): %s" % (ret, str(e)))
except Exception as e:
print("DFLogger: Unknown exception making (%s): %s" % (ret, str(e)))
return ret
|
returns a filepath to a log which does not currently exist and is suitable for DF logging
|
def new_log_filepath(self):
'''returns a filepath to a log which does not currently exist and is suitable for DF logging'''
lastlog_filename = os.path.join(self.dataflash_dir,'LASTLOG.TXT')
if os.path.exists(lastlog_filename) and os.stat(lastlog_filename).st_size != 0:
fh = open(lastlog_filename,'rb')
log_cnt = int(fh.read()) + 1
fh.close()
else:
log_cnt = 1
self.lastlog_file = open(lastlog_filename,'w+b')
self.lastlog_file.write(log_cnt.__str__())
self.lastlog_file.close()
return os.path.join(self.dataflash_dir, '%u.BIN' % (log_cnt,));
|
open a new dataflash log, reset state
|
def start_new_log(self):
'''open a new dataflash log, reset state'''
filename = self.new_log_filepath()
self.block_cnt = 0
self.logfile = open(filename, 'w+b')
print("DFLogger: logging started (%s)" % (filename))
self.prev_cnt = 0
self.download = 0
self.prev_download = 0
self.last_idle_status_printed_time = time.time()
self.last_status_time = time.time()
self.missing_blocks = {}
self.acking_blocks = {}
self.blocks_to_ack_and_nack = []
self.missing_found = 0
self.abandoned = 0
|
returns information about module
|
def status(self):
'''returns information about module'''
transfered = self.download - self.prev_download
now = time.time()
interval = now - self.last_status_time
self.last_status_time = now
return("DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s Block:%(block_cnt)d Missing:%(missing)d Fixed:%(fixed)d Abandoned:%(abandoned)d" %
{"interval": interval,
"rate": transfered/(interval*1000),
"block_cnt": self.block_cnt,
"missing": len(self.missing_blocks),
"fixed": self.missing_found,
"abandoned": self.abandoned,
"state": "Inactive" if self.stopped else "Active"
})
|
print out statistics every 10 seconds from idle loop
|
def idle_print_status(self):
'''print out statistics every 10 seconds from idle loop'''
now = time.time()
if (now - self.last_idle_status_printed_time) >= 10:
print (self.status())
self.last_idle_status_printed_time = now
self.prev_download = self.download
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.