INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
camctrlmsg
def cmd_camctrlmsg(self, args): '''camctrlmsg''' print("Sent DIGICAM_CONFIGURE CMD_LONG") self.master.mav.command_long_send( self.settings.target_system, # target_system 0, # target_component mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONFIGURE, # command 0, # confirmation 10, # param1 20, # param2 30, # param3 40, # param4 50, # param5 60, # param6 70)
cammsg
def cmd_cammsg(self, args): '''cammsg''' print("Sent DIGICAM_CONTROL CMD_LONG") self.master.mav.command_long_send( self.settings.target_system, # target_system 0, # target_component mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL, # command 0, # confirmation 10, # param1 20, # param2 30, # param3 40, # param4 50, # param5 60, # param6 70)
yaw angle angular_speed angle_mode
def cmd_condition_yaw(self, args): '''yaw angle angular_speed angle_mode''' if ( len(args) != 3): print("Usage: yaw ANGLE ANGULAR_SPEED MODE:[0 absolute / 1 relative]") return if (len(args) == 3): angle = float(args[0]) angular_speed = float(args[1]) angle_mode = float(args[2]) print("ANGLE %s" % (str(angle))) self.master.mav.command_long_send( self.settings.target_system, # target_system mavutil.mavlink.MAV_COMP_ID_SYSTEM_CONTROL, # target_component mavutil.mavlink.MAV_CMD_CONDITION_YAW, # command 0, # confirmation angle, # param1 (angle value) angular_speed, # param2 (angular speed value) 0, # param3 angle_mode, # param4 (mode: 0->absolute / 1->relative) 0, # param5 0, # param6 0)
velocity x-ms y-ms z-ms
def cmd_velocity(self, args): '''velocity x-ms y-ms z-ms''' if (len(args) != 3): print("Usage: velocity x y z (m/s)") return if (len(args) == 3): x_mps = float(args[0]) y_mps = float(args[1]) z_mps = float(args[2]) #print("x:%f, y:%f, z:%f" % (x_mps, y_mps, z_mps)) self.master.mav.set_position_target_local_ned_send( 0, # time_boot_ms (not used) 0, 0, # target system, target component mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame 0b0000111111000111, # type_mask (only speeds enabled) 0, 0, 0, # x, y, z positions (not used) x_mps, y_mps, -z_mps, # x, y, z velocity in m/s 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink) 0, 0)
position x-m y-m z-m
def cmd_position(self, args): '''position x-m y-m z-m''' if (len(args) != 3): print("Usage: position x y z (meters)") return if (len(args) == 3): x_m = float(args[0]) y_m = float(args[1]) z_m = float(args[2]) print("x:%f, y:%f, z:%f" % (x_m, y_m, z_m)) self.master.mav.set_position_target_local_ned_send( 0, # system time in milliseconds 1, # target system 0, # target component 8, # coordinate frame MAV_FRAME_BODY_NED 3576, # type mask (pos only) x_m, y_m, z_m, # position x,y,z 0, 0, 0, # velocity x,y,z 0, 0, 0, # accel x,y,z 0, 0)
attitude q0 q1 q2 q3 thrust
def cmd_attitude(self, args): '''attitude q0 q1 q2 q3 thrust''' if len(args) != 5: print("Usage: attitude q0 q1 q2 q3 thrust (0~1)") return if len(args) == 5: q0 = float(args[0]) q1 = float(args[1]) q2 = float(args[2]) q3 = float(args[3]) thrust = float(args[4]) att_target = [q0, q1, q2, q3] print("q0:%.3f, q1:%.3f, q2:%.3f q3:%.3f thrust:%.2f" % (q0, q1, q2, q3, thrust)) self.master.mav.set_attitude_target_send( 0, # system time in milliseconds 1, # target system 0, # target component 63, # type mask (ignore all except attitude + thrust) att_target, # quaternion attitude 0, # body roll rate 0, # body pich rate 0, # body yaw rate thrust)
posvel mapclick vN vE vD
def cmd_posvel(self, args): '''posvel mapclick vN vE vD''' ignoremask = 511 latlon = None try: latlon = self.module('map').click_position except Exception: pass if latlon is None: print ("set latlon to zeros") latlon = [0, 0] else: ignoremask = ignoremask & 504 print ("found latlon", ignoremask) vN = 0 vE = 0 vD = 0 if (len(args) == 3): vN = float(args[0]) vE = float(args[1]) vD = float(args[2]) ignoremask = ignoremask & 455 print ("ignoremask",ignoremask) print (latlon) self.master.mav.set_position_target_global_int_send( 0, # system time in ms 1, # target system 0, # target component mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, ignoremask, # ignore int(latlon[0] * 1e7), int(latlon[1] * 1e7), 10, vN, vE, vD, # velocity 0, 0, 0, # accel x,y,z 0, 0)
repaint the image
def on_paint(self, event): '''repaint the image''' dc = wx.AutoBufferedPaintDC(self) dc.DrawBitmap(self._bmp, 0, 0)
set the image to be displayed
def set_image(self, img): '''set the image to be displayed''' self._bmp = wx.BitmapFromImage(img) self.SetMinSize((self._bmp.GetWidth(), self._bmp.GetHeight()))
Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under Unix
def mavgen(opts, args): """Generate mavlink message formatters and parsers (C and Python ) using options and args where args are a list of xml files. This function allows python scripts under Windows to control mavgen using the same interface as shell scripts under Unix""" xml = [] # Enable validation by default, disabling it if explicitly requested if opts.validate: try: from lxml import etree with open(schemaFile, 'r') as f: xmlschema_root = etree.parse(f) xmlschema = etree.XMLSchema(xmlschema_root) except: print("WARNING: Unable to load XML validator libraries. XML validation will not be performed", file=sys.stderr) opts.validate = False def mavgen_validate(xmlfile): """Uses lxml to validate an XML file. We define mavgen_validate here because it relies on the XML libs that were loaded in mavgen(), so it can't be called standalone""" xmlvalid = True try: with open(xmlfile, 'r') as f: xmldocument = etree.parse(f) xmlschema.assertValid(xmldocument) forbidden_names_re = re.compile("^(break$|case$|class$|catch$|const$|continue$|debugger$|default$|delete$|do$|else$|\ export$|extends$|finally$|for$|function$|if$|import$|in$|instanceof$|let$|new$|\ return$|super$|switch$|this$|throw$|try$|typeof$|var$|void$|while$|with$|yield$|\ enum$|await$|implements$|package$|protected$|static$|interface$|private$|public$|\ abstract$|boolean$|byte$|char$|double$|final$|float$|goto$|int$|long$|native$|\ short$|synchronized$|transient$|volatile$).*", re.IGNORECASE) for element in xmldocument.iter('enum', 'entry', 'message', 'field'): if forbidden_names_re.search(element.get('name')): print("Validation error:", file=sys.stderr) print("Element : %s at line : %s contains forbidden word" % (element.tag, element.sourceline), file=sys.stderr) xmlvalid = False return xmlvalid except etree.XMLSchemaError: return False # Process all XML files, validating them as necessary. for fname in args: if opts.validate: print("Validating %s" % fname) if not mavgen_validate(fname): return False else: print("Validation skipped for %s." % fname) print("Parsing %s" % fname) xml.append(mavparse.MAVXML(fname, opts.wire_protocol)) # expand includes for x in xml[:]: for i in x.include: fname = os.path.join(os.path.dirname(x.filename), i) # Validate XML file with XSD file if possible. if opts.validate: print("Validating %s" % fname) if not mavgen_validate(fname): return False else: print("Validation skipped for %s." % fname) # Parsing print("Parsing %s" % fname) xml.append(mavparse.MAVXML(fname, opts.wire_protocol)) # include message lengths and CRCs too x.message_crcs.update(xml[-1].message_crcs) x.message_lengths.update(xml[-1].message_lengths) x.message_min_lengths.update(xml[-1].message_min_lengths) x.message_flags.update(xml[-1].message_flags) x.message_target_system_ofs.update(xml[-1].message_target_system_ofs) x.message_target_component_ofs.update(xml[-1].message_target_component_ofs) x.message_names.update(xml[-1].message_names) x.largest_payload = max(x.largest_payload, xml[-1].largest_payload) # work out max payload size across all includes largest_payload = 0 for x in xml: if x.largest_payload > largest_payload: largest_payload = x.largest_payload for x in xml: x.largest_payload = largest_payload if mavparse.check_duplicates(xml): sys.exit(1) print("Found %u MAVLink message types in %u XML files" % ( mavparse.total_msgs(xml), len(xml))) # Convert language option to lowercase and validate opts.language = opts.language.lower() if opts.language == 'python': from . import mavgen_python mavgen_python.generate(opts.output, xml) elif opts.language == 'c': from . import mavgen_c mavgen_c.generate(opts.output, xml) elif opts.language == 'wlua': from . import mavgen_wlua mavgen_wlua.generate(opts.output, xml) elif opts.language == 'cs': from . import mavgen_cs mavgen_cs.generate(opts.output, xml) elif opts.language == 'javascript': from . import mavgen_javascript mavgen_javascript.generate(opts.output, xml) elif opts.language == 'objc': from . import mavgen_objc mavgen_objc.generate(opts.output, xml) elif opts.language == 'swift': from . import mavgen_swift mavgen_swift.generate(opts.output, xml) elif opts.language == 'java': from . import mavgen_java mavgen_java.generate(opts.output, xml) else: print("Unsupported language %s" % opts.language) return True
generate the python code on the fly for a MAVLink dialect
def mavgen_python_dialect(dialect, wire_protocol): '''generate the python code on the fly for a MAVLink dialect''' dialects = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'dialects') mdef = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'message_definitions') if wire_protocol == mavparse.PROTOCOL_0_9: py = os.path.join(dialects, 'v09', dialect + '.py') xml = os.path.join(dialects, 'v09', dialect + '.xml') if not os.path.exists(xml): xml = os.path.join(mdef, 'v0.9', dialect + '.xml') elif wire_protocol == mavparse.PROTOCOL_1_0: py = os.path.join(dialects, 'v10', dialect + '.py') xml = os.path.join(dialects, 'v10', dialect + '.xml') if not os.path.exists(xml): xml = os.path.join(mdef, 'v1.0', dialect + '.xml') else: py = os.path.join(dialects, 'v20', dialect + '.py') xml = os.path.join(dialects, 'v20', dialect + '.xml') if not os.path.exists(xml): xml = os.path.join(mdef, 'v1.0', dialect + '.xml') opts = Opts(py, wire_protocol) # Python 2 to 3 compatibility try: import StringIO as io except ImportError: import io # throw away stdout while generating stdout_saved = sys.stdout sys.stdout = io.StringIO() try: xml = os.path.relpath(xml) if not mavgen(opts, [xml]): sys.stdout = stdout_saved return False except Exception: sys.stdout = stdout_saved raise sys.stdout = stdout_saved return True
work out signal loss times for a log file
def sigloss(logfile): '''work out signal loss times for a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename, planner_format=args.planner, notimestamps=args.notimestamps, robust_parsing=args.robust) last_t = 0 types = args.types if types is not None: types = types.split(',') while True: m = mlog.recv_match(condition=args.condition) if m is None: return if types is not None and m.get_type() not in types: continue if args.notimestamps: if not 'usec' in m._fieldnames: continue t = m.usec / 1.0e6 else: t = m._timestamp if last_t != 0: if t - last_t > args.deltat: print("Sig lost for %.1fs at %s" % (t-last_t, time.asctime(time.localtime(t)))) last_t = t
convert a tlog to a .m file
def process_tlog(filename): '''convert a tlog to a .m file''' print("Processing %s" % filename) mlog = mavutil.mavlink_connection(filename, dialect=args.dialect, zero_time_base=True) # first walk the entire file, grabbing all messages into a hash of lists, #and the first message of each type into a hash msg_types = {} msg_lists = {} types = args.types if types is not None: types = types.split(',') # note that Octave doesn't like any extra '.', '*', '-', characters in the filename (head, tail) = os.path.split(filename) basename = '.'.join(tail.split('.')[:-1]) mfilename = re.sub('[\.\-\+\*]','_', basename) + '.m' # Octave also doesn't like files that don't start with a letter if (re.match('^[a-zA-z]', mfilename) == None): mfilename = 'm_' + mfilename if head is not None: mfilename = os.path.join(head, mfilename) print("Creating %s" % mfilename) f = open(mfilename, "w") type_counters = {} while True: m = mlog.recv_match(condition=args.condition) if m is None: break if types is not None and m.get_type() not in types: continue if m.get_type() == 'BAD_DATA': continue fieldnames = m._fieldnames mtype = m.get_type() if mtype in ['FMT', 'PARM']: continue if mtype not in type_counters: type_counters[mtype] = 0 f.write("%s.columns = {'timestamp'" % mtype) for field in fieldnames: val = getattr(m, field) if not isinstance(val, str): if type(val) is not list: f.write(",'%s'" % field) else: for i in range(0, len(val)): f.write(",'%s%d'" % (field, i + 1)) f.write("};\n") type_counters[mtype] += 1 f.write("%s.data(%u,:) = [%f" % (mtype, type_counters[mtype], m._timestamp)) for field in m._fieldnames: val = getattr(m, field) if not isinstance(val, str): if type(val) is not list: f.write(",%.20g" % val) else: for i in range(0, len(val)): f.write(",%.20g" % val[i]) f.write("];\n") f.close()
return radius give data point and offsets
def radius(d, offsets, motor_ofs): '''return radius give data point and offsets''' (mag, motor) = d return (mag + offsets + motor*motor_ofs).length()
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) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps) data = [] last_t = 0 offsets = Vector3(0,0,0) motor_ofs = Vector3(0,0,0) motor = 0.0 # now gather all the data while True: m = mlog.recv_match(condition=args.condition) if m is None: break if m.get_type() == "PARAM_VALUE" and m.param_id == "RC3_MIN": rc3_min = float(m.param_value) if m.get_type() == "SENSOR_OFFSETS": # update current offsets offsets = Vector3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z) if m.get_type() == "SERVO_OUTPUT_RAW": motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw motor_pwm *= 0.25 rc3_min = mlog.param('RC3_MIN', 1100) rc3_max = mlog.param('RC3_MAX', 1900) motor = (motor_pwm - rc3_min) / (rc3_max - rc3_min) if motor > 1.0: motor = 1.0 if motor < 0.0: motor = 0.0 if m.get_type() == "RAW_IMU": mag = Vector3(m.xmag, m.ymag, m.zmag) # add data point after subtracting the current offsets data.append((mag - offsets + noise(), motor)) print("Extracted %u data points" % len(data)) print("Current offsets: %s" % offsets) data = select_data(data) # do an initial fit with all data (offsets, motor_ofs, field_strength) = fit_data(data) for count in range(3): # sort the data by the radius data.sort(lambda a,b : radius_cmp(a,b,offsets,motor_ofs)) print("Fit %u : %s %s field_strength=%6.1f to %6.1f" % ( count, offsets, motor_ofs, radius(data[0], offsets, motor_ofs), radius(data[-1], offsets, motor_ofs))) # discard outliers, keep the middle 3/4 data = data[len(data)/8:-len(data)/8] # fit again (offsets, motor_ofs, field_strength) = fit_data(data) print("Final : %s %s field_strength=%6.1f to %6.1f" % ( offsets, motor_ofs, radius(data[0], offsets, motor_ofs), radius(data[-1], offsets, motor_ofs))) print("mavgraph.py '%s' 'mag_field(RAW_IMU)' 'mag_field_motors(RAW_IMU,SENSOR_OFFSETS,(%f,%f,%f),SERVO_OUTPUT_RAW,(%f,%f,%f))'" % ( filename, offsets.x,offsets.y,offsets.z, motor_ofs.x, motor_ofs.y, motor_ofs.z))
generate MVMavlink header and implementation
def generate_mavlink(directory, xml): '''generate MVMavlink header and implementation''' f = open(os.path.join(directory, "MVMavlink.h"), mode='w') t.write(f,''' // // MVMavlink.h // MAVLink communications protocol built from ${basename}.xml // // Created on ${parse_time} by mavgen_objc.py // http://qgroundcontrol.org/mavlink // #import "MVMessage.h" ${{message_definition_files:#import "MV${name_camel_case}Messages.h" }} @class MVMavlink; @protocol MVMessage; @protocol MVMavlinkDelegate <NSObject> /*! Method called on the delegate when a full message has been received. Note that this may be called multiple times when parseData: is called, if the data passed to parseData: contains multiple messages. @param mavlink The MVMavlink object calling this method @param message The id<MVMessage> class containing the parsed message */ - (void)mavlink:(MVMavlink *)mavlink didGetMessage:(id<MVMessage>)message; /*! Method called on the delegate when data should be sent. @param mavlink The MVMavlink object calling this method @param data NSData object containing the bytes to be sent */ - (BOOL)mavlink:(MVMavlink *)mavlink shouldWriteData:(NSData *)data; @end /*! Class for parsing and sending instances of id<MVMessage> @discussion MVMavlink receives a stream of bytes via the parseData: method and calls the delegate method mavlink:didGetMessage: each time a message is fully parsed. Users of MVMavlink can call parseData: anytime they get new data, even if that data does not contain a complete message. */ @interface MVMavlink : NSObject @property (weak, nonatomic) id<MVMavlinkDelegate> delegate; /*! Parse byte data received from a MAVLink byte stream. @param data NSData containing the received bytes */ - (void)parseData:(NSData *)data; /*! Compile MVMessage object into a bytes and pass to the delegate for sending. @param message Object conforming to the MVMessage protocol that represents the data to be sent @return YES if message sending was successful */ - (BOOL)sendMessage:(id<MVMessage>)message; @end ''', xml) f.close() f = open(os.path.join(directory, "MVMavlink.m"), mode='w') t.write(f,''' // // MVMavlink.m // MAVLink communications protocol built from ${basename}.xml // // Created by mavgen_objc.py // http://qgroundcontrol.org/mavlink // #import "MVMavlink.h" @implementation MVMavlink - (void)parseData:(NSData *)data { mavlink_message_t msg; mavlink_status_t status; char *bytes = (char *)[data bytes]; for (NSInteger i = 0; i < [data length]; ++i) { if (mavlink_parse_char(MAVLINK_COMM_0, bytes[i], &msg, &status)) { // Packet received id<MVMessage> message = [MVMessage messageWithCMessage:msg]; [_delegate mavlink:self didGetMessage:message]; } } } - (BOOL)sendMessage:(id<MVMessage>)message { return [_delegate mavlink:self shouldWriteData:[message data]]; } @end ''', xml) f.close()
generate per-message header and implementation file
def generate_message(directory, m): '''generate per-message header and implementation file''' f = open(os.path.join(directory, 'MVMessage%s.h' % m.name_camel_case), mode='w') t.write(f, ''' // // MVMessage${name_camel_case}.h // MAVLink communications protocol built from ${basename}.xml // // Created by mavgen_objc.py // http://qgroundcontrol.org/mavlink // #import "MVMessage.h" /*! Class that represents a ${name} Mavlink message. @discussion ${description} */ @interface MVMessage${name_camel_case} : MVMessage - (id)initWithSystemId:(uint8_t)systemId componentId:(uint8_t)componentId${{arg_fields: ${name_lower_camel_case}:(${arg_type}${array_prefix})${name_lower_camel_case}}}; ${{fields://! ${description} - (${return_type})${name_lower_camel_case}${get_arg_objc}; }} @end ''', m) f.close() f = open(os.path.join(directory, 'MVMessage%s.m' % m.name_camel_case), mode='w') t.write(f, ''' // // MVMessage${name_camel_case}.m // MAVLink communications protocol built from ${basename}.xml // // Created by mavgen_objc.py // http://qgroundcontrol.org/mavlink // #import "MVMessage${name_camel_case}.h" @implementation MVMessage${name_camel_case} - (id)initWithSystemId:(uint8_t)systemId componentId:(uint8_t)componentId${{arg_fields: ${name_lower_camel_case}:(${arg_type}${array_prefix})${name_lower_camel_case}}} { if ((self = [super init])) { mavlink_msg_${name_lower}_pack(systemId, componentId, &(self->_message)${{arg_fields:, ${name_lower_camel_case}}}); } return self; } ${{fields:- (${return_type})${name_lower_camel_case}${get_arg_objc} { ${return_method_implementation} } }} - (NSString *)description { return [NSString stringWithFormat:@"%@${{fields:, ${name_lower_camel_case}=${print_format}}}", [super description]${{fields:, ${get_message}}}]; } @end ''', m) f.close()
generate a CamelCase string from an underscore_string.
def camel_case_from_underscores(string): """generate a CamelCase string from an underscore_string.""" components = string.split('_') string = '' for component in components: string += component[0].upper() + component[1:] return string
generate a lower-cased camelCase string from an underscore_string. For example: my_variable_name -> myVariableName
def lower_camel_case_from_underscores(string): """generate a lower-cased camelCase string from an underscore_string. For example: my_variable_name -> myVariableName""" components = string.split('_') string = components[0] for component in components[1:]: string += component[0].upper() + component[1:] return string
generate files for one XML file
def generate_message_definitions(basename, xml): '''generate files for one XML file''' directory = os.path.join(basename, xml.basename) print("Generating Objective-C implementation in directory %s" % directory) mavparse.mkdir_p(directory) xml.basename_camel_case = camel_case_from_underscores(xml.basename) # Add some extra field attributes for convenience for m in xml.message: m.basename = xml.basename m.parse_time = xml.parse_time m.name_camel_case = camel_case_from_underscores(m.name_lower) for f in m.fields: f.name_lower_camel_case = lower_camel_case_from_underscores(f.name); f.get_message = "[self %s]" % f.name_lower_camel_case f.return_method_implementation = '' f.array_prefix = '' f.array_return_arg = '' f.get_arg = '' f.get_arg_objc = '' if f.enum: f.return_type = f.enum f.arg_type = f.enum else: f.return_type = f.type f.arg_type = f.type if f.print_format is None: if f.array_length != 0: f.print_format = "%@" elif f.type.startswith('uint64_t'): f.print_format = "%lld" elif f.type.startswith('uint') or f.type.startswith('int'): f.print_format = "%d" elif f.type.startswith('float'): f.print_format = "%f" elif f.type.startswith('char'): f.print_format = "%c" else: print("print_format unsupported for type %s" % f.type) if f.array_length != 0: f.get_message = '@"[array of %s[%d]]"' % (f.type, f.array_length) f.array_prefix = ' *' f.array_return_arg = '%s, %u, ' % (f.name, f.array_length) f.return_type = 'uint16_t' f.get_arg = ', %s' % (f.name) f.get_arg_objc = ':(%s *)%s' % (f.type, f.name) if f.type == 'char': # Special handling for strings (assumes all char arrays are strings) f.return_type = 'NSString *' f.get_arg_objc = '' f.get_message = "[self %s]" % f.name_lower_camel_case f.return_method_implementation = \ """char string[%(array_length)d]; mavlink_msg_%(message_name_lower)s_get_%(name)s(&(self->_message), (char *)&string); return [[NSString alloc] initWithBytes:string length:%(array_length)d encoding:NSASCIIStringEncoding];""" % {'array_length': f.array_length, 'message_name_lower': m.name_lower, 'name': f.name} if not f.return_method_implementation: f.return_method_implementation = \ """return mavlink_msg_%(message_name_lower)s_get_%(name)s(&(self->_message)%(get_arg)s);""" % {'message_name_lower': m.name_lower, 'name': f.name, 'get_arg': f.get_arg} for m in xml.message: m.arg_fields = [] for f in m.fields: if not f.omit_arg: m.arg_fields.append(f) generate_message_definitions_h(directory, xml) for m in xml.message: generate_message(directory, m)
generate complete MAVLink Objective-C implemenation
def generate(basename, xml_list): '''generate complete MAVLink Objective-C implemenation''' generate_shared(basename, xml_list) for xml in xml_list: generate_message_definitions(basename, xml)
Translates from JderobotTypes CMDVel to ROS Twist. @param vel: JderobotTypes CMDVel to translate @type img: JdeRobotTypes.CMDVel @return a Twist translated from vel
def cmdvel2Twist(vel): ''' Translates from JderobotTypes CMDVel to ROS Twist. @param vel: JderobotTypes CMDVel to translate @type img: JdeRobotTypes.CMDVel @return a Twist translated from vel ''' tw = TwistStamped() tw.twist.linear.x = vel.vx tw.twist.linear.y = vel.vy tw.twist.linear.z = vel.vz tw.twist.angular.x = vel.ax tw.twist.angular.y = vel.ay tw.twist.angular.z = vel.az return tw
Function to publish cmdvel.
def publish (self): ''' Function to publish cmdvel. ''' self.lock.acquire() tw = cmdvel2Twist(self.vel) self.lock.release() if (self.jdrc.getState() == "flying"): self.pub.publish(tw)
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() import matplotlib import wx_processguard from wx_loader import wx from live_graph_ui import GraphFrame matplotlib.use('WXAgg') app = wx.App(False) app.frame = GraphFrame(state=self) app.frame.Show() app.MainLoop()
add some data to the graph
def add_values(self, values): '''add some data to the graph''' if self.child.is_alive(): self.parent_pipe.send(values)
close the graph
def close(self): '''close the graph''' self.close_graph.set() if self.is_alive(): self.child.join(2)
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) mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps) flying = False gps_heading = 0.0 data = [] # get the current mag offsets m = mlog.recv_match(type='SENSOR_OFFSETS',condition=args.condition) offsets = vec3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z) attitude = mlog.recv_match(type='ATTITUDE',condition=args.condition) # now gather all the data while True: m = mlog.recv_match(condition=args.condition) if m is None: break if m.get_type() == "GPS_RAW": # flying if groundspeed more than 5 m/s flying = (m.v > args.minspeed and m.fix_type == 2) gps_heading = m.hdg if m.get_type() == "GPS_RAW_INT": # flying if groundspeed more than 5 m/s flying = (m.vel/100 > args.minspeed and m.fix_type == 3) gps_heading = m.cog/100 if m.get_type() == "ATTITUDE": attitude = m if m.get_type() == "SENSOR_OFFSETS": # update current offsets offsets = vec3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z) if not flying: continue if m.get_type() == "RAW_IMU": data.append((m.xmag - offsets.x, m.ymag - offsets.y, m.zmag - offsets.z, attitude.roll, attitude.pitch, gps_heading)) print("Extracted %u data points" % len(data)) print("Current offsets: %s" % offsets) ofs2 = fit_data(data) print("Declination estimate: %.1f" % ofs2[-1]) new_offsets = vec3(ofs2[0], ofs2[1], ofs2[2]) a = [[ofs2[3], ofs2[4], ofs2[5]], [ofs2[6], ofs2[7], ofs2[8]], [ofs2[9], ofs2[10], ofs2[11]]] print(a) print("New offsets : %s" % new_offsets)
Generate Swift file header with source files list and creation date
def generate_header(outf, filelist, xml): """Generate Swift file header with source files list and creation date""" print("Generating Swift file header") t.write(outf, """ // // MAVLink.swift // MAVLink Micro Air Vehicle Communication Protocol // // Generated from ${FILELIST} on ${PARSE_TIME} by mavgen_swift.py // http://qgroundcontrol.org/mavlink/start // import Foundation /** Common protocol for all MAVLink entities which describes type metadata properties */ public protocol MAVLinkEntity: CustomStringConvertible, CustomDebugStringConvertible { /// Original MAVLink enum name (from declarations xml) static var typeName: String { get } /// Compact type description static var typeDescription: String { get } /// Verbose type description static var typeDebugDescription: String { get } } // MARK: MAVLink enums /** Enum protocol description with common for all MAVLink enums property requirements */ public protocol Enum: RawRepresentable, Equatable, MAVLinkEntity { /// Array with all members of current enum static var allMembers: [Self] { get } // Array with `Name` - `Description` tuples (values from declarations xml file) static var membersInfo: [(String, String)] { get } /// Original MAVLinks enum member name (as declared in definitions xml file) var memberName: String { get } /// Specific member description from definitions xml var memberDescription: String { get } } /** Enum protocol default implementations */ extension Enum { public static var typeDebugDescription: String { // It seems Xcode 7 beta does not support default protocol implementations for type methods. // Calling this method without specific implementations inside enums will cause following error on Xcode 7.0 beta (7A120f): // "Command failed due to signal: Illegal instruction: 4" let cases = "\\n\\t".join(allMembers.map { $0.debugDescription }) return "Enum \(typeName): \(typeDescription)\\nMembers:\\n\\t\(cases)" } public var description: String { return memberName } public var debugDescription: String { return "\(memberName): \(memberDescription)" } public var memberName: String { return Self.membersInfo[Self.allMembers.indexOf(self)!].0 } public var memberDescription: String { return Self.membersInfo[Self.allMembers.indexOf(self)!].1 } } """, {'FILELIST' : ", ".join(filelist), 'PARSE_TIME' : xml[0].parse_time})
Iterate through all enums and create Swift equivalents
def generate_enums(outf, enums, msgs): """Iterate through all enums and create Swift equivalents""" print("Generating Enums") for enum in enums: t.write(outf, """ ${formatted_description}public enum ${swift_name}: ${raw_value_type}, Enum { ${{entry:${formatted_description}\tcase ${swift_name} = ${value}\n}} } extension ${swift_name} { public static var typeName = "${name}" public static var typeDescription = "${entity_description}" public static var typeDebugDescription: String { let cases = "\\n\\t".join(allMembers.map { $0.debugDescription }) return "Enum \(typeName): \(typeDescription)\\nMembers:\\n\\t\(cases)" } public static var allMembers = [${all_entities}] public static var membersInfo = [${entities_info}] } """, enum)
Search appropirate raw type for enums in messages fields
def get_enum_raw_type(enum, msgs): """Search appropirate raw type for enums in messages fields""" for msg in msgs: for field in msg.fields: if field.enum == enum.name: return swift_types[field.type][0] return "Int"
Generate Swift structs to represent all MAVLink messages
def generate_messages(outf, msgs): """Generate Swift structs to represent all MAVLink messages""" print("Generating Messages") t.write(outf, """ // MARK: MAVLink messages /** Message protocol describes common for all MAVLink messages properties and methods requirements */ public protocol Message: MAVLinkEntity { /** Initialize Message from received data - Warning: Throws `ParserError` or `ParserEnumError` if any parsing error occurred */ init(data: NSData) throws /// Array of tuples with fields name, offset, type and description information static var fieldsInfo: [(String, Int, String, String)] { get } /// All fields names and values of current Message var allFields: [(String, Any)] { get } } /** Message protocol default implementations */ extension Message { public static var typeDebugDescription: String { // It seems Xcode 7 beta does not support default protocol implementations for type methods. // Calling this method without specific implementations inside messages will cause following error in Xcode 7.0 beta (7A120f): // "Command failed due to signal: Illegal instruction: 4" let fields = "\\n\\t".join(fieldsInfo.map { "\($0.0): \($0.2): \($0.3)" }) return "Struct \(typeName): \(typeDescription)\\nFields:\\n\\t\(fields)" } public var description: String { let describeField: ((String, Any)) -> String = { (let name, var value) in value = value is String ? "\\"\(value)\\"" : value return "\(name): \(value)" } let fieldsDescription = ", ".join(allFields.map(describeField)) return "\(self.dynamicType)(\(fieldsDescription))" } public var debugDescription: String { let describeFieldVerbose: ((String, Any)) -> String = { (let name, var value) in value = value is String ? "\\"\(value)\\"" : value let (_, _, _, description) = Self.fieldsInfo.filter { $0.0 == name }.first! return "\(name) = \(value) : \(description)" } let fieldsDescription = "\\n\\t".join(allFields.map(describeFieldVerbose)) return "\(Self.typeName): \(Self.typeDescription)\\nFields:\\n\\t\(fieldsDescription)" } public var allFields: [(String, Any)] { var result: [(String, Any)] = [] let mirror = reflect(self) for i in 0..<mirror.count { result.append((mirror[i].0, mirror[i].1.value)) } return result } } """) for msg in msgs: t.write(outf, """ ${formatted_description}public struct ${swift_name}: Message { ${{fields:${formatted_description}\tpublic let ${swift_name}: ${return_type}\n}} public init(data: NSData) throws { ${{ordered_fields:\t\tself.${swift_name} = ${initial_value}\n}} } } extension ${swift_name} { public static var typeName = "${name}" public static var typeDescription = "${message_description}" public static var typeDebugDescription: String { let fields = "\\n\\t".join(fieldsInfo.map { "\($0.0): \($0.2): \($0.3)" }) return "Struct \(typeName): \(typeDescription)\\nFields:\\n\\t\(fields)" } public static var fieldsInfo = [${fields_info}] } """, msg)
Open and copy static code from specified file
def append_static_code(filename, outf): """Open and copy static code from specified file""" basepath = os.path.dirname(os.path.realpath(__file__)) filepath = os.path.join(basepath, 'swift/%s' % filename) print("Appending content of %s" % filename) with open(filepath) as inf: for line in inf: outf.write(line)
Create array for mapping message Ids to proper structs
def generate_message_mappings_array(outf, msgs): """Create array for mapping message Ids to proper structs""" classes = [] for msg in msgs: classes.append("%u: %s.self" % (msg.id, msg.swift_name)) t.write(outf, """ /** Array for mapping message id to proper struct */ private let messageIdToClass: [UInt8: Message.Type] = [${ARRAY_CONTENT}] """, {'ARRAY_CONTENT' : ", ".join(classes)})
Create array with message lengths to validate known message lengths
def generate_message_lengths_array(outf, msgs): """Create array with message lengths to validate known message lengths""" # form message lengths array lengths = [] for msg in msgs: lengths.append("%u: %u" % (msg.id, msg.wire_length)) t.write(outf, """ /** Message lengths array for known messages length validation */ private let messageLengths: [UInt8: UInt8] = [${ARRAY_CONTENT}] """, {'ARRAY_CONTENT' : ", ".join(lengths)})
Add array with CRC extra values to detect incompatible XML changes
def generate_message_crc_extra_array(outf, msgs): """Add array with CRC extra values to detect incompatible XML changes""" crcs = [] for msg in msgs: crcs.append("%u: %u" % (msg.id, msg.crc_extra)) t.write(outf, """ /** Message CRSs extra for detection incompatible XML changes */ private let messageCrcsExtra: [UInt8: UInt8] = [${ARRAY_CONTENT}] """, {'ARRAY_CONTENT' : ", ".join(crcs)})
Generate a CamelCase string from an underscore_string
def camel_case_from_underscores(string): """Generate a CamelCase string from an underscore_string""" components = string.split('_') string = '' for component in components: if component in abbreviations: string += component else: string += component[0].upper() + component[1:].lower() return string
Add camel case swift names for enums an entries, descriptions and sort enums alphabetically
def generate_enums_info(enums, msgs): """Add camel case swift names for enums an entries, descriptions and sort enums alphabetically""" for enum in enums: enum.swift_name = camel_case_from_underscores(enum.name) enum.raw_value_type = get_enum_raw_type(enum, msgs) enum.formatted_description = "" if enum.description: enum.description = " ".join(enum.description.split()) enum.formatted_description = "\n/**\n %s\n*/\n" % enum.description all_entities = [] entities_info = [] for entry in enum.entry: name = entry.name.replace(enum.name + '_', '') """Ensure that enums entry name does not start from digit""" if name[0].isdigit(): name = "MAV_" + name entry.swift_name = camel_case_from_underscores(name) entry.formatted_description = "" if entry.description: entry.description = " ".join(entry.description.split()) entry.formatted_description = "\n\t/// " + entry.description + "\n" all_entities.append(entry.swift_name) entities_info.append('("%s", "%s")' % (entry.name, entry.description.replace('"','\\"'))) enum.all_entities = ", ".join(all_entities) enum.entities_info = ", ".join(entities_info) enum.entity_description = enum.description.replace('"','\\"') enums.sort(key = lambda enum : enum.swift_name)
Add proper formated variable names, initializers and type names to use in templates
def generate_messages_info(msgs): """Add proper formated variable names, initializers and type names to use in templates""" for msg in msgs: msg.swift_name = camel_case_from_underscores(msg.name) msg.formatted_description = "" if msg.description: msg.description = " ".join(msg.description.split()) msg.formatted_description = "\n/**\n %s\n*/\n" % " ".join(msg.description.split()) msg.message_description = msg.description.replace('"','\\"') for field in msg.ordered_fields: field.swift_name = lower_camel_case_from_underscores(field.name) field.return_type = swift_types[field.type][0] # configure fields initializers if field.enum: # handle enums field.return_type = camel_case_from_underscores(field.enum) field.initial_value = "try data.mavEnumeration(offset: %u)" % field.wire_offset elif field.array_length > 0: if field.return_type == "String": # handle strings field.initial_value = "data." + swift_types[field.type][2] % (field.wire_offset, field.array_length) else: # other array types field.return_type = "[%s]" % field.return_type field.initial_value = "try data.mavArray(offset: %u, count: %u)" % (field.wire_offset, field.array_length) else: # simple type field field.initial_value = "try data." + swift_types[field.type][2] % field.wire_offset field.formatted_description = "" if field.description: field.description = " ".join(field.description.split()) field.formatted_description = "\n\t/// " + field.description + "\n" fields_info = map(lambda field: '("%s", %u, "%s", "%s")' % (field.swift_name, field.wire_offset, field.return_type, field.description.replace('"','\\"')), msg.fields) msg.fields_info = ", ".join(fields_info) msgs.sort(key = lambda msg : msg.id)
Generate complete MAVLink Swift implemenation
def generate(basename, xml_list): """Generate complete MAVLink Swift implemenation""" if os.path.isdir(basename): filename = os.path.join(basename, 'MAVLink.swift') else: filename = basename msgs = [] enums = [] filelist = [] for xml in xml_list: msgs.extend(xml.message) enums.extend(xml.enum) filelist.append(os.path.basename(xml.filename)) outf = open(filename, "w") generate_header(outf, filelist, xml_list) generate_enums_info(enums, msgs) generate_enums(outf, enums, msgs) generate_messages_info(msgs) generate_messages(outf, msgs) append_static_code('Parser.swift', outf) generate_message_mappings_array(outf, msgs) generate_message_lengths_array(outf, msgs) generate_message_crc_extra_array(outf, msgs) outf.close()
Updates LaserData.
def update(self): ''' Updates LaserData. ''' if self.hasproxy(): sonarD = SonarData() range = 0 data = self.proxy.getSonarData() sonarD.range = data.range sonarD.maxAngle = data.maxAngle sonarD.minAngle = data.minAngle sonarD.maxRange = data.maxRange sonarD.minRange = data.minRange self.lock.acquire() self.sonar = sonarD self.lock.release()
Returns last LaserData. @return last JdeRobotTypes LaserData saved
def getSonarData(self): ''' Returns last LaserData. @return last JdeRobotTypes LaserData saved ''' if self.hasproxy(): self.lock.acquire() sonar = self.sonar self.lock.release() return sonar return None
return true if waypoint is a loiter waypoint
def wp_is_loiter(self, i): '''return true if waypoint is a loiter waypoint''' loiter_cmds = [mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM, mavutil.mavlink.MAV_CMD_NAV_LOITER_TURNS, mavutil.mavlink.MAV_CMD_NAV_LOITER_TIME, mavutil.mavlink.MAV_CMD_NAV_LOITER_TO_ALT] if (self.wpoints[i].command in loiter_cmds): return True return False
add a waypoint
def add(self, w, comment=''): '''add a waypoint''' w = copy.copy(w) if comment: w.comment = comment w.seq = self.count() self.wpoints.append(w) self.last_change = time.time()
insert a waypoint
def insert(self, idx, w, comment=''): '''insert a waypoint''' if idx >= self.count(): self.add(w, comment) return if idx < 0: return w = copy.copy(w) if comment: w.comment = comment w.seq = idx self.wpoints.insert(idx, w) self.last_change = time.time() self.reindex()
reindex waypoints
def reindex(self): '''reindex waypoints''' for i in range(self.count()): w = self.wpoints[i] w.seq = i self.last_change = time.time()
add a point via latitude/longitude/altitude
def add_latlonalt(self, lat, lon, altitude, terrain_alt=False): '''add a point via latitude/longitude/altitude''' if terrain_alt: frame = mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT else: frame = mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT p = mavutil.mavlink.MAVLink_mission_item_message(self.target_system, self.target_component, 0, frame, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, lat, lon, altitude) self.add(p)
set a waypoint
def set(self, w, idx): '''set a waypoint''' w.seq = idx if w.seq == self.count(): return self.add(w) if self.count() <= idx: raise MAVWPError('adding waypoint at idx=%u past end of list (count=%u)' % (idx, self.count())) self.wpoints[idx] = w self.last_change = time.time()
remove a waypoint
def remove(self, w): '''remove a waypoint''' self.wpoints.remove(w) self.last_change = time.time() self.reindex()
read a version 100 waypoint
def _read_waypoints_v100(self, file): '''read a version 100 waypoint''' cmdmap = { 2 : mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 3 : mavutil.mavlink.MAV_CMD_NAV_RETURN_TO_LAUNCH, 4 : mavutil.mavlink.MAV_CMD_NAV_LAND, 24: mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 26: mavutil.mavlink.MAV_CMD_NAV_LAND, 25: mavutil.mavlink.MAV_CMD_NAV_WAYPOINT , 27: mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM } comment = '' for line in file: if line.startswith('#'): comment = line[1:].lstrip() continue line = line.strip() if not line: continue a = line.split() if len(a) != 13: raise MAVWPError("invalid waypoint line with %u values" % len(a)) if mavutil.mavlink10(): fn = mavutil.mavlink.MAVLink_mission_item_message else: fn = mavutil.mavlink.MAVLink_waypoint_message w = fn(self.target_system, self.target_component, int(a[0]), # seq int(a[1]), # frame int(a[2]), # action int(a[7]), # current int(a[12]), # autocontinue float(a[5]), # param1, float(a[6]), # param2, float(a[3]), # param3 float(a[4]), # param4 float(a[9]), # x, latitude float(a[8]), # y, longitude float(a[10]) # z ) if not w.command in cmdmap: raise MAVWPError("Unknown v100 waypoint action %u" % w.command) w.command = cmdmap[w.command] self.add(w, comment) comment = ''
read a version 110 waypoint
def _read_waypoints_v110(self, file): '''read a version 110 waypoint''' comment = '' for line in file: if line.startswith('#'): comment = line[1:].lstrip() continue line = line.strip() if not line: continue a = line.split() if len(a) != 12: raise MAVWPError("invalid waypoint line with %u values" % len(a)) if mavutil.mavlink10(): fn = mavutil.mavlink.MAVLink_mission_item_message else: fn = mavutil.mavlink.MAVLink_waypoint_message w = fn(self.target_system, self.target_component, int(a[0]), # seq int(a[2]), # frame int(a[3]), # command int(a[1]), # current int(a[11]), # autocontinue float(a[4]), # param1, float(a[5]), # param2, float(a[6]), # param3 float(a[7]), # param4 float(a[8]), # x (latitude) float(a[9]), # y (longitude) float(a[10]) # z (altitude) ) if w.command == 0 and w.seq == 0 and self.count() == 0: # special handling for Mission Planner created home wp w.command = mavutil.mavlink.MAV_CMD_NAV_WAYPOINT self.add(w, comment) comment = ''
load waypoints from a file. returns number of waypoints loaded
def load(self, filename): '''load waypoints from a file. returns number of waypoints loaded''' f = open(filename, mode='r') version_line = f.readline().strip() if version_line == "QGC WPL 100": readfn = self._read_waypoints_v100 elif version_line == "QGC WPL 110": readfn = self._read_waypoints_v110 elif version_line == "QGC WPL PB 110": readfn = self._read_waypoints_pb_110 else: f.close() raise MAVWPError("Unsupported waypoint format '%s'" % version_line) self.clear() readfn(f) f.close() return len(self.wpoints)
save waypoints to a file
def save(self, filename): '''save waypoints to a file''' f = open(filename, mode='w') f.write("QGC WPL 110\n") for w in self.wpoints: if getattr(w, 'comment', None): f.write("# %s\n" % w.comment) f.write("%u\t%u\t%u\t%u\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%u\n" % ( w.seq, w.current, w.frame, w.command, w.param1, w.param2, w.param3, w.param4, w.x, w.y, w.z, w.autocontinue)) f.close()
see if cmd is a MAV_CMD with a latitide/longitude. We check if it has Latitude and Longitude params in the right indexes
def is_location_command(self, cmd): '''see if cmd is a MAV_CMD with a latitide/longitude. We check if it has Latitude and Longitude params in the right indexes''' mav_cmd = mavutil.mavlink.enums['MAV_CMD'] if not cmd in mav_cmd: return False if not mav_cmd[cmd].param.get(5,'').startswith('Latitude'): return False if not mav_cmd[cmd].param.get(6,'').startswith('Longitude'): return False return True
return a list waypoint indexes in view order
def view_indexes(self, done=None): '''return a list waypoint indexes in view order''' ret = [] if done is None: done = set() idx = 0 # find first point not done yet while idx < self.count(): if not idx in done: break idx += 1 while idx < self.count(): w = self.wp(idx) if idx in done: if w.x != 0 or w.y != 0: ret.append(idx) break done.add(idx) if w.command == mavutil.mavlink.MAV_CMD_DO_JUMP: idx = int(w.param1) w = self.wp(idx) if w.x != 0 or w.y != 0: ret.append(idx) continue if (w.x != 0 or w.y != 0) and self.is_location_command(w.command): ret.append(idx) idx += 1 return ret
return a polygon for the waypoints
def polygon(self, done=None): '''return a polygon for the waypoints''' indexes = self.view_indexes(done) points = [] for idx in indexes: w = self.wp(idx) points.append((w.x, w.y)) return points
return a list of polygons for the waypoints
def polygon_list(self): '''return a list of polygons for the waypoints''' done = set() ret = [] while len(done) != self.count(): p = self.polygon(done) if len(p) > 0: ret.append(p) return ret
return a list of polygon indexes lists for the waypoints
def view_list(self): '''return a list of polygon indexes lists for the waypoints''' done = set() ret = [] while len(done) != self.count(): p = self.view_indexes(done) if len(p) > 0: ret.append(p) return ret
reset counters and indexes
def reindex(self): '''reset counters and indexes''' for i in range(self.rally_count()): self.rally_points[i].count = self.rally_count() self.rally_points[i].idx = i self.last_change = time.time()
add rallypoint to end of list
def append_rally_point(self, p): '''add rallypoint to end of list''' if (self.rally_count() > 9): print("Can't have more than 10 rally points, not adding.") return self.rally_points.append(p) self.reindex()
add a point via latitude/longitude
def create_and_append_rally_point(self, lat, lon, alt, break_alt, land_dir, flags): '''add a point via latitude/longitude''' p = mavutil.mavlink.MAVLink_rally_point_message(self.target_system, self.target_component, self.rally_count(), 0, lat, lon, alt, break_alt, land_dir, flags) self.append_rally_point(p)
remove a rally point
def remove(self, i): '''remove a rally point''' if i < 1 or i > self.rally_count(): print("Invalid rally point number %u" % i) self.rally_points.pop(i-1) self.reindex()
move a rally point
def move(self, i, lat, lng, change_time=True): '''move a rally point''' if i < 1 or i > self.rally_count(): print("Invalid rally point number %u" % i) self.rally_points[i-1].lat = int(lat*1e7) self.rally_points[i-1].lng = int(lng*1e7) if change_time: self.last_change = time.time()
set rally point altitude(s)
def set_alt(self, i, alt, break_alt=None, change_time=True): '''set rally point altitude(s)''' if i < 1 or i > self.rally_count(): print("Inavlid rally point number %u" % i) return self.rally_points[i-1].alt = int(alt) if (break_alt != None): self.rally_points[i-1].break_alt = break_alt if change_time: self.last_change = time.time()
load rally and rally_land points from a file. returns number of points loaded
def load(self, filename): '''load rally and rally_land points from a file. returns number of points loaded''' f = open(filename, mode='r') self.clear() for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 7: raise MAVRallyError("invalid rally file line: %s" % line) if (a[0].lower() == "rally"): self.create_and_append_rally_point(float(a[1]) * 1e7, float(a[2]) * 1e7, float(a[3]), float(a[4]), float(a[5]) * 100.0, int(a[6])) f.close() return len(self.rally_points)
save fence points to a file
def save(self, filename): '''save fence points to a file''' f = open(filename, mode='w') for p in self.rally_points: f.write("RALLY %f\t%f\t%f\t%f\t%f\t%d\n" % (p.lat * 1e-7, p.lng * 1e-7, p.alt, p.break_alt, p.land_dir, p.flags)) f.close()
reindex waypoints
def reindex(self): '''reindex waypoints''' for i in range(self.count()): w = self.points[i] w.idx = i w.count = self.count() w.target_system = self.target_system w.target_component = self.target_component self.last_change = time.time()
add a point via latitude/longitude
def add_latlon(self, lat, lon): '''add a point via latitude/longitude''' p = mavutil.mavlink.MAVLink_fence_point_message(self.target_system, self.target_component, self.count(), 0, lat, lon) self.add(p)
load points from a file. returns number of points loaded
def load(self, filename): '''load points from a file. returns number of points loaded''' f = open(filename, mode='r') self.clear() for line in f: if line.startswith('#'): continue line = line.strip() if not line: continue a = line.split() if len(a) != 2: raise MAVFenceError("invalid fence point line: %s" % line) self.add_latlon(float(a[0]), float(a[1])) f.close() return len(self.points)
save fence points to a file
def save(self, filename): '''save fence points to a file''' f = open(filename, mode='w') for p in self.points: f.write("%f\t%f\n" % (p.lat, p.lng)) f.close()
move a fence point
def move(self, i, lat, lng, change_time=True): '''move a fence point''' if i < 0 or i >= self.count(): print("Invalid fence point number %u" % i) self.points[i].lat = lat self.points[i].lng = lng # ensure we close the polygon if i == 1: self.points[self.count()-1].lat = lat self.points[self.count()-1].lng = lng if i == self.count() - 1: self.points[1].lat = lat self.points[1].lng = lng if change_time: self.last_change = time.time()
remove a fence point
def remove(self, i, change_time=True): '''remove a fence point''' if i < 0 or i >= self.count(): print("Invalid fence point number %u" % i) self.points.pop(i) # ensure we close the polygon if i == 1: self.points[self.count()-1].lat = self.points[1].lat self.points[self.count()-1].lng = self.points[1].lng if i == self.count(): self.points[1].lat = self.points[self.count()-1].lat self.points[1].lng = self.points[self.count()-1].lng if change_time: self.last_change = time.time()
return a polygon for the fence
def polygon(self): '''return a polygon for the fence''' points = [] for fp in self.points[1:]: points.append((fp.lat, fp.lng)) return points
add some command input to be processed
def add_input(cmd, immediate=False): '''add some command input to be processed''' if immediate: process_stdin(cmd) else: mpstate.input_queue.put(cmd)
set a parameter
def param_set(name, value, retries=3): '''set a parameter''' name = name.upper() return mpstate.mav_param.mavset(mpstate.master(), name, value, retries=retries)
show status
def cmd_status(args): '''show status''' if len(args) == 0: mpstate.status.show(sys.stdout, pattern=None) else: for pattern in args: mpstate.status.show(sys.stdout, pattern=pattern)
unload a module
def unload_module(modname): '''unload a module''' for (m,pm) in mpstate.modules: if m.name == modname: if hasattr(m, 'unload'): m.unload() mpstate.modules.remove((m,pm)) print("Unloaded module %s" % modname) return True print("Unable to find module %s" % modname) return False
alias commands
def cmd_alias(args): '''alias commands''' usage = "usage: alias <add|remove|list>" if len(args) < 1 or args[0] == "list": if len(args) >= 2: wildcard = args[1].upper() else: wildcard = '*' for a in sorted(mpstate.aliases.keys()): if fnmatch.fnmatch(a.upper(), wildcard): print("%-15s : %s" % (a, mpstate.aliases[a])) elif args[0] == "add": if len(args) < 3: print(usage) return a = args[1] mpstate.aliases[a] = ' '.join(args[2:]) elif args[0] == "remove": if len(args) != 2: print(usage) return a = args[1] if a in mpstate.aliases: mpstate.aliases.pop(a) else: print("no alias %s" % a) else: print(usage) return
Clear out cached entries from _zip_directory_cache. See http://www.digi.com/wiki/developer/index.php/Error_messages
def clear_zipimport_cache(): """Clear out cached entries from _zip_directory_cache. See http://www.digi.com/wiki/developer/index.php/Error_messages""" import sys, zipimport syspath_backup = list(sys.path) zipimport._zip_directory_cache.clear() # load back items onto sys.path sys.path = syspath_backup # add this too: see https://mail.python.org/pipermail/python-list/2005-May/353229.html sys.path_importer_cache.clear()
Given a package name like 'foo.bar.quux', imports the package and returns the desired module.
def import_package(name): """Given a package name like 'foo.bar.quux', imports the package and returns the desired module.""" import zipimport try: mod = __import__(name) except ImportError: clear_zipimport_cache() mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
handle commands from user
def process_stdin(line): '''handle commands from user''' if line is None: sys.exit(0) # allow for modules to override input handling if mpstate.functions.input_handler is not None: mpstate.functions.input_handler(line) return line = line.strip() if mpstate.status.setup_mode: # in setup mode we send strings straight to the master if line == '.': mpstate.status.setup_mode = False mpstate.status.flightmode = "MAV" mpstate.rl.set_prompt("MAV> ") return if line != '+++': line += '\r' for c in line: time.sleep(0.01) mpstate.master().write(c) return if not line: return args = shlex.split(line) cmd = args[0] while cmd in mpstate.aliases: line = mpstate.aliases[cmd] args = shlex.split(line) + args[1:] cmd = args[0] if cmd == 'help': k = command_map.keys() #k.sort() for cmd in k: (fn, help) = command_map[cmd] print("%-15s : %s" % (cmd, help)) return if cmd == 'exit' and mpstate.settings.requireexit: mpstate.status.exit = True return ###################################################################################################### if cmd == 'velocity' and len(args) == 4: PH_CMDVel = CMDVelI(args[1],args[2],args[3],0,0,0) #1 to avoid indeterminations ###################################################################################################### if not cmd in command_map: for (m,pm) in mpstate.modules: if hasattr(m, 'unknown_command'): try: if m.unknown_command(args): return except Exception as e: print("ERROR in command: %s" % str(e)) print("Unknown command '%s'" % line) return (fn, help) = command_map[cmd] try: fn(args[1:]) except Exception as e: print("ERROR in command %s: %s" % (args[1:], str(e))) if mpstate.settings.moddebug > 1: traceback.print_exc()
process packets from the MAVLink master
def process_master(m): '''process packets from the MAVLink master''' try: s = m.recv(16*1024) except Exception: time.sleep(0.1) return # prevent a dead serial port from causing the CPU to spin. The user hitting enter will # cause it to try and reconnect if len(s) == 0: time.sleep(0.1) return if (mpstate.settings.compdebug & 1) != 0: return if mpstate.logqueue_raw: mpstate.logqueue_raw.put(str(s)) if mpstate.status.setup_mode: if mpstate.system == 'Windows': # strip nsh ansi codes s = s.replace("\033[K","") sys.stdout.write(str(s)) sys.stdout.flush() return if m.first_byte and opts.auto_protocol: m.auto_mavlink_version(s) msgs = m.mav.parse_buffer(s) if msgs: for msg in msgs: sysid = msg.get_srcSystem() if sysid in mpstate.sysid_outputs: # the message has been handled by a specialised handler for this system continue if getattr(m, '_timestamp', None) is None: m.post_message(msg) if msg.get_type() == "BAD_DATA": if opts.show_errors: mpstate.console.writeln("MAV error: %s" % msg) mpstate.status.mav_error += 1
open log files
def open_telemetry_logs(logpath_telem, logpath_telem_raw): '''open log files''' if opts.append_log or opts.continue_mode: mode = 'a' else: mode = 'w' mpstate.logfile = open(logpath_telem, mode=mode) mpstate.logfile_raw = open(logpath_telem_raw, mode=mode) print("Log Directory: %s" % mpstate.status.logdir) print("Telemetry log: %s" % logpath_telem) # use a separate thread for writing to the logfile to prevent # delays during disk writes (important as delays can be long if camera # app is running) t = threading.Thread(target=log_writer, name='log_writer') t.daemon = True t.start()
set mavlink stream rates
def set_stream_rates(): '''set mavlink stream rates''' if (not msg_period.trigger() and mpstate.status.last_streamrate1 == mpstate.settings.streamrate and mpstate.status.last_streamrate2 == mpstate.settings.streamrate2): return mpstate.status.last_streamrate1 = mpstate.settings.streamrate mpstate.status.last_streamrate2 = mpstate.settings.streamrate2 for master in mpstate.mav_master: if master.linknum == 0: rate = mpstate.settings.streamrate else: rate = mpstate.settings.streamrate2 if rate != -1: master.mav.request_data_stream_send(mpstate.settings.target_system, mpstate.settings.target_component, mavutil.mavlink.MAV_DATA_STREAM_ALL, rate, 1)
check status of master links
def check_link_status(): '''check status of master links''' tnow = time.time() if mpstate.status.last_message != 0 and tnow > mpstate.status.last_message + 5: say("no link") mpstate.status.heartbeat_error = True for master in mpstate.mav_master: if not master.linkerror and (tnow > master.last_message + 5 or master.portdead): say("link %u down" % (master.linknum+1)) master.linkerror = True
run periodic checks
def periodic_tasks(): '''run periodic checks''' if mpstate.status.setup_mode: return if (mpstate.settings.compdebug & 2) != 0: return if mpstate.settings.heartbeat != 0: heartbeat_period.frequency = mpstate.settings.heartbeat if heartbeat_period.trigger() and mpstate.settings.heartbeat != 0: mpstate.status.counters['MasterOut'] += 1 for master in mpstate.mav_master: send_heartbeat(master) if heartbeat_check_period.trigger(): check_link_status() set_stream_rates() # call optional module idle tasks. These are called at several hundred Hz for (m,pm) in mpstate.modules: if hasattr(m, 'idle_task'): try: m.idle_task() except Exception as msg: if mpstate.settings.moddebug == 1: print(msg) elif 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) # also see if the module should be unloaded: if m.needs_unloading: unload_module(m.name)
wait for user input
def input_loop(): '''wait for user input''' global operation_takeoff global time_init_operation_takeoff global time_end_operation_takeoff while mpstate.status.exit != True: try: if mpstate.status.exit != True: if mpstate.udp.bound(): line = mpstate.udp.readln() mpstate.udp.writeln(line) elif mpstate.tcp.connected(): line = mpstate.tcp.readln() mpstate.tcp.writeln(line) else: line = input(mpstate.rl.prompt) if line == 'takeoff': print("Detecto takeoff") operation_takeoff=True time_init_operation_takeoff = int(round(time.time() * 1000)) time_end_operation_takeoff = time_init_operation_takeoff + 5000 print(time_end_operation_takeoff) mpstate.input_queue.put("arm throttle") return if line == 'land': print("Orden de aterrizar") on_air = False except EOFError: mpstate.status.exit = True sys.exit(1) mpstate.input_queue.put(line)
write status to status.txt
def show(self, f, pattern=None): '''write status to status.txt''' if pattern is None: f.write('Counters: ') for c in self.counters: f.write('%s:%s ' % (c, self.counters[c])) f.write('\n') f.write('MAV Errors: %u\n' % self.mav_error) f.write(str(self.gps)+'\n') for m in sorted(self.msgs.keys()): if pattern is not None and not fnmatch.fnmatch(str(m).upper(), pattern.upper()): continue f.write("%u: %s\n" % (self.msg_count[m], str(self.msgs[m])))
run a script file
def run_script(scriptfile): '''run a script file''' try: f = open(scriptfile, mode='r') except Exception: return mpstate.console.writeln("Running script %s" % scriptfile) for line in f: line = line.strip() if line == "" or line.startswith('#'): continue if line.startswith('@'): line = line[1:] else: mpstate.console.writeln("-> %s" % line) process_stdin(line) f.close()
write status to status.txt
def write(self): '''write status to status.txt''' f = open('status.txt', mode='w') self.show(f) f.close()
return the currently chosen mavlink master object
def master(self): '''return the currently chosen mavlink master object''' if len(self.mav_master) == 0: return None if self.settings.link > len(self.mav_master): self.settings.link = 1 # try to use one with no link error if not self.mav_master[self.settings.link-1].linkerror: return self.mav_master[self.settings.link-1] for m in self.mav_master: if not m.linkerror: return m return self.mav_master[self.settings.link-1]
display fft for raw ACC data in logfile
def fft(logfile): '''display fft for raw ACC data in logfile''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename) data = {'ACC1.rate' : 1000, 'ACC2.rate' : 1600, 'ACC3.rate' : 1000, 'GYR1.rate' : 1000, 'GYR2.rate' : 800, 'GYR3.rate' : 1000} for acc in ['ACC1','ACC2','ACC3']: for ax in ['AccX', 'AccY', 'AccZ']: data[acc+'.'+ax] = [] for gyr in ['GYR1','GYR2','GYR3']: for ax in ['GyrX', 'GyrY', 'GyrZ']: data[gyr+'.'+ax] = [] # now gather all the data while True: m = mlog.recv_match(condition=args.condition) if m is None: break type = m.get_type() if type.startswith("ACC"): data[type+'.AccX'].append(m.AccX) data[type+'.AccY'].append(m.AccY) data[type+'.AccZ'].append(m.AccZ) if type.startswith("GYR"): data[type+'.GyrX'].append(m.GyrX) data[type+'.GyrY'].append(m.GyrY) data[type+'.GyrZ'].append(m.GyrZ) print("Extracted %u data points" % len(data['ACC1.AccX'])) for msg in ['ACC1', 'ACC2', 'ACC3', 'GYR1', 'GYR2', 'GYR3']: pylab.figure() if msg.startswith('ACC'): prefix = 'Acc' else: prefix = 'Gyr' for axis in ['X', 'Y', 'Z']: field = msg + '.' + prefix + axis d = data[field] if args.sample_length != 0: d = d[0:args.sample_length] d = numpy.array(d) if len(d) == 0: continue avg = numpy.sum(d) / len(d) d -= avg d_fft = numpy.fft.rfft(d) freq = numpy.fft.rfftfreq(len(d), 1.0 / data[msg+'.rate']) pylab.plot( freq, numpy.abs(d_fft), label=field ) pylab.legend(loc='upper right')
called on idle
def idle_task(self): '''called on idle''' if self.module('console') is not None and not self.menu_added_console: self.menu_added_console = True self.module('console').add_menu(self.menu)
help commands
def cmd_help(self, args): '''help commands''' if len(args) < 1: self.print_usage() return if args[0] == "about": print("MAVProxy Version " + self.version + "\nOS: " + self.host + "\nPython " + self.pythonversion) elif args[0] == "site": print("See http://dronecode.github.io/MAVProxy/ for documentation") else: self.print_usage()
generate complete MAVLink CSharp implemenation
def generate(basename, xml): '''generate complete MAVLink CSharp implemenation''' structsfilename = basename + '.generated.cs' 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: m.order_map = [ 0 ] * len(m.fieldnames) for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) m.fields_in_order = [] for i in range(0, len(m.fieldnames)): m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i]) print("Generating messages file: %s" % structsfilename) dir = os.path.dirname(structsfilename) if not os.path.exists(dir): os.makedirs(dir) outf = open(structsfilename, "w") generate_preamble(outf, msgs, filelist, xml[0]) outf.write(""" using System.Reflection; [assembly: AssemblyTitle("Mavlink Classes")] [assembly: AssemblyDescription("Generated Message Classes for Mavlink. See http://qgroundcontrol.org/mavlink/start")] [assembly: AssemblyProduct("Mavlink")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] """) generate_enums(outf, enums) generate_classes(outf, msgs) outf.close() print("Generating the (De)Serializer classes") serfilename = basename + '_codec.generated.cs' outf = open(serfilename, "w") generate_CodecIndex(outf, msgs, xml) generate_Deserialization(outf, msgs) generate_Serialization(outf, msgs) outf.write("\t}\n\n") outf.write("}\n\n") outf.close() # Some build commands depend on the platform - eg MS .NET Windows Vs Mono on Linux if platform.system() == "Windows": winpath=os.environ['WinDir'] cscCommand = winpath + "\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe" if (os.path.exists(cscCommand)==False): print("\nError: CS compiler not found. .Net Assembly generation skipped") return else: print("Error:.Net Assembly generation not yet supported on non Windows platforms") return cscCommand = "csc" print("Compiling Assembly for .Net Framework 4.0") generatedCsFiles = [ serfilename, structsfilename] includedCsFiles = [ 'CS/common/ByteArrayUtil.cs', 'CS/common/FrameworkBitConverter.cs', 'CS/common/Mavlink.cs' ] outputLibraryPath = os.path.normpath(dir + "/mavlink.dll") compileCommand = "%s %s" % (cscCommand, "/target:library /debug /out:" + outputLibraryPath) compileCommand = compileCommand + " /doc:" + os.path.normpath(dir + "/mavlink.xml") for csFile in generatedCsFiles + includedCsFiles: compileCommand = compileCommand + " " + os.path.normpath(csFile) #print("Cmd:" + compileCommand) res = os.system (compileCommand) if res == '0': print("Generated %s OK" % filename) else: print("Error")
Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string
def load_stylesheet(pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file if pyside: import qdarkstyle.pyside_style_rc else: import qdarkstyle.pyqt_style_rc # Load the stylesheet content from resources if not pyside: from PyQt4.QtCore import QFile, QTextStream else: from PySide.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string
def load_stylesheet_pyqt5(): """ Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file import qdarkstyle.pyqt5_style_rc # Load the stylesheet content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
optionally call a handler function
def call_handler(self): '''optionally call a handler function''' if self.handler is None: return call = getattr(self.handler, 'call', None) if call is not None: self.handler_result = call()
append this menu item to a menu
def _append(self, menu): '''append this menu item to a menu''' menu.Append(self.id(), self.name, self.description)
find the selected menu item
def find_selected(self, event): '''find the selected menu item''' if event.GetId() == self.id(): self.checked = event.IsChecked() return self return None
append this menu item to a menu
def _append(self, menu): '''append this menu item to a menu''' menu.AppendCheckItem(self.id(), self.name, self.description) menu.Check(self.id(), self.checked)