idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
41,400
def earth_rates ( ATTITUDE ) : from math import sin , cos , tan , fabs p = ATTITUDE . rollspeed q = ATTITUDE . pitchspeed r = ATTITUDE . yawspeed phi = ATTITUDE . roll theta = ATTITUDE . pitch psi = ATTITUDE . yaw phiDot = p + tan ( theta ) * ( q * sin ( phi ) + r * cos ( phi ) ) thetaDot = q * cos ( phi ) - r * sin ( phi ) if fabs ( cos ( theta ) ) < 1.0e-20 : theta += 1.0e-10 psiDot = ( q * sin ( phi ) + r * cos ( phi ) ) / cos ( theta ) return ( phiDot , thetaDot , psiDot )
return angular velocities in earth frame
41,401
def gps_velocity_body ( GPS_RAW_INT , ATTITUDE ) : r = rotation ( ATTITUDE ) return r . transposed ( ) * Vector3 ( GPS_RAW_INT . vel * 0.01 * cos ( radians ( GPS_RAW_INT . cog * 0.01 ) ) , GPS_RAW_INT . vel * 0.01 * sin ( radians ( GPS_RAW_INT . cog * 0.01 ) ) , - tan ( ATTITUDE . pitch ) * GPS_RAW_INT . vel * 0.01 )
return GPS velocity vector in body frame
41,402
def earth_accel ( RAW_IMU , ATTITUDE ) : r = rotation ( ATTITUDE ) accel = Vector3 ( RAW_IMU . xacc , RAW_IMU . yacc , RAW_IMU . zacc ) * 9.81 * 0.001 return r * accel
return earth frame acceleration vector
41,403
def earth_gyro ( RAW_IMU , ATTITUDE ) : r = rotation ( ATTITUDE ) accel = Vector3 ( degrees ( RAW_IMU . xgyro ) , degrees ( RAW_IMU . ygyro ) , degrees ( RAW_IMU . zgyro ) ) * 0.001 return r * accel
return earth frame gyro vector
41,404
def airspeed_energy_error ( NAV_CONTROLLER_OUTPUT , VFR_HUD ) : aspeed_cm = VFR_HUD . airspeed * 100 target_airspeed = NAV_CONTROLLER_OUTPUT . aspd_error + aspeed_cm airspeed_energy_error = ( ( target_airspeed * target_airspeed ) - ( aspeed_cm * aspeed_cm ) ) * 0.00005 return airspeed_energy_error
return airspeed energy error matching APM internals This is positive when we are going too slow
41,405
def energy_error ( NAV_CONTROLLER_OUTPUT , VFR_HUD ) : aspeed_energy_error = airspeed_energy_error ( NAV_CONTROLLER_OUTPUT , VFR_HUD ) alt_error = NAV_CONTROLLER_OUTPUT . alt_error * 100 energy_error = aspeed_energy_error + alt_error * 0.098 return energy_error
return energy error matching APM internals This is positive when we are too low or going too slow
41,406
def mixer ( servo1 , servo2 , mixtype = 1 , gain = 0.5 ) : s1 = servo1 - 1500 s2 = servo2 - 1500 v1 = ( s1 - s2 ) * gain v2 = ( s1 + s2 ) * gain if mixtype == 2 : v2 = - v2 elif mixtype == 3 : v1 = - v1 elif mixtype == 4 : v1 = - v1 v2 = - v2 if v1 > 600 : v1 = 600 elif v1 < - 600 : v1 = - 600 if v2 > 600 : v2 = 600 elif v2 < - 600 : v2 = - 600 return ( 1500 + v1 , 1500 + v2 )
mix two servos
41,407
def DCM_update ( IMU , ATT , MAG , GPS ) : global dcm_state if dcm_state is None : dcm_state = DCM_State ( ATT . Roll , ATT . Pitch , ATT . Yaw ) mag = Vector3 ( MAG . MagX , MAG . MagY , MAG . MagZ ) gyro = Vector3 ( IMU . GyrX , IMU . GyrY , IMU . GyrZ ) accel = Vector3 ( IMU . AccX , IMU . AccY , IMU . AccZ ) accel2 = Vector3 ( IMU . AccX , IMU . AccY , IMU . AccZ ) dcm_state . update ( gyro , accel , mag , GPS ) return dcm_state
implement full DCM system
41,408
def PX4_update ( IMU , ATT ) : global px4_state if px4_state is None : px4_state = PX4_State ( degrees ( ATT . Roll ) , degrees ( ATT . Pitch ) , degrees ( ATT . Yaw ) , IMU . _timestamp ) gyro = Vector3 ( IMU . GyroX , IMU . GyroY , IMU . GyroZ ) accel = Vector3 ( IMU . AccX , IMU . AccY , IMU . AccZ ) px4_state . update ( gyro , accel , IMU . _timestamp ) return px4_state
implement full DCM using PX4 native SD log data
41,409
def armed ( HEARTBEAT ) : from . import mavutil if HEARTBEAT . type == mavutil . mavlink . MAV_TYPE_GCS : self = mavutil . mavfile_global if self . motors_armed ( ) : return 1 return 0 if HEARTBEAT . base_mode & mavutil . mavlink . MAV_MODE_FLAG_SAFETY_ARMED : return 1 return 0
return 1 if armed 0 if not
41,410
def earth_accel2 ( RAW_IMU , ATTITUDE ) : r = rotation2 ( ATTITUDE ) accel = Vector3 ( RAW_IMU . xacc , RAW_IMU . yacc , RAW_IMU . zacc ) * 9.81 * 0.001 return r * accel
return earth frame acceleration vector from AHRS2
41,411
def ekf1_pos ( EKF1 ) : global ekf_home from . import mavutil self = mavutil . mavfile_global if ekf_home is None : if not 'GPS' in self . messages or self . messages [ 'GPS' ] . Status != 3 : return None ekf_home = self . messages [ 'GPS' ] ( ekf_home . Lat , ekf_home . Lng ) = gps_offset ( ekf_home . Lat , ekf_home . Lng , - EKF1 . PE , - EKF1 . PN ) ( lat , lon ) = gps_offset ( ekf_home . Lat , ekf_home . Lng , EKF1 . PE , EKF1 . PN ) return ( lat , lon )
calculate EKF position when EKF disabled
41,412
def cmd_condition_yaw ( self , args ) : 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 , mavutil . mavlink . MAV_COMP_ID_SYSTEM_CONTROL , mavutil . mavlink . MAV_CMD_CONDITION_YAW , 0 , angle , angular_speed , 0 , angle_mode , 0 , 0 , 0 )
yaw angle angular_speed angle_mode
41,413
def cmd_velocity ( self , args ) : 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 ] ) self . master . mav . set_position_target_local_ned_send ( 0 , 0 , 0 , mavutil . mavlink . MAV_FRAME_LOCAL_NED , 0b0000111111000111 , 0 , 0 , 0 , x_mps , y_mps , - z_mps , 0 , 0 , 0 , 0 , 0 )
velocity x - ms y - ms z - ms
41,414
def cmd_position ( self , args ) : 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 , 1 , 0 , 8 , 3576 , x_m , y_m , z_m , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 )
position x - m y - m z - m
41,415
def cmd_attitude ( self , args ) : 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 , 1 , 0 , 63 , att_target , 0 , 0 , 0 , thrust )
attitude q0 q1 q2 q3 thrust
41,416
def cmd_posvel ( self , args ) : 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 , 1 , 0 , mavutil . mavlink . MAV_FRAME_GLOBAL_RELATIVE_ALT_INT , ignoremask , int ( latlon [ 0 ] * 1e7 ) , int ( latlon [ 1 ] * 1e7 ) , 10 , vN , vE , vD , 0 , 0 , 0 , 0 , 0 )
posvel mapclick vN vE vD
41,417
def on_paint ( self , event ) : dc = wx . AutoBufferedPaintDC ( self ) dc . DrawBitmap ( self . _bmp , 0 , 0 )
repaint the image
41,418
def mavgen_python_dialect ( dialect , wire_protocol ) : 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 ) try : import StringIO as io except ImportError : import io 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
generate the python code on the fly for a MAVLink dialect
41,419
def process_tlog ( filename ) : print ( "Processing %s" % filename ) mlog = mavutil . mavlink_connection ( filename , dialect = args . dialect , zero_time_base = True ) msg_types = { } msg_lists = { } types = args . types if types is not None : types = types . split ( ',' ) ( head , tail ) = os . path . split ( filename ) basename = '.' . join ( tail . split ( '.' ) [ : - 1 ] ) mfilename = re . sub ( '[\.\-\+\*]' , '_' , basename ) + '.m' 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 ( )
convert a tlog to a . m file
41,420
def radius ( d , offsets , motor_ofs ) : ( mag , motor ) = d return ( mag + offsets + motor * motor_ofs ) . length ( )
return radius give data point and offsets
41,421
def camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = '' for component in components : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
generate a CamelCase string from an underscore_string .
41,422
def generate ( basename , xml_list ) : generate_shared ( basename , xml_list ) for xml in xml_list : generate_message_definitions ( basename , xml )
generate complete MAVLink Objective - C implemenation
41,423
def add_values ( self , values ) : if self . child . is_alive ( ) : self . parent_pipe . send ( values )
add some data to the graph
41,424
def close ( self ) : self . close_graph . set ( ) if self . is_alive ( ) : self . child . join ( 2 )
close the graph
41,425
def get_enum_raw_type ( enum , msgs ) : for msg in msgs : for field in msg . fields : if field . enum == enum . name : return swift_types [ field . type ] [ 0 ] return "Int"
Search appropirate raw type for enums in messages fields
41,426
def append_static_code ( filename , outf ) : 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 )
Open and copy static code from specified file
41,427
def camel_case_from_underscores ( 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
Generate a CamelCase string from an underscore_string
41,428
def generate_enums_info ( enums , msgs ) : 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 + '_' , '' ) 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 camel case swift names for enums an entries descriptions and sort enums alphabetically
41,429
def generate_messages_info ( msgs ) : 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 ] if field . enum : 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" : field . initial_value = "data." + swift_types [ field . type ] [ 2 ] % ( field . wire_offset , field . array_length ) else : field . return_type = "[%s]" % field . return_type field . initial_value = "try data.mavArray(offset: %u, count: %u)" % ( field . wire_offset , field . array_length ) else : 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 )
Add proper formated variable names initializers and type names to use in templates
41,430
def generate ( basename , xml_list ) : 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 ( )
Generate complete MAVLink Swift implemenation
41,431
def wp_is_loiter ( self , i ) : 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
return true if waypoint is a loiter waypoint
41,432
def add ( self , w , comment = '' ) : w = copy . copy ( w ) if comment : w . comment = comment w . seq = self . count ( ) self . wpoints . append ( w ) self . last_change = time . time ( )
add a waypoint
41,433
def insert ( self , idx , w , comment = '' ) : 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 ( )
insert a waypoint
41,434
def set ( self , w , idx ) : 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 ( )
set a waypoint
41,435
def remove ( self , w ) : self . wpoints . remove ( w ) self . last_change = time . time ( ) self . reindex ( )
remove a waypoint
41,436
def _read_waypoints_v100 ( self , file ) : 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 ] ) , int ( a [ 1 ] ) , int ( a [ 2 ] ) , int ( a [ 7 ] ) , int ( a [ 12 ] ) , float ( a [ 5 ] ) , float ( a [ 6 ] ) , float ( a [ 3 ] ) , float ( a [ 4 ] ) , float ( a [ 9 ] ) , float ( a [ 8 ] ) , float ( a [ 10 ] ) ) 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 100 waypoint
41,437
def _read_waypoints_v110 ( self , file ) : 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 ] ) , int ( a [ 2 ] ) , int ( a [ 3 ] ) , int ( a [ 1 ] ) , int ( a [ 11 ] ) , float ( a [ 4 ] ) , float ( a [ 5 ] ) , float ( a [ 6 ] ) , float ( a [ 7 ] ) , float ( a [ 8 ] ) , float ( a [ 9 ] ) , float ( a [ 10 ] ) ) if w . command == 0 and w . seq == 0 and self . count ( ) == 0 : w . command = mavutil . mavlink . MAV_CMD_NAV_WAYPOINT self . add ( w , comment ) comment = ''
read a version 110 waypoint
41,438
def load ( self , filename ) : 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 )
load waypoints from a file . returns number of waypoints loaded
41,439
def view_indexes ( self , done = None ) : ret = [ ] if done is None : done = set ( ) idx = 0 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 list waypoint indexes in view order
41,440
def polygon ( self , done = None ) : indexes = self . view_indexes ( done ) points = [ ] for idx in indexes : w = self . wp ( idx ) points . append ( ( w . x , w . y ) ) return points
return a polygon for the waypoints
41,441
def polygon_list ( self ) : 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 polygons for the waypoints
41,442
def view_list ( self ) : done = set ( ) ret = [ ] while len ( done ) != self . count ( ) : p = self . view_indexes ( done ) if len ( p ) > 0 : ret . append ( p ) return ret
return a list of polygon indexes lists for the waypoints
41,443
def reindex ( self ) : 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 ( )
reset counters and indexes
41,444
def append_rally_point ( self , p ) : 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 rallypoint to end of list
41,445
def load ( self , filename ) : 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 )
load rally and rally_land points from a file . returns number of points loaded
41,446
def load ( self , filename ) : 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 )
load points from a file . returns number of points loaded
41,447
def move ( self , i , lat , lng , change_time = True ) : if i < 0 or i >= self . count ( ) : print ( "Invalid fence point number %u" % i ) self . points [ i ] . lat = lat self . points [ i ] . lng = lng 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 ( )
move a fence point
41,448
def remove ( self , i , change_time = True ) : if i < 0 or i >= self . count ( ) : print ( "Invalid fence point number %u" % i ) self . points . pop ( i ) 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 ( )
remove a fence point
41,449
def polygon ( self ) : points = [ ] for fp in self . points [ 1 : ] : points . append ( ( fp . lat , fp . lng ) ) return points
return a polygon for the fence
41,450
def add_input ( cmd , immediate = False ) : if immediate : process_stdin ( cmd ) else : mpstate . input_queue . put ( cmd )
add some command input to be processed
41,451
def param_set ( name , value , retries = 3 ) : name = name . upper ( ) return mpstate . mav_param . mavset ( mpstate . master ( ) , name , value , retries = retries )
set a parameter
41,452
def unload_module ( modname ) : 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
unload a module
41,453
def import_package ( name ) : 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
Given a package name like foo . bar . quux imports the package and returns the desired module .
41,454
def process_master ( m ) : try : s = m . recv ( 16 * 1024 ) except Exception : time . sleep ( 0.1 ) return 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' : 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 : 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
process packets from the MAVLink master
41,455
def set_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 )
set mavlink stream rates
41,456
def periodic_tasks ( ) : 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 ( ) 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 ) if m . needs_unloading : unload_module ( m . name )
run periodic checks
41,457
def master ( self ) : if len ( self . mav_master ) == 0 : return None if self . settings . link > len ( self . mav_master ) : self . settings . link = 1 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 ]
return the currently chosen mavlink master object
41,458
def generate ( basename , xml ) : 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 ( ) 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 ( ) 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 ) res = os . system ( compileCommand ) if res == '0' : print ( "Generated %s OK" % filename ) else : print ( "Error" )
generate complete MAVLink CSharp implemenation
41,459
def load_stylesheet ( pyside = True ) : if pyside : import qdarkstyle . pyside_style_rc else : import qdarkstyle . pyqt_style_rc 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' : mac_fix = stylesheet += mac_fix return stylesheet
Loads the stylesheet . Takes care of importing the rc module .
41,460
def load_stylesheet_pyqt5 ( ) : import qdarkstyle . pyqt5_style_rc 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' : mac_fix = stylesheet += mac_fix return stylesheet
Loads the stylesheet for use in a pyqt5 application .
41,461
def call_handler ( self ) : if self . handler is None : return call = getattr ( self . handler , 'call' , None ) if call is not None : self . handler_result = call ( )
optionally call a handler function
41,462
def add ( self , items ) : if not isinstance ( items , list ) : items = [ items ] for m in items : updated = False for i in range ( len ( self . items ) ) : if self . items [ i ] . name == m . name : self . items [ i ] = m updated = True if not updated : self . items . append ( m )
add a submenu
41,463
def call ( self ) : mp_util . child_close_fds ( ) import wx_processguard from wx_loader import wx from wx . lib . agw . genericmessagedialog import GenericMessageDialog app = wx . App ( False ) font = wx . Font ( self . font_size , wx . MODERN , wx . NORMAL , wx . NORMAL ) dlg = GenericMessageDialog ( None , self . message , self . title , wx . ICON_INFORMATION | wx . OK ) dlg . SetFont ( font ) dlg . ShowModal ( ) app . MainLoop ( )
show the dialog as a child process
41,464
def read_ermapper ( self , ifile ) : ers_index = ifile . find ( '.ers' ) if ers_index > 0 : data_file = ifile [ 0 : ers_index ] header_file = ifile else : data_file = ifile header_file = ifile + '.ers' self . header = self . read_ermapper_header ( header_file ) nroflines = int ( self . header [ 'nroflines' ] ) nrofcellsperlines = int ( self . header [ 'nrofcellsperline' ] ) self . data = self . read_ermapper_data ( data_file , offset = int ( self . header [ 'headeroffset' ] ) ) self . data = numpy . reshape ( self . data , ( nroflines , nrofcellsperlines ) ) longy = numpy . fromstring ( self . getHeaderParam ( 'longitude' ) , sep = ':' ) latty = numpy . fromstring ( self . getHeaderParam ( 'latitude' ) , sep = ':' ) self . deltalatitude = float ( self . header [ 'ydimension' ] ) self . deltalongitude = float ( self . header [ 'xdimension' ] ) if longy [ 0 ] < 0 : self . startlongitude = longy [ 0 ] + - ( ( longy [ 1 ] / 60 ) + ( longy [ 2 ] / 3600 ) ) self . endlongitude = self . startlongitude - int ( self . header [ 'nrofcellsperline' ] ) * self . deltalongitude else : self . startlongitude = longy [ 0 ] + ( longy [ 1 ] / 60 ) + ( longy [ 2 ] / 3600 ) self . endlongitude = self . startlongitude + int ( self . header [ 'nrofcellsperline' ] ) * self . deltalongitude if latty [ 0 ] < 0 : self . startlatitude = latty [ 0 ] - ( ( latty [ 1 ] / 60 ) + ( latty [ 2 ] / 3600 ) ) self . endlatitude = self . startlatitude - int ( self . header [ 'nroflines' ] ) * self . deltalatitude else : self . startlatitude = latty [ 0 ] + ( latty [ 1 ] / 60 ) + ( latty [ 2 ] / 3600 ) self . endlatitude = self . startlatitude + int ( self . header [ 'nroflines' ] ) * self . deltalatitude
Read in a DEM file and associated . ers file
41,465
def printBoundingBox ( self ) : print ( "Bounding Latitude: " ) print ( self . startlatitude ) print ( self . endlatitude ) print ( "Bounding Longitude: " ) print ( self . startlongitude ) print ( self . endlongitude )
Print the bounding box that this DEM covers
41,466
def getPercentBlank ( self ) : blank = 0 nonblank = 0 for x in self . data . flat : if x == - 99999.0 : blank = blank + 1 else : nonblank = nonblank + 1 print ( "Blank tiles = " , blank , "out of " , ( nonblank + blank ) )
Print how many null cells are in the DEM - Quality measure
41,467
def send_rc_override ( self ) : if self . sitl_output : buf = struct . pack ( '<HHHHHHHH' , * self . override ) self . sitl_output . write ( buf ) else : self . master . mav . rc_channels_override_send ( self . target_system , self . target_component , * self . override )
send RC override packet
41,468
def cmd_switch ( self , args ) : mapping = [ 0 , 1165 , 1295 , 1425 , 1555 , 1685 , 1815 ] if len ( args ) != 1 : print ( "Usage: switch <pwmvalue>" ) return value = int ( args [ 0 ] ) if value < 0 or value > 6 : print ( "Invalid switch value. Use 1-6 for flight modes, '0' to disable" ) return if self . vehicle_type == 'copter' : default_channel = 5 else : default_channel = 8 if self . vehicle_type == 'rover' : flite_mode_ch_parm = int ( self . get_mav_param ( "MODE_CH" , default_channel ) ) else : flite_mode_ch_parm = int ( self . get_mav_param ( "FLTMODE_CH" , default_channel ) ) self . override [ flite_mode_ch_parm - 1 ] = mapping [ value ] self . override_counter = 10 self . send_rc_override ( ) if value == 0 : print ( "Disabled RC switch override" ) else : print ( "Set RC switch override to %u (PWM=%u channel=%u)" % ( value , mapping [ value ] , flite_mode_ch_parm ) )
handle RC switch changes
41,469
def write_NetCDF_georeference ( origin , outfile ) : geo_ref = ensure_geo_reference ( origin ) geo_ref . write_NetCDF ( outfile ) return geo_ref
Write georeference info to a netcdf file usually sww .
41,470
def is_absolute ( self ) : if not hasattr ( self , 'absolute' ) : self . absolute = num . allclose ( [ self . xllcorner , self . yllcorner ] , 0 ) return self . absolute
Return True if xllcorner == yllcorner == 0 indicating that points in question are absolute .
41,471
def mkdir_p ( dir ) : if not dir : return if dir . endswith ( "/" ) or dir . endswith ( "\\" ) : mkdir_p ( dir [ : - 1 ] ) return if os . path . isdir ( dir ) : return mkdir_p ( os . path . dirname ( dir ) ) try : os . mkdir ( dir ) except Exception : pass
like mkdir - p
41,472
def polygon_load ( filename ) : ret = [ ] f = open ( filename ) for line in f : if line . startswith ( '#' ) : continue line = line . strip ( ) if not line : continue a = line . split ( ) if len ( a ) != 2 : raise RuntimeError ( "invalid polygon line: %s" % line ) ret . append ( ( float ( a [ 0 ] ) , float ( a [ 1 ] ) ) ) f . close ( ) return ret
load a polygon from a file
41,473
def bounds_overlap ( bound1 , bound2 ) : ( x1 , y1 , w1 , h1 ) = bound1 ( x2 , y2 , w2 , h2 ) = bound2 if x1 + w1 < x2 : return False if x2 + w2 < x1 : return False if y1 + h1 < y2 : return False if y2 + h2 < y1 : return False return True
return true if two bounding boxes overlap
41,474
def latlon_to_grid ( latlon ) : from MAVProxy . modules . lib . ANUGA import redfearn ( zone , easting , northing ) = redfearn . redfearn ( latlon [ 0 ] , latlon [ 1 ] ) if latlon [ 0 ] < 0 : hemisphere = 'S' else : hemisphere = 'N' return UTMGrid ( zone , easting , northing , hemisphere = hemisphere )
convert to grid reference
41,475
def latlon_round ( latlon , spacing = 1000 ) : g = latlon_to_grid ( latlon ) g . easting = ( g . easting // spacing ) * spacing g . northing = ( g . northing // spacing ) * spacing return g . latlon ( )
round to nearest grid corner
41,476
def wxToPIL ( wimg ) : from PIL import Image ( w , h ) = wimg . GetSize ( ) d = wimg . GetData ( ) pimg = Image . new ( "RGB" , ( w , h ) , color = 1 ) pimg . fromstring ( d ) return pimg
convert a wxImage to a PIL Image
41,477
def child_close_fds ( ) : global child_fd_list import os while len ( child_fd_list ) > 0 : fd = child_fd_list . pop ( 0 ) try : os . close ( fd ) except Exception as msg : pass
close file descriptors that a child process should not inherit . Should be called from child processes .
41,478
def snapshot_folder ( ) : logger . info ( "Snapshot folder" ) try : stdout = subprocess . check_output ( [ "git" , "show" , "-s" , "--format=%cI" , "HEAD" ] ) except subprocess . CalledProcessError as e : logger . error ( "Error: {}" . format ( e . output . decode ( 'ascii' , 'ignore' ) . strip ( ) ) ) sys . exit ( 2 ) except FileNotFoundError as e : logger . error ( "Error: {}" . format ( e ) ) sys . exit ( 2 ) ds = stdout . decode ( 'ascii' , 'ignore' ) . strip ( ) dt = datetime . fromisoformat ( ds ) utc = dt - dt . utcoffset ( ) return utc . strftime ( "%Y%m%d_%H%M%S" )
Use the commit date in UTC as folder name
41,479
def opengraph_get ( html , prop ) : match = re . search ( '<meta [^>]*property="og:' + prop + '" content="([^"]*)"' , html ) if match is None : match = re . search ( '<meta [^>]*content="([^"]*)" property="og:' + prop + '"' , html ) if match is None : return None return match . group ( 1 )
Extract specified OpenGraph property from html .
41,480
def decode_html_entities ( s ) : parser = HTMLParser . HTMLParser ( ) def unesc ( m ) : return parser . unescape ( m . group ( ) ) return re . sub ( r'(&[^;]+;)' , unesc , ensure_unicode ( s ) )
Replaces html entities with the character they represent .
41,481
def filenamify ( title ) : title = ensure_unicode ( title ) title = unicodedata . normalize ( 'NFD' , title ) title = re . sub ( r'[^a-z0-9 .-]' , '' , title . lower ( ) . strip ( ) ) title = re . sub ( r'\s+' , '.' , title ) title = re . sub ( r'\.-\.' , '-' , title ) return title
Convert a string to something suitable as a file name . E . g .
41,482
def download ( self ) : _ , ext = os . path . splitext ( self . url ) if ext == ".mp3" : self . output_extention = "mp3" else : self . output_extention = "mp4" data = self . http . request ( "get" , self . url , stream = True ) try : total_size = data . headers [ 'content-length' ] except KeyError : total_size = 0 total_size = int ( total_size ) bytes_so_far = 0 file_d = output ( self . output , self . config , self . output_extention ) if file_d is None : return eta = ETA ( total_size ) for i in data . iter_content ( 8192 ) : bytes_so_far += len ( i ) file_d . write ( i ) if not self . config . get ( "silent" ) : eta . update ( bytes_so_far ) progressbar ( total_size , bytes_so_far , '' . join ( [ "ETA: " , str ( eta ) ] ) ) file_d . close ( ) self . finished = True
Get the stream from HTTP
41,483
def progress ( byte , total , extra = "" ) : if total == 0 : progresstr = "Downloaded %dkB bytes" % ( byte >> 10 ) progress_stream . write ( progresstr + '\r' ) return progressbar ( total , byte , extra )
Print some info about how much we have downloaded
41,484
def update ( self , pos ) : self . pos = pos self . now = time . time ( )
Set new absolute progress position .
41,485
def check_xlim_change ( self ) : if self . xlim_pipe is None : return None xlim = None while self . xlim_pipe [ 0 ] . poll ( ) : try : xlim = self . xlim_pipe [ 0 ] . recv ( ) except EOFError : return None if xlim != self . xlim : return xlim return None
check for new X bounds
41,486
def set_xlim ( self , xlim ) : if self . xlim_pipe is not None and self . xlim != xlim : try : self . xlim_pipe [ 0 ] . send ( xlim ) except IOError : return False self . xlim = xlim return True
set new X bounds
41,487
def serial_lock ( self , lock ) : mav = self . master . mav if lock : flags = mavutil . mavlink . SERIAL_CONTROL_FLAG_EXCLUSIVE self . locked = True else : flags = 0 self . locked = False mav . serial_control_send ( self . serial_settings . port , flags , 0 , 0 , 0 , [ 0 ] * 70 )
lock or unlock the port
41,488
def cmd_serial ( self , args ) : usage = "Usage: serial <lock|unlock|set|send>" if len ( args ) < 1 : print ( usage ) return if args [ 0 ] == "lock" : self . serial_lock ( True ) elif args [ 0 ] == "unlock" : self . serial_lock ( False ) elif args [ 0 ] == "set" : self . serial_settings . command ( args [ 1 : ] ) elif args [ 0 ] == "send" : self . serial_send ( args [ 1 : ] ) else : print ( usage )
serial control commands
41,489
def downloader ( self ) : while self . tiles_pending ( ) > 0 : time . sleep ( self . tile_delay ) keys = sorted ( self . _download_pending . keys ( ) ) tile_info = self . _download_pending [ keys [ 0 ] ] for key in keys : if self . _download_pending [ key ] . request_time > tile_info . request_time : tile_info = self . _download_pending [ key ] url = tile_info . url ( self . service ) path = self . tile_to_path ( tile_info ) key = tile_info . key ( ) try : if self . debug : print ( "Downloading %s [%u left]" % ( url , len ( keys ) ) ) req = url_request ( url ) if url . find ( 'google' ) != - 1 : req . add_header ( 'Referer' , 'https://maps.google.com/' ) resp = url_open ( req ) headers = resp . info ( ) except url_error as e : if not key in self . _tile_cache : self . _tile_cache [ key ] = self . _unavailable self . _download_pending . pop ( key ) if self . debug : print ( "Failed %s: %s" % ( url , str ( e ) ) ) continue if 'content-type' not in headers or headers [ 'content-type' ] . find ( 'image' ) == - 1 : if not key in self . _tile_cache : self . _tile_cache [ key ] = self . _unavailable self . _download_pending . pop ( key ) if self . debug : print ( "non-image response %s" % url ) continue else : img = resp . read ( ) md5 = hashlib . md5 ( img ) . hexdigest ( ) if md5 in BLANK_TILES : if self . debug : print ( "blank tile %s" % url ) if not key in self . _tile_cache : self . _tile_cache [ key ] = self . _unavailable self . _download_pending . pop ( key ) continue mp_util . mkdir_p ( os . path . dirname ( path ) ) h = open ( path + '.tmp' , 'wb' ) h . write ( img ) h . close ( ) try : os . unlink ( path ) except Exception : pass os . rename ( path + '.tmp' , path ) self . _download_pending . pop ( key ) self . _download_thread = None
the download thread
41,490
def cmd_fw ( self , args ) : if len ( args ) == 0 : print ( self . usage ( ) ) return rest = args [ 1 : ] if args [ 0 ] == "manifest" : self . cmd_fw_manifest ( rest ) elif args [ 0 ] == "list" : self . cmd_fw_list ( rest ) elif args [ 0 ] == "download" : self . cmd_fw_download ( rest ) elif args [ 0 ] in [ "help" , "usage" ] : self . cmd_fw_help ( rest ) else : print ( self . usage ( ) )
execute command defined in args
41,491
def frame_from_firmware ( self , firmware ) : frame_to_mavlink_dict = { "quad" : "QUADROTOR" , "hexa" : "HEXAROTOR" , "y6" : "ARDUPILOT_Y6" , "tri" : "TRICOPTER" , "octa" : "OCTOROTOR" , "octa-quad" : "ARDUPILOT_OCTAQUAD" , "heli" : "HELICOPTER" , "Plane" : "FIXED_WING" , "Tracker" : "ANTENNA_TRACKER" , "Rover" : "GROUND_ROVER" , "PX4IO" : "ARDUPILOT_PX4IO" , } mavlink_to_frame_dict = { v : k for k , v in frame_to_mavlink_dict . items ( ) } x = firmware [ "mav-type" ] if firmware [ "mav-autopilot" ] != "ARDUPILOTMEGA" : return x if x in mavlink_to_frame_dict : return mavlink_to_frame_dict [ x ] return x
extract information from firmware return pretty string to user
41,492
def row_is_filtered ( self , row_subs , filters ) : for filtername in filters : filtervalue = filters [ filtername ] if filtername in row_subs : row_subs_value = row_subs [ filtername ] if str ( row_subs_value ) != str ( filtervalue ) : return True else : print ( "fw: Unknown filter keyword (%s)" % ( filtername , ) ) return False
returns True if row should NOT be included according to filters
41,493
def filters_from_args ( self , args ) : filters = dict ( ) remainder = [ ] for arg in args : try : equals = arg . index ( '=' ) filters [ arg [ 0 : equals ] ] = arg [ equals + 1 : ] except ValueError : remainder . append ( arg ) return ( filters , remainder )
take any argument of the form name = value anmd put it into a dict ; return that and the remaining arguments
41,494
def all_firmwares ( self ) : all = [ ] for manifest in self . manifests : for firmware in manifest [ "firmware" ] : all . append ( firmware ) return all
return firmware entries from all manifests
41,495
def rows_for_firmwares ( self , firmwares ) : rows = [ ] i = 0 for firmware in firmwares : frame = self . frame_from_firmware ( firmware ) row = { "seq" : i , "platform" : firmware [ "platform" ] , "frame" : frame , "releasetype" : firmware [ "mav-firmware-version-type" ] , "latest" : firmware [ "latest" ] , "git-sha" : firmware [ "git-sha" ] [ 0 : 7 ] , "format" : firmware [ "format" ] , "_firmware" : firmware , } ( major , minor , patch ) = self . semver_from_firmware ( firmware ) if major is None : row [ "version" ] = "" row [ "major" ] = "" row [ "minor" ] = "" row [ "patch" ] = "" else : row [ "version" ] = firmware [ "mav-firmware-version" ] row [ "major" ] = major row [ "minor" ] = minor row [ "patch" ] = patch i += 1 rows . append ( row ) return rows
provide user - readable text for a firmware entry
41,496
def filter_rows ( self , filters , rows ) : ret = [ ] for row in rows : if not self . row_is_filtered ( row , filters ) : ret . append ( row ) return ret
returns rows as filtered by filters
41,497
def filtered_rows_from_args ( self , args ) : if len ( self . manifests ) == 0 : print ( "fw: No manifests downloaded. Try 'manifest download'" ) return None ( filters , remainder ) = self . filters_from_args ( args ) all = self . all_firmwares ( ) rows = self . rows_for_firmwares ( all ) filtered = self . filter_rows ( filters , rows ) return ( filtered , remainder )
extracts filters from args rows from manifests returns filtered rows
41,498
def cmd_fw_list ( self , args ) : stuff = self . filtered_rows_from_args ( args ) if stuff is None : return ( filtered , remainder ) = stuff print ( "" ) print ( " seq platform frame major.minor.patch releasetype latest git-sha format" ) for row in filtered : print ( "{seq:>5} {platform:<13} {frame:<10} {version:<10} {releasetype:<9} {latest:<6} {git-sha} {format}" . format ( ** row ) )
cmd handler for list
41,499
def cmd_fw_download ( self , args ) : stuff = self . filtered_rows_from_args ( args ) if stuff is None : return ( filtered , remainder ) = stuff if len ( filtered ) == 0 : print ( "fw: No firmware specified" ) return if len ( filtered ) > 1 : print ( "fw: No single firmware specified" ) return firmware = filtered [ 0 ] [ "_firmware" ] url = firmware [ "url" ] try : print ( "fw: URL: %s" % ( url , ) ) filename = os . path . basename ( url ) files = [ ] files . append ( ( url , filename ) ) child = multiproc . Process ( target = mp_util . download_files , args = ( files , ) ) child . start ( ) except Exception as e : print ( "fw: download failed" ) print ( e )
cmd handler for downloading firmware