INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Send packets to UAV in idle loop
def idle_send_acks_and_nacks(self): '''Send packets to UAV in idle loop''' max_blocks_to_send = 10 blocks_sent = 0 i=0 now = time.time() while i < len(self.blocks_to_ack_and_nack) and blocks_sent < max_blocks_to_send: # print("ACKLIST: %s" % ([x[1] for x in self.blocks_to_ack_and_nack],)) stuff = self.blocks_to_ack_and_nack[i] [master, block, status, first_sent, last_sent] = stuff if status == 1: # print("DFLogger: ACKing block (%d)" % (block,)) self.master.mav.remote_log_block_status_send(block,status) blocks_sent += 1 del self.acking_blocks[block] del self.blocks_to_ack_and_nack[i] continue if block not in self.missing_blocks: # we've received this block now del self.blocks_to_ack_and_nack[i] continue # give up on packet if we have seen one with a much higher # number: if self.block_cnt - block > 200 or \ now - first_sent > 60: print("DFLogger: Abandoning block (%d)" % (block,)) del self.blocks_to_ack_and_nack[i] del self.missing_blocks[block] self.abandoned += 1 continue i += 1 # only send each nack every-so-often: if last_sent is not None: if now - last_sent < 0.1: continue print("DFLogger: NACKing block (%d)" % (block,)) self.master.mav.remote_log_block_status_send(block,status) blocks_sent += 1 stuff[4] = now
handle REMOTE_LOG_DATA_BLOCK packets
def mavlink_packet(self, m): '''handle REMOTE_LOG_DATA_BLOCK packets''' now = time.time() if m.get_type() == 'REMOTE_LOG_DATA_BLOCK': if self.stopped: # send a stop packet every second until the other end gets the idea: if now - self.time_last_stop_packet_sent > 1: if self.log_settings.verbose: print("DFLogger: Sending stop packet") self.master.mav.remote_log_block_status_send(mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_STOP,1) return # if random.random() < 0.1: # drop 1 packet in 10 # return if not self.new_log_started: if self.log_settings.verbose: print("DFLogger: Received data packet - starting new log") self.start_new_log() self.new_log_started = True if self.new_log_started == True: size = m.block_size data = ''.join(str(chr(x)) for x in m.data[:size]) ofs = size*(m.block_cnt) self.logfile.seek(ofs) self.logfile.write(data) if m.block_cnt in self.missing_blocks: if self.log_settings.verbose: print("DFLogger: Received missing block: %d" % (m.block_cnt,)) del self.missing_blocks[m.block_cnt] self.missing_found += 1 self.blocks_to_ack_and_nack.append([self.master,m.block_cnt,1,now,None]) self.acking_blocks[m.block_cnt] = 1 # print("DFLogger: missing blocks: %s" % (str(self.missing_blocks),)) else: # ACK the block we just got: if m.block_cnt in self.acking_blocks: # already acking this one; we probably sent # multiple nacks and received this one # multiple times pass else: self.blocks_to_ack_and_nack.append([self.master,m.block_cnt,1,now,None]) self.acking_blocks[m.block_cnt] = 1 # NACK any blocks we haven't seen and should have: if(m.block_cnt - self.block_cnt > 1): for block in range(self.block_cnt+1, m.block_cnt): if block not in self.missing_blocks and \ block not in self.acking_blocks: self.missing_blocks[block] = 1 if self.log_settings.verbose: print ("DFLogger: setting %d for nacking" % (block,)) self.blocks_to_ack_and_nack.append([self.master,block,0,now,None]) #print "\nmissed blocks: ",self.missing_blocks if self.block_cnt < m.block_cnt: self.block_cnt = m.block_cnt self.download += size elif not self.new_log_started and not self.stopped: # send a start packet every second until the other end gets the idea: if now - self.time_last_start_packet_sent > 1: if self.log_settings.verbose: print("DFLogger: Sending start packet") self.master.mav.remote_log_block_status_send(mavutil.mavlink.MAV_REMOTE_LOG_DATA_BLOCK_START,1) self.time_last_start_packet_sent = now
state of APM memory brkval : heap top (uint16_t) freemem : free memory (uint16_t)
def meminfo_send(self, brkval, freemem, force_mavlink1=False): ''' state of APM memory brkval : heap top (uint16_t) freemem : free memory (uint16_t) ''' return self.send(self.meminfo_encode(brkval, freemem), force_mavlink1=force_mavlink1)
return true if m is older than lastm by timestamp
def older_message(m, lastm): '''return true if m is older than lastm by timestamp''' atts = {'time_boot_ms' : 1.0e-3, 'time_unix_usec' : 1.0e-6, 'time_usec' : 1.0e-6} for a in atts.keys(): if hasattr(m, a): mul = atts[a] t1 = m.getattr(a) * mul t2 = lastm.getattr(a) * mul if t2 >= t1 and t2 - t1 < 60: return True return False
process one logfile
def process(filename): '''process one logfile''' print("Processing %s" % filename) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps, robust_parsing=args.robust) ext = os.path.splitext(filename)[1] isbin = ext in ['.bin', '.BIN'] islog = ext in ['.log', '.LOG'] output = None count = 1 dirname = os.path.dirname(filename) if isbin or islog: extension = "bin" else: extension = "tlog" file_header = '' messages = [] # we allow a list of modes that map to one mode number. This allows for --mode=AUTO,RTL and consider the RTL as part of AUTO modes = args.mode.upper().split(',') flightmode = None while True: m = mlog.recv_match() if m is None: break if args.link is not None and m._link != args.link: continue mtype = m.get_type() if mtype in messages: if older_message(m, messages[mtype]): continue # we don't use mlog.flightmode as that can be wrong if we are extracting a single link if mtype == 'HEARTBEAT' and m.get_srcComponent() != mavutil.mavlink.MAV_COMP_ID_GIMBAL and m.type != mavutil.mavlink.MAV_TYPE_GCS: flightmode = mavutil.mode_string_v10(m).upper() if mtype == 'MODE': flightmode = mlog.flightmode if (isbin or islog) and m.get_type() in ["FMT", "PARM", "CMD"]: file_header += m.get_msgbuf() if (isbin or islog) and m.get_type() == 'MSG' and m.Message.startswith("Ardu"): file_header += m.get_msgbuf() if m.get_type() in ['PARAM_VALUE','MISSION_ITEM']: timestamp = getattr(m, '_timestamp', None) file_header += struct.pack('>Q', timestamp*1.0e6) + m.get_msgbuf() if not mavutil.evaluate_condition(args.condition, mlog.messages): continue if flightmode in modes: if output is None: path = os.path.join(dirname, "%s%u.%s" % (modes[0], count, extension)) count += 1 print("Creating %s" % path) output = open(path, mode='wb') output.write(file_header) else: if output is not None: output.close() output = None if output and m.get_type() != 'BAD_DATA': timestamp = getattr(m, '_timestamp', None) if not isbin: output.write(struct.pack('>Q', timestamp*1.0e6)) output.write(m.get_msgbuf())
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if m.get_type() == 'LOG_ENTRY': self.handle_log_entry(m) elif m.get_type() == 'LOG_DATA': self.handle_log_data(m)
handling incoming log entry
def handle_log_entry(self, m): '''handling incoming log entry''' if m.time_utc == 0: tstring = '' else: tstring = time.ctime(m.time_utc) self.entries[m.id] = m print("Log %u numLogs %u lastLog %u size %u %s" % (m.id, m.num_logs, m.last_log_num, m.size, tstring))
handling incoming log data
def handle_log_data(self, m): '''handling incoming log data''' if self.download_file is None: return # lose some data # import random # if random.uniform(0,1) < 0.05: # print('dropping ', str(m)) # return if m.ofs != self.download_ofs: self.download_file.seek(m.ofs) self.download_ofs = m.ofs if m.count != 0: data = m.data[:m.count] s = ''.join(str(chr(x)) for x in data) self.download_file.write(s) self.download_set.add(m.ofs // 90) self.download_ofs += m.count self.download_last_timestamp = time.time() if m.count == 0 or (m.count < 90 and len(self.download_set) == 1 + (m.ofs // 90)): dt = time.time() - self.download_start self.download_file.close() size = os.path.getsize(self.download_filename) speed = size / (1000.0 * dt) print("Finished downloading %s (%u bytes %u seconds, %.1f kbyte/sec %u retries)" % ( self.download_filename, size, dt, speed, self.retries)) self.download_file = None self.download_filename = None self.download_set = set()
handling missing incoming log data
def handle_log_data_missing(self): '''handling missing incoming log data''' if len(self.download_set) == 0: return highest = max(self.download_set) diff = set(range(highest)).difference(self.download_set) if len(diff) == 0: self.master.mav.log_request_data_send(self.target_system, self.target_component, self.download_lognum, (1 + highest) * 90, 0xffffffff) self.retries += 1 else: num_requests = 0 while num_requests < 20: start = min(diff) diff.remove(start) end = start while end + 1 in diff: end += 1 diff.remove(end) self.master.mav.log_request_data_send(self.target_system, self.target_component, self.download_lognum, start * 90, (end + 1 - start) * 90) num_requests += 1 self.retries += 1 if len(diff) == 0: break
show download status
def log_status(self): '''show download status''' if self.download_filename is None: print("No download") return dt = time.time() - self.download_start speed = os.path.getsize(self.download_filename) / (1000.0 * dt) m = self.entries.get(self.download_lognum, None) if m is None: size = 0 else: size = m.size highest = max(self.download_set) diff = set(range(highest)).difference(self.download_set) print("Downloading %s - %u/%u bytes %.1f kbyte/s (%u retries %u missing)" % (self.download_filename, os.path.getsize(self.download_filename), size, speed, self.retries, len(diff)))
download a log file
def log_download(self, log_num, filename): '''download a log file''' print("Downloading log %u as %s" % (log_num, filename)) self.download_lognum = log_num self.download_file = open(filename, "wb") self.master.mav.log_request_data_send(self.target_system, self.target_component, log_num, 0, 0xFFFFFFFF) self.download_filename = filename self.download_set = set() self.download_start = time.time() self.download_last_timestamp = time.time() self.download_ofs = 0 self.retries = 0
log commands
def cmd_log(self, args): '''log commands''' if len(args) < 1: print("usage: log <list|download|erase|resume|status|cancel>") return if args[0] == "status": self.log_status() if args[0] == "list": print("Requesting log list") self.download_set = set() self.master.mav.log_request_list_send(self.target_system, self.target_component, 0, 0xffff) elif args[0] == "erase": self.master.mav.log_erase_send(self.target_system, self.target_component) elif args[0] == "resume": self.master.mav.log_request_end_send(self.target_system, self.target_component) elif args[0] == "cancel": if self.download_file is not None: self.download_file.close() self.reset() elif args[0] == "download": if len(args) < 2: print("usage: log download <lognumber> <filename>") return if args[1] == 'latest': if len(self.entries.keys()) == 0: print("Please use log list first") return log_num = sorted(self.entries, key=lambda id: self.entries[id].time_utc)[-1] else: log_num = int(args[1]) if len(args) > 2: filename = args[2] else: filename = "log%u.bin" % log_num self.log_download(log_num, filename)
handle missing log data
def idle_task(self): '''handle missing log data''' if self.download_last_timestamp is not None and time.time() - self.download_last_timestamp > 0.7: self.download_last_timestamp = time.time() self.handle_log_data_missing()
complete mavproxy module names
def complete_modules(text): '''complete mavproxy module names''' import MAVProxy.modules, pkgutil modlist = [x[1] for x in pkgutil.iter_modules(MAVProxy.modules.__path__)] ret = [] loaded = set(complete_loadedmodules('')) for m in modlist: if not m.startswith("mavproxy_"): continue name = m[9:] if not name in loaded: ret.append(name) return ret
complete a filename
def complete_filename(text): '''complete a filename''' #ensure directories have trailing slashes: list = glob.glob(text+'*') for idx, val in enumerate(list): if os.path.isdir(val): list[idx] = (val + os.path.sep) return list
complete a MAVLink variable
def complete_variable(text): '''complete a MAVLink variable''' if text.find('.') != -1: var = text.split('.')[0] if var in rline_mpstate.status.msgs: ret = [] for f in rline_mpstate.status.msgs[var].get_fieldnames(): ret.append(var + '.' + f) return ret return [] return rline_mpstate.status.msgs.keys()
expand one rule component
def rule_expand(component, text): '''expand one rule component''' global rline_mpstate if component[0] == '<' and component[-1] == '>': return component[1:-1].split('|') if component in rline_mpstate.completion_functions: return rline_mpstate.completion_functions[component](text) return [component]
see if one rule component matches
def rule_match(component, cmd): '''see if one rule component matches''' if component == cmd: return True expanded = rule_expand(component, cmd) if cmd in expanded: return True return False
complete using a list of completion rules
def complete_rules(rules, cmd): '''complete using a list of completion rules''' if not isinstance(rules, list): rules = [rules] ret = [] for r in rules: ret += complete_rule(r, cmd) return ret
completion routine for when user presses tab
def complete(text, state): '''completion routine for when user presses tab''' global last_clist global rline_mpstate if state != 0 and last_clist is not None: return last_clist[state] # split the command so far cmd = readline.get_line_buffer().split() if len(cmd) == 1: # if on first part then complete on commands and aliases last_clist = complete_command(text) + complete_alias(text) elif cmd[0] in rline_mpstate.completions: # we have a completion rule for this command last_clist = complete_rules(rline_mpstate.completions[cmd[0]], cmd[1:]) else: # assume completion by filename last_clist = glob.glob(text+'*') ret = [] for c in last_clist: if c.startswith(text) or c.startswith(text.upper()): ret.append(c) if len(ret) == 0: # if we had no matches then try case insensitively text = text.lower() for c in last_clist: if c.lower().startswith(text): ret.append(c) ret.append(None) last_clist = ret return last_clist[state]
Translates from ROS LaserScan to JderobotTypes LaserData. @param scan: ROS LaserScan to translate @type scan: LaserScan @return a LaserData translated from scan
def laserScan2LaserData(scan): ''' Translates from ROS LaserScan to JderobotTypes LaserData. @param scan: ROS LaserScan to translate @type scan: LaserScan @return a LaserData translated from scan ''' laser = LaserData() laser.values = scan.ranges ''' ROS Angle Map JdeRobot Angle Map 0 PI/2 | | | | PI/2 --------- -PI/2 PI --------- 0 | | | | ''' laser.minAngle = scan.angle_min + PI/2 laser.maxAngle = scan.angle_max + PI/2 laser.maxRange = scan.range_max laser.minRange = scan.range_min laser.timeStamp = scan.header.stamp.secs + (scan.header.stamp.nsecs *1e-9) return laser
Callback function to receive and save Laser Scans. @param scan: ROS LaserScan received @type scan: LaserScan
def __callback (self, scan): ''' Callback function to receive and save Laser Scans. @param scan: ROS LaserScan received @type scan: LaserScan ''' laser = laserScan2LaserData(scan) self.lock.acquire() self.data = laser self.lock.release()
Starts (Subscribes) the client.
def start (self): ''' Starts (Subscribes) the client. ''' self.sub = rospy.Subscriber(self.topic, LaserScan, self.__callback)
Returns last LaserData. @return last JdeRobotTypes LaserData saved
def getLaserData(self): ''' Returns last LaserData. @return last JdeRobotTypes LaserData saved ''' self.lock.acquire() laser = self.data self.lock.release() return laser
add a point to the kml file
def add_to_linestring(position_data, kml_linestring): '''add a point to the kml file''' global kml # add altitude offset position_data[2] += float(args.aoff) kml_linestring.coords.addcoordinates([position_data])
add some data
def add_data(t, msg, msg_types, vars, fields, field_types, position_field_type): '''add some data''' mtype = msg.get_type() if mtype not in msg_types: return for i in range(0, len(fields)): if mtype not in field_types[i]: continue f = fields[i] v = mavutil.evaluate_expression(f, vars) if v is None: continue # Check if we have position or state information if f == mainstate_field: # Handle main state information # add_data.mainstate_current >= 0 : avoid starting a new linestring # when mainstate comes after the first position data in the log if (v != add_data.mainstate_current and add_data.mainstate_current >= 0): add_data.new_linestring = True add_data.mainstate_current = v else: # Handle position information # make sure lon, lat, alt is saved in the correct order in # position_data (the same as in position_field_types) add_data.position_data[i] = v # check if we have a full gps measurement gps_measurement_ready = True for v in add_data.position_data: if v is None: gps_measurement_ready = False if not gps_measurement_ready: return # if new line string is needed (because of state change): add previous # linestring to kml_linestrings list, add a new linestring to the kml # multigeometry and append to the new linestring # else: append to current linestring if add_data.new_linestring: if add_data.current_kml_linestring is not None: kml_linestrings.append(add_data.current_kml_linestring) name = "".join([args.source, ":", str(add_data.mainstate_current)]) add_data.current_kml_linestring = \ kml.newlinestring(name=name, altitudemode='absolute') # set rendering options if args.extrude: add_data.current_kml_linestring.extrude = 1 add_data.current_kml_linestring.style.linestyle.color = \ colors[max([add_data.mainstate_current, 0])] add_data.new_linestring = False add_to_linestring(add_data.position_data, add_data.current_kml_linestring) add_data.last_time = msg._timestamp else: if (msg._timestamp - add_data.last_time) > 0.1: add_to_linestring(add_data.position_data, add_data.current_kml_linestring) add_data.last_time = msg._timestamp # reset position_data add_data.position_data = [None for n in position_field_type]
process one file
def process_file(filename, source): '''process one file''' print("Processing %s" % filename) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps) position_field_type = sniff_field_spelling(mlog, source) # init fields and field_types lists fields = [args.source + "." + s for s in position_field_type] fields.append(mainstate_field) field_types = [] msg_types = set() re_caps = re.compile('[A-Z_][A-Z0-9_]+') for f in fields: caps = set(re.findall(re_caps, f)) msg_types = msg_types.union(caps) field_types.append(caps) add_data.new_linestring = True add_data.mainstate_current = -1 add_data.current_kml_linestring = None add_data.position_data = [None for n in position_field_type] add_data.last_time = 0 while True: msg = mlog.recv_match(args.condition) if msg is None: break tdays = (msg._timestamp - time.timezone) / (24 * 60 * 60) tdays += 719163 # pylab wants it since 0001-01-01 add_data(tdays, msg, msg_types, mlog.messages, fields, field_types, position_field_type)
attempt to detect whether APM or PX4 attributes names are in use
def sniff_field_spelling(mlog, source): '''attempt to detect whether APM or PX4 attributes names are in use''' position_field_type_default = position_field_types[0] # Default to PX4 spelling msg = mlog.recv_match(source) mlog._rewind() # Unfortunately it's either call this or return a mutated object position_field_selection = [spelling for spelling in position_field_types if hasattr(msg, spelling[0])] return position_field_selection[0] if position_field_selection else position_field_type_default
called on idle
def idle_task(self): '''called on idle''' if mp_util.has_wxpython and (not self.menu_added_console and self.module('console') is not None): self.menu_added_console = True # we don't dynamically update these yet due to a wx bug self.menu_add.items = [ MPMenuItem(p, p, '# link add %s' % p) for p in self.complete_serial_ports('') ] self.menu_rm.items = [ MPMenuItem(p, p, '# link remove %s' % p) for p in self.complete_links('') ] self.module('console').add_menu(self.menu) for m in self.mpstate.mav_master: m.source_system = self.settings.source_system m.mav.srcSystem = m.source_system m.mav.srcComponent = self.settings.source_component
handle link commands
def cmd_link(self, args): '''handle link commands''' if len(args) < 1: self.show_link() elif args[0] == "list": self.cmd_link_list() elif args[0] == "add": if len(args) != 2: print("Usage: link add LINK") return self.cmd_link_add(args[1:]) elif args[0] == "ports": self.cmd_link_ports() elif args[0] == "remove": if len(args) != 2: print("Usage: link remove LINK") return self.cmd_link_remove(args[1:]) else: print("usage: link <list|add|remove>")
show link information
def show_link(self): '''show link information''' for master in self.mpstate.mav_master: linkdelay = (self.status.highest_msec - master.highest_msec)*1.0e-3 if master.linkerror: print("link %u down" % (master.linknum+1)) else: print("link %u OK (%u packets, %.2fs delay, %u lost, %.1f%% loss)" % (master.linknum+1, self.status.counters['MasterIn'][master.linknum], linkdelay, master.mav_loss, master.packet_loss()))
list links
def cmd_link_list(self): '''list links''' print("%u links" % len(self.mpstate.mav_master)) for i in range(len(self.mpstate.mav_master)): conn = self.mpstate.mav_master[i] print("%u: %s" % (i, conn.address))
add new link
def link_add(self, device): '''add new link''' try: print("Connect %s source_system=%d" % (device, self.settings.source_system)) conn = mavutil.mavlink_connection(device, autoreconnect=True, source_system=self.settings.source_system, baud=self.settings.baudrate) conn.mav.srcComponent = self.settings.source_component except Exception as msg: print("Failed to connect to %s : %s" % (device, msg)) return False if self.settings.rtscts: conn.set_rtscts(True) conn.linknum = len(self.mpstate.mav_master) conn.mav.set_callback(self.master_callback, conn) if hasattr(conn.mav, 'set_send_callback'): conn.mav.set_send_callback(self.master_send_callback, conn) conn.linknum = len(self.mpstate.mav_master) conn.linkerror = False conn.link_delayed = False conn.last_heartbeat = 0 conn.last_message = 0 conn.highest_msec = 0 self.mpstate.mav_master.append(conn) self.status.counters['MasterIn'].append(0) try: mp_util.child_fd_list_add(conn.port.fileno()) except Exception: pass return True
add new link
def cmd_link_add(self, args): '''add new link''' device = args[0] print("Adding link %s" % device) self.link_add(device)
show available ports
def cmd_link_ports(self): '''show available ports''' ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*']) for p in ports: print("%s : %s : %s" % (p.device, p.description, p.hwid))
process mavlink message m on master, sending any messages to recipients
def master_callback(self, m, master): '''process mavlink message m on master, sending any messages to recipients''' # see if it is handled by a specialised sysid connection sysid = m.get_srcSystem() if sysid in self.mpstate.sysid_outputs: self.mpstate.sysid_outputs[sysid].write(m.get_msgbuf()) return if getattr(m, '_timestamp', None) is None: master.post_message(m) self.status.counters['MasterIn'][master.linknum] += 1 mtype = m.get_type() # and log them if mtype not in dataPackets and self.mpstate.logqueue: # put link number in bottom 2 bits, so we can analyse packet # delay in saved logs usec = self.get_usec() usec = (usec & ~3) | master.linknum self.mpstate.logqueue.put(str(struct.pack('>Q', usec) + m.get_msgbuf())) # keep the last message of each type around self.status.msgs[m.get_type()] = m if not m.get_type() in self.status.msg_count: self.status.msg_count[m.get_type()] = 0 self.status.msg_count[m.get_type()] += 1 if m.get_srcComponent() == mavutil.mavlink.MAV_COMP_ID_GIMBAL and m.get_type() == 'HEARTBEAT': # silence gimbal heartbeat packets for now return if getattr(m, 'time_boot_ms', None) is not None: # update link_delayed attribute self.handle_msec_timestamp(m, master) if mtype in activityPackets: if master.linkerror: master.linkerror = False self.say("link %u OK" % (master.linknum+1)) self.status.last_message = time.time() master.last_message = self.status.last_message if master.link_delayed: # don't process delayed packets that cause double reporting if mtype in delayedPackets: return if mtype == 'HEARTBEAT' and m.get_srcSystem() != 255: if self.settings.target_system == 0 and self.settings.target_system != m.get_srcSystem(): self.settings.target_system = m.get_srcSystem() self.say("online system %u" % self.settings.target_system,'message') if self.status.heartbeat_error: self.status.heartbeat_error = False self.say("heartbeat OK") if master.linkerror: master.linkerror = False self.say("link %u OK" % (master.linknum+1)) self.status.last_heartbeat = time.time() master.last_heartbeat = self.status.last_heartbeat armed = self.master.motors_armed() if armed != self.status.armed: self.status.armed = armed if armed: self.say("ARMED") else: self.say("DISARMED") if master.flightmode != self.status.flightmode and time.time() > self.status.last_mode_announce + 2: self.status.flightmode = master.flightmode self.status.last_mode_announce = time.time() if self.mpstate.functions.input_handler is None: self.mpstate.rl.set_prompt(self.status.flightmode + "> ") self.say("Mode " + self.status.flightmode) if m.type == mavutil.mavlink.MAV_TYPE_FIXED_WING: self.mpstate.vehicle_type = 'plane' self.mpstate.vehicle_name = 'ArduPlane' elif m.type in [mavutil.mavlink.MAV_TYPE_GROUND_ROVER, mavutil.mavlink.MAV_TYPE_SURFACE_BOAT, mavutil.mavlink.MAV_TYPE_SUBMARINE]: self.mpstate.vehicle_type = 'rover' self.mpstate.vehicle_name = 'APMrover2' elif m.type in [mavutil.mavlink.MAV_TYPE_QUADROTOR, mavutil.mavlink.MAV_TYPE_COAXIAL, mavutil.mavlink.MAV_TYPE_HEXAROTOR, mavutil.mavlink.MAV_TYPE_OCTOROTOR, mavutil.mavlink.MAV_TYPE_TRICOPTER, mavutil.mavlink.MAV_TYPE_HELICOPTER]: self.mpstate.vehicle_type = 'copter' self.mpstate.vehicle_name = 'ArduCopter' elif m.type in [mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER]: self.mpstate.vehicle_type = 'antenna' self.mpstate.vehicle_name = 'AntennaTracker' elif mtype == 'STATUSTEXT': if m.text != self.status.last_apm_msg or time.time() > self.status.last_apm_msg_time+2: self.mpstate.console.writeln("APM: %s" % m.text, bg='red') self.status.last_apm_msg = m.text self.status.last_apm_msg_time = time.time() elif mtype == "VFR_HUD": have_gps_lock = False if 'GPS_RAW' in self.status.msgs and self.status.msgs['GPS_RAW'].fix_type == 2: have_gps_lock = True elif 'GPS_RAW_INT' in self.status.msgs and self.status.msgs['GPS_RAW_INT'].fix_type == 3: have_gps_lock = True if have_gps_lock and not self.status.have_gps_lock and m.alt != 0: self.say("GPS lock at %u meters" % m.alt, priority='notification') self.status.have_gps_lock = True elif mtype == "GPS_RAW": if self.status.have_gps_lock: if m.fix_type != 2 and not self.status.lost_gps_lock and (time.time() - self.status.last_gps_lock) > 3: self.say("GPS fix lost") self.status.lost_gps_lock = True if m.fix_type == 2 and self.status.lost_gps_lock: self.say("GPS OK") self.status.lost_gps_lock = False if m.fix_type == 2: self.status.last_gps_lock = time.time() elif mtype == "GPS_RAW_INT": if self.status.have_gps_lock: if m.fix_type < 3 and not self.status.lost_gps_lock and (time.time() - self.status.last_gps_lock) > 3: self.say("GPS fix lost") self.status.lost_gps_lock = True if m.fix_type >= 3 and self.status.lost_gps_lock: self.say("GPS OK") self.status.lost_gps_lock = False if m.fix_type >= 3: self.status.last_gps_lock = time.time() elif mtype == "NAV_CONTROLLER_OUTPUT" and self.status.flightmode == "AUTO" and self.mpstate.settings.distreadout: rounded_dist = int(m.wp_dist/self.mpstate.settings.distreadout)*self.mpstate.settings.distreadout if math.fabs(rounded_dist - self.status.last_distance_announce) >= self.mpstate.settings.distreadout: if rounded_dist != 0: self.say("%u" % rounded_dist, priority="progress") self.status.last_distance_announce = rounded_dist elif mtype == "GLOBAL_POSITION_INT": self.report_altitude(m.relative_alt*0.001) elif mtype == "COMPASSMOT_STATUS": print(m) elif mtype == "BAD_DATA": if self.mpstate.settings.shownoise and mavutil.all_printable(m.data): self.mpstate.console.write(str(m.data), bg='red') elif mtype in [ "COMMAND_ACK", "MISSION_ACK" ]: self.mpstate.console.writeln("Got MAVLink msg: %s" % m) if mtype == "COMMAND_ACK" and m.command == mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION: if m.result == mavutil.mavlink.MAV_RESULT_ACCEPTED: self.say("Calibrated") else: #self.mpstate.console.writeln("Got MAVLink msg: %s" % m) pass if self.status.watch is not None: if fnmatch.fnmatch(m.get_type().upper(), self.status.watch.upper()): self.mpstate.console.writeln('< '+str(m)) # don't pass along bad data if mtype != 'BAD_DATA': # pass messages along to listeners, except for REQUEST_DATA_STREAM, which # would lead a conflict in stream rate setting between mavproxy and the other # GCS if self.mpstate.settings.mavfwd_rate or mtype != 'REQUEST_DATA_STREAM': if not mtype in self.no_fwd_types: for r in self.mpstate.mav_outputs: r.write(m.get_msgbuf()) # pass to modules for (mod,pm) in self.mpstate.modules: if not hasattr(mod, 'mavlink_packet'): continue try: mod.mavlink_packet(m) except Exception as msg: if self.mpstate.settings.moddebug == 1: print(msg) elif self.mpstate.settings.moddebug > 1: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
write to the console
def write(self, text, fg='black', bg='white'): '''write to the console''' if isinstance(text, str): sys.stdout.write(text) else: sys.stdout.write(str(text)) sys.stdout.flush() if self.udp.connected(): self.udp.writeln(text) if self.tcp.connected(): self.tcp.writeln(text)
write to the console with linefeed
def writeln(self, text, fg='black', bg='white'): '''write to the console with linefeed''' if not isinstance(text, str): text = str(text) self.write(text + '\n', fg=fg, bg=bg)
see if the path matches a extension
def match_extension(f): '''see if the path matches a extension''' (root,ext) = os.path.splitext(f) return ext.lower() in extensions
load an icon from the data directory
def mp_icon(filename): '''load an icon from the data directory''' # we have to jump through a lot of hoops to get an OpenCV image # when we may be in a package zip file try: import pkg_resources name = __name__ if name == "__main__": name = "MAVProxy.modules.mavproxy_map.mp_tile" raw = pkg_resources.resource_stream(name, "data/%s" % filename).read() except Exception: raw = open(os.path.join(__file__, 'data', filename)).read() imagefiledata = cv.CreateMatHeader(1, len(raw), cv.CV_8UC1) cv.SetData(imagefiledata, raw, len(raw)) img = cv.DecodeImage(imagefiledata, cv.CV_LOAD_IMAGE_COLOR) return img
return lat,lon within a tile given (offsetx,offsety)
def coord(self, offset=(0,0)): '''return lat,lon within a tile given (offsetx,offsety)''' (tilex, tiley) = self.tile (offsetx, offsety) = offset world_tiles = 1<<self.zoom x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1 y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1 lon = x * 180.0 y = math.exp(-y*2*math.pi) e = (y-1)/(y+1) lat = 180.0/math.pi * math.asin(e) return (lat, lon)
return tile size as (width,height) in meters
def size(self): '''return tile size as (width,height) in meters''' (lat1, lon1) = self.coord((0,0)) (lat2, lon2) = self.coord((TILES_WIDTH,0)) width = mp_util.gps_distance(lat1, lon1, lat2, lon2) (lat2, lon2) = self.coord((0,TILES_HEIGHT)) height = mp_util.gps_distance(lat1, lon1, lat2, lon2) return (width,height)
distance of this tile from a given lat/lon
def distance(self, lat, lon): '''distance of this tile from a given lat/lon''' (tlat, tlon) = self.coord((TILES_WIDTH/2,TILES_HEIGHT/2)) return mp_util.gps_distance(lat, lon, tlat, tlon)
return relative path of tile image
def path(self): '''return relative path of tile image''' (x, y) = self.tile return os.path.join('%u' % self.zoom, '%u' % y, '%u.img' % x)
return URL for a tile
def url(self, service): '''return URL for a tile''' if service not in TILE_SERVICES: raise TileException('unknown tile service %s' % service) url = string.Template(TILE_SERVICES[service]) (x,y) = self.tile tile_info = TileServiceInfo(x, y, self.zoom) return url.substitute(tile_info)
convert lat/lon/zoom to a TileInfo
def coord_to_tile(self, lat, lon, zoom): '''convert lat/lon/zoom to a TileInfo''' world_tiles = 1<<zoom x = world_tiles / 360.0 * (lon + 180.0) tiles_pre_radian = world_tiles / (2 * math.pi) e = math.sin(lat * (1/180.*math.pi)) y = world_tiles/2 + 0.5*math.log((1+e)/(1-e)) * (-tiles_pre_radian) offsetx = int((x - int(x)) * TILES_WIDTH) offsety = int((y - int(y)) * TILES_HEIGHT) return TileInfo((int(x) % world_tiles, int(y) % world_tiles), zoom, self.service, offset=(offsetx, offsety))
return full path to a tile
def tile_to_path(self, tile): '''return full path to a tile''' return os.path.join(self.cache_path, self.service, tile.path())
return the tile ID that covers a latitude/longitude at a specified zoom level
def coord_to_tilepath(self, lat, lon, zoom): '''return the tile ID that covers a latitude/longitude at a specified zoom level ''' tile = self.coord_to_tile(lat, lon, zoom) return self.tile_to_path(tile)
start the downloader
def start_download_thread(self): '''start the downloader''' if self._download_thread: return t = threading.Thread(target=self.downloader) t.daemon = True self._download_thread = t t.start()
load a lower resolution tile from cache to fill in a map while waiting for a higher resolution tile
def load_tile_lowres(self, tile): '''load a lower resolution tile from cache to fill in a map while waiting for a higher resolution tile''' if tile.zoom == self.min_zoom: return None # find the equivalent lower res tile (lat,lon) = tile.coord() width2 = TILES_WIDTH height2 = TILES_HEIGHT for zoom2 in range(tile.zoom-1, self.min_zoom-1, -1): width2 /= 2 height2 /= 2 if width2 == 0 or height2 == 0: break tile_info = self.coord_to_tile(lat, lon, zoom2) # see if its in the tile cache key = tile_info.key() if key in self._tile_cache: img = self._tile_cache[key] if img == self._unavailable: continue else: path = self.tile_to_path(tile_info) try: img = cv.LoadImage(path) # add it to the tile cache self._tile_cache[key] = img while len(self._tile_cache) > self.cache_size: self._tile_cache.popitem(0) except IOError as e: continue # copy out the quadrant we want availx = min(TILES_WIDTH - tile_info.offsetx, width2) availy = min(TILES_HEIGHT - tile_info.offsety, height2) if availx != width2 or availy != height2: continue cv.SetImageROI(img, (tile_info.offsetx, tile_info.offsety, width2, height2)) img2 = cv.CreateImage((width2,height2), 8, 3) try: cv.Copy(img, img2) except Exception: continue cv.ResetImageROI(img) # and scale it scaled = cv.CreateImage((TILES_WIDTH, TILES_HEIGHT), 8, 3) cv.Resize(img2, scaled) #cv.Rectangle(scaled, (0,0), (255,255), (0,255,0), 1) return scaled return None
load a tile from cache or tile server
def load_tile(self, tile): '''load a tile from cache or tile server''' # see if its in the tile cache key = tile.key() if key in self._tile_cache: img = self._tile_cache[key] if img == self._unavailable: img = self.load_tile_lowres(tile) if img is None: img = self._unavailable return img path = self.tile_to_path(tile) try: ret = cv.LoadImage(path) # if it is an old tile, then try to refresh if os.path.getmtime(path) + self.refresh_age < time.time(): try: self._download_pending[key].refresh_time() except Exception: self._download_pending[key] = tile self.start_download_thread() # add it to the tile cache self._tile_cache[key] = ret while len(self._tile_cache) > self.cache_size: self._tile_cache.popitem(0) return ret except IOError as e: # windows gives errno 0 for some versions of python, treat that as ENOENT # and try a download if not e.errno in [errno.ENOENT,0]: raise pass if not self.download: img = self.load_tile_lowres(tile) if img is None: img = self._unavailable return img try: self._download_pending[key].refresh_time() except Exception: self._download_pending[key] = tile self.start_download_thread() img = self.load_tile_lowres(tile) if img is None: img = self._loading return img
return a scaled tile
def scaled_tile(self, tile): '''return a scaled tile''' width = int(TILES_WIDTH / tile.scale) height = int(TILES_HEIGHT / tile.scale) scaled_tile = cv.CreateImage((width,height), 8, 3) full_tile = self.load_tile(tile) cv.Resize(full_tile, scaled_tile) return scaled_tile
return (lat,lon) for a pixel in an area image
def coord_from_area(self, x, y, lat, lon, width, ground_width): '''return (lat,lon) for a pixel in an area image''' pixel_width = ground_width / float(width) dx = x * pixel_width dy = y * pixel_width return mp_util.gps_offset(lat, lon, dx, -dy)
return pixel coordinate (px,py) for position (lat2,lon2) in an area image. Note that the results are relative to top,left and may be outside the image
def coord_to_pixel(self, lat, lon, width, ground_width, lat2, lon2): '''return pixel coordinate (px,py) for position (lat2,lon2) in an area image. Note that the results are relative to top,left and may be outside the image''' pixel_width = ground_width / float(width) if lat is None or lon is None or lat2 is None or lon2 is None: return (0,0) dx = mp_util.gps_distance(lat, lon, lat, lon2) if lon2 < lon: dx = -dx dy = mp_util.gps_distance(lat, lon, lat2, lon) if lat2 > lat: dy = -dy dx /= pixel_width dy /= pixel_width return (int(dx), int(dy))
return a list of TileInfoScaled objects needed for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. If unspecified, the zoom is automatically chosen to avoid having to grow the tiles
def area_to_tile_list(self, lat, lon, width, height, ground_width, zoom=None): '''return a list of TileInfoScaled objects needed for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. If unspecified, the zoom is automatically chosen to avoid having to grow the tiles ''' pixel_width = ground_width / float(width) ground_height = ground_width * (height/(float(width))) top_right = mp_util.gps_newpos(lat, lon, 90, ground_width) bottom_left = mp_util.gps_newpos(lat, lon, 180, ground_height) bottom_right = mp_util.gps_newpos(bottom_left[0], bottom_left[1], 90, ground_width) # choose a zoom level if not provided if zoom is None: zooms = range(self.min_zoom, self.max_zoom+1) else: zooms = [zoom] for zoom in zooms: tile_min = self.coord_to_tile(lat, lon, zoom) (twidth,theight) = tile_min.size() tile_pixel_width = twidth / float(TILES_WIDTH) scale = pixel_width / tile_pixel_width if scale >= 1.0: break scaled_tile_width = int(TILES_WIDTH / scale) scaled_tile_height = int(TILES_HEIGHT / scale) # work out the bottom right tile tile_max = self.coord_to_tile(bottom_right[0], bottom_right[1], zoom) ofsx = int(tile_min.offsetx / scale) ofsy = int(tile_min.offsety / scale) srcy = ofsy dsty = 0 ret = [] # place the tiles for y in range(tile_min.y, tile_max.y+1): srcx = ofsx dstx = 0 for x in range(tile_min.x, tile_max.x+1): if dstx < width and dsty < height: ret.append(TileInfoScaled((x,y), zoom, scale, (srcx,srcy), (dstx,dsty), self.service)) dstx += scaled_tile_width-srcx srcx = 0 dsty += scaled_tile_height-srcy srcy = 0 return ret
return an RGB image for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. The zoom is automatically chosen to avoid having to grow the tiles
def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordered=True): '''return an RGB image for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. The zoom is automatically chosen to avoid having to grow the tiles''' img = cv.CreateImage((width,height),8,3) tlist = self.area_to_tile_list(lat, lon, width, height, ground_width, zoom) # order the display by distance from the middle, so the download happens # close to the middle of the image first if ordered: (midlat, midlon) = self.coord_from_area(width/2, height/2, lat, lon, width, ground_width) tlist.sort(key=lambda d: d.distance(midlat, midlon), reverse=True) for t in tlist: scaled_tile = self.scaled_tile(t) w = min(width - t.dstx, scaled_tile.width - t.srcx) h = min(height - t.dsty, scaled_tile.height - t.srcy) if w > 0 and h > 0: cv.SetImageROI(scaled_tile, (t.srcx, t.srcy, w, h)) cv.SetImageROI(img, (t.dstx, t.dsty, w, h)) cv.Copy(scaled_tile, img) cv.ResetImageROI(img) cv.ResetImageROI(scaled_tile) # return as an RGB image cv.CvtColor(img, img, cv.CV_BGR2RGB) return img
Run a shell command with a timeout. See http://stackoverflow.com/questions/1191374/subprocess-with-timeout
def run_command(args, cwd = None, shell = False, timeout = None, env = None): ''' Run a shell command with a timeout. See http://stackoverflow.com/questions/1191374/subprocess-with-timeout ''' from subprocess import PIPE, Popen from StringIO import StringIO import fcntl, os, signal p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env) tstart = time.time() buf = StringIO() # try to make it non-blocking try: fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK) except Exception: pass while True: time.sleep(0.1) retcode = p.poll() try: buf.write(p.stdout.read()) except Exception: pass if retcode is not None: break if timeout is not None and time.time() > tstart + timeout: print("timeout in process %u" % p.pid) try: os.kill(p.pid, signal.SIGKILL) except OSError: pass p.wait() return buf.getvalue()
calculate barometric altitude
def altitude_difference(self, pressure1, pressure2, ground_temp): '''calculate barometric altitude''' scaling = pressure2 / pressure1 temp = ground_temp + 273.15 return 153.8462 * temp * (1.0 - math.exp(0.190259 * math.log(scaling)))
estimate QNH pressure from GPS altitude and scaled pressure
def qnh_estimate(self): '''estimate QNH pressure from GPS altitude and scaled pressure''' alt_gps = self.master.field('GPS_RAW_INT', 'alt', 0) * 0.001 pressure2 = self.master.field('SCALED_PRESSURE', 'press_abs', 0) ground_temp = self.get_mav_param('GND_TEMP', 21) temp = ground_temp + 273.15 pressure1 = pressure2 / math.exp(math.log(1.0 - (alt_gps / (153.8462 * temp))) / 0.190259) return pressure1
show altitude
def cmd_alt(self, args): '''show altitude''' print("Altitude: %.1f" % self.status.altitude) qnh_pressure = self.get_mav_param('AFS_QNH_PRESSURE', None) if qnh_pressure is not None and qnh_pressure > 0: ground_temp = self.get_mav_param('GND_TEMP', 21) pressure = self.master.field('SCALED_PRESSURE', 'press_abs', 0) qnh_alt = self.altitude_difference(qnh_pressure, pressure, ground_temp) print("QNH Alt: %u meters %u feet for QNH pressure %.1f" % (qnh_alt, qnh_alt*3.2808, qnh_pressure)) print("QNH Estimate: %.1f millibars" % self.qnh_estimate())
adjust TRIM_PITCH_CD up by 5 degrees
def cmd_up(self, args): '''adjust TRIM_PITCH_CD up by 5 degrees''' if len(args) == 0: adjust = 5.0 else: adjust = float(args[0]) old_trim = self.get_mav_param('TRIM_PITCH_CD', None) if old_trim is None: print("Existing trim value unknown!") return new_trim = int(old_trim + (adjust*100)) if math.fabs(new_trim - old_trim) > 1000: print("Adjustment by %d too large (from %d to %d)" % (adjust*100, old_trim, new_trim)) return print("Adjusting TRIM_PITCH_CD from %d to %d" % (old_trim, new_trim)) self.param_set('TRIM_PITCH_CD', new_trim)
show autopilot time
def cmd_time(self, args): '''show autopilot time''' tusec = self.master.field('SYSTEM_TIME', 'time_unix_usec', 0) if tusec == 0: print("No SYSTEM_TIME time available") return print("%s (%s)\n" % (time.ctime(tusec * 1.0e-6), time.ctime()))
change target altitude
def cmd_changealt(self, args): '''change target altitude''' if len(args) < 1: print("usage: changealt <relaltitude>") return relalt = float(args[0]) self.master.mav.mission_item_send(self.settings.target_system, self.settings.target_component, 0, 3, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 3, 1, 0, 0, 0, 0, 0, 0, relalt) print("Sent change altitude command for %.1f meters" % relalt)
auto land commands
def cmd_land(self, args): '''auto land commands''' if len(args) < 1: self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_DO_LAND_START, 0, 0, 0, 0, 0, 0, 0, 0) elif args[0] == 'abort': self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_DO_GO_AROUND, 0, 0, 0, 0, 0, 0, 0, 0) else: print("Usage: land [abort]")
show version
def cmd_version(self, args): '''show version''' self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, 0, 1, 0, 0, 0, 0, 0, 0)
start RC bind
def cmd_rcbind(self, args): '''start RC bind''' if len(args) < 1: print("Usage: rcbind <dsmmode>") return self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_START_RX_PAIR, 0, float(args[0]), 0, 0, 0, 0, 0, 0)
repeat a command at regular intervals
def cmd_repeat(self, args): '''repeat a command at regular intervals''' if len(args) == 0: if len(self.repeats) == 0: print("No repeats") return for i in range(len(self.repeats)): print("%u: %s" % (i, self.repeats[i])) return if args[0] == 'add': if len(args) < 3: print("Usage: repeat add PERIOD CMD") return self.repeats.append(RepeatCommand(float(args[1]), " ".join(args[2:]))) elif args[0] == 'remove': if len(args) < 2: print("Usage: repeat remove INDEX") return i = int(args[1]) if i < 0 or i >= len(self.repeats): print("Invalid index %d" % i) return self.repeats.pop(i) return elif args[0] == 'clean': self.repeats = [] else: print("Usage: repeat <add|remove|clean>")
called on idle
def idle_task(self): '''called on idle''' for r in self.repeats: if r.event.trigger(): self.mpstate.functions.process_stdin(r.cmd, immediate=True)
process one file
def process_file(filename, timeshift): '''process one file''' print("Processing %s" % filename) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps, zero_time_base=args.zero_time_base, dialect=args.dialect) vars = {} while True: msg = mlog.recv_match(args.condition) if msg is None: break try: tdays = matplotlib.dates.date2num(datetime.datetime.fromtimestamp(msg._timestamp+timeshift)) except ValueError: # this can happen if the log is corrupt # ValueError: year is out of range break add_data(tdays, msg, mlog.messages, mlog.flightmode)
show map position click information
def show_position(self): '''show map position click information''' pos = self.click_position dms = (mp_util.degrees_to_dms(pos[0]), mp_util.degrees_to_dms(pos[1])) msg = "Coordinates in WGS84\n" msg += "Decimal: %.6f %.6f\n" % (pos[0], pos[1]) msg += "DMS: %s %s\n" % (dms[0], dms[1]) msg += "Grid: %s\n" % mp_util.latlon_to_grid(pos) if self.logdir: logf = open(os.path.join(self.logdir, "positions.txt"), "a") logf.write("Position: %.6f %.6f at %s\n" % (pos[0], pos[1], time.ctime())) logf.close() posbox = MPMenuChildMessageDialog('Position', msg, font_size=32) posbox.show()
map commands
def cmd_map(self, args): '''map commands''' from MAVProxy.modules.mavproxy_map import mp_slipmap if args[0] == "icon": if len(args) < 3: print("Usage: map icon <lat> <lon> <icon>") else: lat = args[1] lon = args[2] flag = 'flag.png' if len(args) > 3: flag = args[3] + '.png' icon = self.mpstate.map.icon(flag) self.mpstate.map.add_object(mp_slipmap.SlipIcon('icon - %s [%u]' % (str(flag),self.icon_counter), (float(lat),float(lon)), icon, layer=3, rotation=0, follow=False)) self.icon_counter += 1 elif args[0] == "set": self.map_settings.command(args[1:]) self.mpstate.map.add_object(mp_slipmap.SlipBrightness(self.map_settings.brightness)) elif args[0] == "sethome": self.cmd_set_home(args) else: print("usage: map <icon|set>")
display the waypoints
def display_waypoints(self): '''display the waypoints''' from MAVProxy.modules.mavproxy_map import mp_slipmap self.mission_list = self.module('wp').wploader.view_list() polygons = self.module('wp').wploader.polygon_list() self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('Mission')) for i in range(len(polygons)): p = polygons[i] if len(p) > 1: popup = MPMenuSubMenu('Popup', items=[MPMenuItem('Set', returnkey='popupMissionSet'), MPMenuItem('WP Remove', returnkey='popupMissionRemove'), MPMenuItem('WP Move', returnkey='popupMissionMove')]) self.mpstate.map.add_object(mp_slipmap.SlipPolygon('mission %u' % i, p, layer='Mission', linewidth=2, colour=(255,255,255), popup_menu=popup)) loiter_rad = self.get_mav_param('WP_LOITER_RAD') labeled_wps = {} self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('LoiterCircles')) for i in range(len(self.mission_list)): next_list = self.mission_list[i] for j in range(len(next_list)): #label already printed for this wp? if (next_list[j] not in labeled_wps): self.mpstate.map.add_object(mp_slipmap.SlipLabel( 'miss_cmd %u/%u' % (i,j), polygons[i][j], str(next_list[j]), 'Mission', colour=(0,255,255))) if (self.map_settings.loitercircle and self.module('wp').wploader.wp_is_loiter(next_list[j])): self.mpstate.map.add_object(mp_slipmap.SlipCircle('Loiter Circle %u' % (next_list[j] + 1), 'LoiterCircles', polygons[i][j], abs(loiter_rad), (255, 255, 255), 2)) labeled_wps[next_list[j]] = (i,j)
display the fence
def display_fence(self): '''display the fence''' from MAVProxy.modules.mavproxy_map import mp_slipmap self.fence_change_time = self.module('fence').fenceloader.last_change points = self.module('fence').fenceloader.polygon() self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('Fence')) if len(points) > 1: popup = MPMenuSubMenu('Popup', items=[MPMenuItem('FencePoint Remove', returnkey='popupFenceRemove'), MPMenuItem('FencePoint Move', returnkey='popupFenceMove')]) self.mpstate.map.add_object(mp_slipmap.SlipPolygon('Fence', points, layer=1, linewidth=2, colour=(0,255,0), popup_menu=popup))
find closest waypoint to a position
def closest_waypoint(self, latlon): '''find closest waypoint to a position''' (lat, lon) = latlon best_distance = -1 closest = -1 for i in range(self.module('wp').wploader.count()): w = self.module('wp').wploader.wp(i) distance = mp_util.gps_distance(lat, lon, w.x, w.y) if best_distance == -1 or distance < best_distance: best_distance = distance closest = i if best_distance < 20: return closest else: return -1
remove a rally point
def remove_rally(self, key): '''remove a rally point''' a = key.split(' ') if a[0] != 'Rally' or len(a) != 2: print("Bad rally object %s" % key) return i = int(a[1]) self.mpstate.functions.process_stdin('rally remove %u' % i)
move a rally point
def move_rally(self, key): '''move a rally point''' a = key.split(' ') if a[0] != 'Rally' or len(a) != 2: print("Bad rally object %s" % key) return i = int(a[1]) self.moving_rally = i
return a mission idx from a selection_index
def selection_index_to_idx(self, key, selection_index): '''return a mission idx from a selection_index''' a = key.split(' ') if a[0] != 'mission' or len(a) != 2: print("Bad mission object %s" % key) return None midx = int(a[1]) if midx < 0 or midx >= len(self.mission_list): print("Bad mission index %s" % key) return None mlist = self.mission_list[midx] if selection_index < 0 or selection_index >= len(mlist): print("Bad mission polygon %s" % selection_index) return None idx = mlist[selection_index] return idx
move a mission point
def move_mission(self, key, selection_index): '''move a mission point''' idx = self.selection_index_to_idx(key, selection_index) self.moving_wp = idx print("Moving wp %u" % idx)
remove a mission point
def remove_mission(self, key, selection_index): '''remove a mission point''' idx = self.selection_index_to_idx(key, selection_index) self.mpstate.functions.process_stdin('wp remove %u' % idx)
unload module
def unload(self): '''unload module''' self.mpstate.map.close() self.mpstate.map = None self.mpstate.map_functions = {}
add a vehicle to the map
def create_vehicle_icon(self, name, colour, follow=False, vehicle_type=None): '''add a vehicle to the map''' from MAVProxy.modules.mavproxy_map import mp_slipmap if vehicle_type is None: vehicle_type = self.vehicle_type_name if name in self.have_vehicle and self.have_vehicle[name] == vehicle_type: return self.have_vehicle[name] = vehicle_type icon = self.mpstate.map.icon(colour + vehicle_type + '.png') self.mpstate.map.add_object(mp_slipmap.SlipIcon(name, (0,0), icon, layer=3, rotation=0, follow=follow, trail=mp_slipmap.SlipTrail()))
update line drawing
def drawing_update(self): '''update line drawing''' from MAVProxy.modules.mavproxy_map import mp_slipmap if self.draw_callback is None: return self.draw_line.append(self.click_position) if len(self.draw_line) > 1: self.mpstate.map.add_object(mp_slipmap.SlipPolygon('drawing', self.draw_line, layer='Drawing', linewidth=2, colour=(128,128,255)))
called when user selects "Set Home" on map
def cmd_set_home(self, args): '''called when user selects "Set Home" on map''' (lat, lon) = (self.click_position[0], self.click_position[1]) alt = self.ElevationMap.GetElevation(lat, lon) print("Setting home to: ", lat, lon, alt) self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_DO_SET_HOME, 1, # set position 0, # param1 0, # param2 0, # param3 0, # param4 lat, # lat lon, # lon alt)
Returns the configuration as dict @param filename: Name of the file @type filename: String @return a dict with propierties reader from file
def load(filename): ''' Returns the configuration as dict @param filename: Name of the file @type filename: String @return a dict with propierties reader from file ''' filepath = findConfigFile(filename) prop= None if (filepath): print ('loading Config file %s' %(filepath)) with open(filepath, 'r') as stream: cfg=yaml.load(stream) prop = Properties(cfg) else: msg = "Ice.Config file '%s' could not being found" % (filename) raise ValueError(msg) return prop
handle an incoming mavlink packet
def handle_mavlink_packet(self, master, m): '''handle an incoming mavlink packet''' if m.get_type() == 'PARAM_VALUE': param_id = "%.16s" % m.param_id # Note: the xml specifies param_index is a uint16, so -1 in that field will show as 65535 # We accept both -1 and 65535 as 'unknown index' to future proof us against someday having that # xml fixed. if m.param_index != -1 and m.param_index != 65535 and m.param_index not in self.mav_param_set: added_new_parameter = True self.mav_param_set.add(m.param_index) else: added_new_parameter = False if m.param_count != -1: self.mav_param_count = m.param_count self.mav_param[str(param_id)] = m.param_value if self.fetch_one > 0: self.fetch_one -= 1 print("%s = %f" % (param_id, m.param_value)) if added_new_parameter and len(self.mav_param_set) == m.param_count: print("Received %u parameters" % m.param_count) if self.logdir != None: self.mav_param.save(os.path.join(self.logdir, self.parm_file), '*', verbose=True)
check for missing parameters periodically
def fetch_check(self, master): '''check for missing parameters periodically''' if self.param_period.trigger(): if master is None: return if len(self.mav_param_set) == 0: master.param_fetch_all() elif self.mav_param_count != 0 and len(self.mav_param_set) != self.mav_param_count: if master.time_since('PARAM_VALUE') >= 1: diff = set(range(self.mav_param_count)).difference(self.mav_param_set) count = 0 while len(diff) > 0 and count < 10: idx = diff.pop() master.param_fetch_one(idx) count += 1
show help on a parameter
def param_help(self, args): '''show help on a parameter''' if len(args) == 0: print("Usage: param help PARAMETER_NAME") return if self.vehicle_name is None: print("Unknown vehicle type") return path = mp_util.dot_mavproxy("%s.xml" % self.vehicle_name) if not os.path.exists(path): print("Please run 'param download' first (vehicle_name=%s)" % self.vehicle_name) return xml = open(path).read() from lxml import objectify objectify.enable_recursive_str() tree = objectify.fromstring(xml) htree = {} for p in tree.vehicles.parameters.param: n = p.get('name').split(':')[1] htree[n] = p for lib in tree.libraries.parameters: for p in lib.param: n = p.get('name') htree[n] = p for h in args: if h in htree: help = htree[h] print("%s: %s\n" % (h, help.get('humanName'))) print(help.get('documentation')) try: vchild = help.getchildren()[0] print("\nValues: ") for v in vchild.value: print("\t%s : %s" % (v.get('code'), str(v))) except Exception as e: pass else: print("Parameter '%s' not found in documentation" % h)
handle missing parameters
def idle_task(self): '''handle missing parameters''' self.pstate.vehicle_name = self.vehicle_name self.pstate.fetch_check(self.master)
control parameters
def cmd_param(self, args): '''control parameters''' self.pstate.handle_command(self.master, self.mpstate, args)
child process - this holds all the GUI elements
def child_task(self): '''child process - this holds all the GUI elements''' from MAVProxy.modules.lib import mp_util import wx_processguard from wx_loader import wx from wxsettings_ui import SettingsDlg mp_util.child_close_fds() app = wx.App(False) dlg = SettingsDlg(self.settings) dlg.parent_pipe = self.parent_pipe dlg.ShowModal() dlg.Destroy()
watch for settings changes from child
def watch_thread(self): '''watch for settings changes from child''' from mp_settings import MPSetting while True: setting = self.child_pipe.recv() if not isinstance(setting, MPSetting): break try: self.settings.set(setting.name, setting.value) except Exception: print("Unable to set %s to %s" % (setting.name, setting.value))
enable/disable speed report
def cmd_speed(self, args): '''enable/disable speed report''' self.settings.set('speedreporting', not self.settings.speedreporting) if self.settings.speedreporting: self.console.writeln("Speed reporting enabled", bg='yellow') else: self.console.writeln("Speed reporting disabled", bg='yellow')
report a sensor error
def report(self, name, ok, msg=None, deltat=20): '''report a sensor error''' r = self.reports[name] if time.time() < r.last_report + deltat: r.ok = ok return r.last_report = time.time() if ok and not r.ok: self.say("%s OK" % name) r.ok = ok if not r.ok: self.say(msg)
report a sensor change
def report_change(self, name, value, maxdiff=1, deltat=10): '''report a sensor change''' r = self.reports[name] if time.time() < r.last_report + deltat: return r.last_report = time.time() if math.fabs(r.value - value) < maxdiff: return r.value = value self.say("%s %u" % (name, value))
check heading discrepancy
def check_heading(self, m): '''check heading discrepancy''' if 'GPS_RAW' in self.status.msgs: gps = self.status.msgs['GPS_RAW'] if gps.v < 3: return diff = math.fabs(angle_diff(m.heading, gps.hdg)) elif 'GPS_RAW_INT' in self.status.msgs: gps = self.status.msgs['GPS_RAW_INT'] if gps.vel < 300: return diff = math.fabs(angle_diff(m.heading, gps.cog / 100.0)) else: return self.report('heading', diff < 20, 'heading error %u' % diff)
handle an incoming mavlink packet
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if m.get_type() == 'VFR_HUD' and ('GPS_RAW' in self.status.msgs or 'GPS_RAW_INT' in self.status.msgs): self.check_heading(m) if self.settings.speedreporting: if m.airspeed != 0: speed = m.airspeed else: speed = m.groundspeed self.report_change('speed', speed, maxdiff=2, deltat=2) if self.status.watch == "sensors" and time.time() > self.sensors_state.last_watch + 1: self.sensors_state.last_watch = time.time() self.cmd_sensors([])
generate complete python implemenation
def generate(basename, xml): '''generate complete python implemenation''' if basename.endswith('.py'): filename = basename else: filename = basename + '.py' 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 = '>' m.native_fmtstr = m.fmtstr for f in m.ordered_fields: m.fmtstr += mavfmt(f) m.native_fmtstr += native_mavfmt(f) m.order_map = [ 0 ] * len(m.fieldnames) m.len_map = [ 0 ] * len(m.fieldnames) m.array_len_map = [ 0 ] * len(m.fieldnames) for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) m.array_len_map[i] = m.ordered_fields[i].array_length for i in range(0, len(m.fieldnames)): n = m.order_map[i] m.len_map[n] = m.fieldlengths[i] print("Generating %s" % filename) outf = open(filename, "w") generate_preamble(outf, msgs, basename, filelist, xml[0]) generate_enums(outf, enums) generate_message_ids(outf, msgs) generate_classes(outf, msgs) generate_mavlink_class(outf, msgs, xml[0]) generate_methods(outf, msgs) outf.close() print("Generated %s OK" % filename)
close the window
def close(self): '''close the window''' self.close_window.release() count=0 while self.child.is_alive() and count < 30: # 3 seconds to die... time.sleep(0.1) #? count+=1 if self.child.is_alive(): self.child.terminate() self.child.join()
hide an object on the map by key
def hide_object(self, key, hide=True): '''hide an object on the map by key''' self.object_queue.put(SlipHideObject(key, hide))
move an object on the map
def set_position(self, key, latlon, layer=None, rotation=0): '''move an object on the map''' self.object_queue.put(SlipPosition(key, latlon, layer, rotation))