idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
39,500 | def colour_rgb ( self ) : hexvalue = self . status ( ) [ self . DPS ] [ self . DPS_INDEX_COLOUR ] return BulbDevice . _hexvalue_to_rgb ( hexvalue ) | Return colour as RGB value |
39,501 | def colour_hsv ( self ) : hexvalue = self . status ( ) [ self . DPS ] [ self . DPS_INDEX_COLOUR ] return BulbDevice . _hexvalue_to_hsv ( hexvalue ) | Return colour as HSV value |
39,502 | def set_group_mask ( self , group_mask = ALL_GROUPS ) : self . _send_packet ( struct . pack ( '<BB' , self . COMMAND_SET_GROUP_MASK , group_mask ) ) | Set the group mask that the Crazyflie belongs to |
39,503 | def takeoff ( self , absolute_height_m , duration_s , group_mask = ALL_GROUPS ) : self . _send_packet ( struct . pack ( '<BBff' , self . COMMAND_TAKEOFF , group_mask , absolute_height_m , duration_s ) ) | vertical takeoff from current x - y position to given height |
39,504 | def land ( self , absolute_height_m , duration_s , group_mask = ALL_GROUPS ) : self . _send_packet ( struct . pack ( '<BBff' , self . COMMAND_LAND , group_mask , absolute_height_m , duration_s ) ) | vertical land from current x - y position to given height |
39,505 | def go_to ( self , x , y , z , yaw , duration_s , relative = False , group_mask = ALL_GROUPS ) : self . _send_packet ( struct . pack ( '<BBBfffff' , self . COMMAND_GO_TO , group_mask , relative , x , y , z , yaw , duration_s ) ) | Go to an absolute or relative position |
39,506 | def start_trajectory ( self , trajectory_id , time_scale = 1.0 , relative = False , reversed = False , group_mask = ALL_GROUPS ) : self . _send_packet ( struct . pack ( '<BBBBBf' , self . COMMAND_START_TRAJECTORY , group_mask , relative , reversed , trajectory_id , time_scale ) ) | starts executing a specified trajectory |
39,507 | def define_trajectory ( self , trajectory_id , offset , n_pieces ) : self . _send_packet ( struct . pack ( '<BBBBIB' , self . COMMAND_DEFINE_TRAJECTORY , trajectory_id , self . TRAJECTORY_LOCATION_MEM , self . TRAJECTORY_TYPE_POLY4D , offset , n_pieces ) ) | Define a trajectory that has previously been uploaded to memory . |
39,508 | def choose ( items , title_text , question_text ) : print ( title_text ) for i , item in enumerate ( items , start = 1 ) : print ( '%d) %s' % ( i , item ) ) print ( '%d) Abort' % ( i + 1 ) ) selected = input ( question_text ) try : index = int ( selected ) except ValueError : index = - 1 if not ( index - 1 ) in range ( len ( items ) ) : print ( 'Aborting.' ) return None return items [ index - 1 ] | Interactively choose one of the items . |
39,509 | def scan ( ) : cflib . crtp . init_drivers ( enable_debug_driver = False ) print ( 'Scanning interfaces for Crazyflies...' ) available = cflib . crtp . scan_interfaces ( ) interfaces = [ uri for uri , _ in available ] if not interfaces : return None return choose ( interfaces , 'Crazyflies found:' , 'Select interface: ' ) | Scan for Crazyflie and return its URI . |
39,510 | def connect ( self ) : print ( 'Connecting to %s' % self . _link_uri ) self . _cf . open_link ( self . _link_uri ) | Connect to the crazyflie . |
39,511 | def wait_for_connection ( self , timeout = 10 ) : start_time = datetime . datetime . now ( ) while True : if self . connected : return True now = datetime . datetime . now ( ) if ( now - start_time ) . total_seconds ( ) > timeout : return False time . sleep ( 0.5 ) | Busy loop until connection is established . |
39,512 | def search_memories ( self ) : if not self . connected : raise NotConnected ( ) return self . _cf . mem . get_mems ( MemoryElement . TYPE_1W ) | Search and return list of 1 - wire memories . |
39,513 | def _stab_log_data ( self , timestamp , data , logconf ) : print ( '[%d][%s]: %s' % ( timestamp , logconf . name , data ) ) | Callback froma the log API when data arrives |
39,514 | def fetch_platform_informations ( self , callback ) : self . _protocolVersion = - 1 self . _callback = callback self . _request_protocol_version ( ) | Fetch platform info from the firmware Should be called at the earliest in the connection sequence |
39,515 | def receive_packet ( self , time = 0 ) : if time == 0 : try : return self . in_queue . get ( False ) except queue . Empty : return None elif time < 0 : try : return self . in_queue . get ( True ) except queue . Empty : return None else : try : return self . in_queue . get ( True , time ) except queue . Empty : return None | Receive a packet though the link . This call is blocking but will timeout and return None if a timeout is supplied . |
39,516 | def add_callback ( self , cb ) : if ( ( cb in self . callbacks ) is False ) : self . callbacks . append ( cb ) | Register cb as a new callback . Will not register duplicates . |
39,517 | def read_cf1_config ( self ) : target = self . _cload . targets [ 0xFF ] config_page = target . flash_pages - 1 return self . _cload . read_flash ( addr = 0xFF , page = config_page ) | Read a flash page from the specified target |
39,518 | def set_channel ( self , channel ) : if channel != self . current_channel : _send_vendor_setup ( self . handle , SET_RADIO_CHANNEL , channel , 0 , ( ) ) self . current_channel = channel | Set the radio channel to be used |
39,519 | def set_address ( self , address ) : if len ( address ) != 5 : raise Exception ( 'Crazyradio: the radio address shall be 5' ' bytes long' ) if address != self . current_address : _send_vendor_setup ( self . handle , SET_RADIO_ADDRESS , 0 , 0 , address ) self . current_address = address | Set the radio address to be used |
39,520 | def set_data_rate ( self , datarate ) : if datarate != self . current_datarate : _send_vendor_setup ( self . handle , SET_DATA_RATE , datarate , 0 , ( ) ) self . current_datarate = datarate | Set the radio datarate to be used |
39,521 | def set_arc ( self , arc ) : _send_vendor_setup ( self . handle , SET_RADIO_ARC , arc , 0 , ( ) ) self . arc = arc | Set the ACK retry count for radio communication |
39,522 | def set_ard_time ( self , us ) : t = int ( ( us / 250 ) - 1 ) if ( t < 0 ) : t = 0 if ( t > 0xF ) : t = 0xF _send_vendor_setup ( self . handle , SET_RADIO_ARD , t , 0 , ( ) ) | Set the ACK retry delay for radio communication |
39,523 | def fetch ( self , crc ) : cache_data = None pattern = '%08X.json' % crc hit = None for name in self . _cache_files : if ( name . endswith ( pattern ) ) : hit = name if ( hit ) : try : cache = open ( hit ) cache_data = json . load ( cache , object_hook = self . _decoder ) cache . close ( ) except Exception as exp : logger . warning ( 'Error while parsing cache file [%s]:%s' , hit , str ( exp ) ) return cache_data | Try to get a hit in the cache return None otherwise |
39,524 | def insert ( self , crc , toc ) : if self . _rw_cache : try : filename = '%s/%08X.json' % ( self . _rw_cache , crc ) cache = open ( filename , 'w' ) cache . write ( json . dumps ( toc , indent = 2 , default = self . _encoder ) ) cache . close ( ) logger . info ( 'Saved cache to [%s]' , filename ) self . _cache_files += [ filename ] except Exception as exp : logger . warning ( 'Could not save cache to file [%s]: %s' , filename , str ( exp ) ) else : logger . warning ( 'Could not save cache, no writable directory' ) | Save a new cache to file |
39,525 | def _encoder ( self , obj ) : return { '__class__' : obj . __class__ . __name__ , 'ident' : obj . ident , 'group' : obj . group , 'name' : obj . name , 'ctype' : obj . ctype , 'pytype' : obj . pytype , 'access' : obj . access } raise TypeError ( repr ( obj ) + ' is not JSON serializable' ) | Encode a toc element leaf - node |
39,526 | def _decoder ( self , obj ) : if '__class__' in obj : elem = eval ( obj [ '__class__' ] ) ( ) elem . ident = obj [ 'ident' ] elem . group = str ( obj [ 'group' ] ) elem . name = str ( obj [ 'name' ] ) elem . ctype = str ( obj [ 'ctype' ] ) elem . pytype = str ( obj [ 'pytype' ] ) elem . access = obj [ 'access' ] return elem return obj | Decode a toc element leaf - node |
39,527 | def set_mode ( self , anchor_id , mode ) : data = struct . pack ( '<BB' , LoPoAnchor . LPP_TYPE_MODE , mode ) self . crazyflie . loc . send_short_lpp_packet ( anchor_id , data ) | Send a packet to set the anchor mode . If the anchor receive the packet it will change mode and resets . |
39,528 | def open_links ( self ) : if self . _is_open : raise Exception ( 'Already opened' ) try : self . parallel_safe ( lambda scf : scf . open_link ( ) ) self . _is_open = True except Exception as e : self . close_links ( ) raise e | Open links to all individuals in the swarm |
39,529 | def close_links ( self ) : for uri , cf in self . _cfs . items ( ) : cf . close_link ( ) self . _is_open = False | Close all open links |
39,530 | def sequential ( self , func , args_dict = None ) : for uri , cf in self . _cfs . items ( ) : args = self . _process_args_dict ( cf , uri , args_dict ) func ( * args ) | Execute a function for all Crazyflies in the swarm in sequence . |
39,531 | def parallel_safe ( self , func , args_dict = None ) : threads = [ ] reporter = self . Reporter ( ) for uri , scf in self . _cfs . items ( ) : args = [ func , reporter ] + self . _process_args_dict ( scf , uri , args_dict ) thread = Thread ( target = self . _thread_function_wrapper , args = args ) threads . append ( thread ) thread . start ( ) for thread in threads : thread . join ( ) if reporter . is_error_reported ( ) : raise Exception ( 'One or more threads raised an exception when ' 'executing parallel task' ) | Execute a function for all Crazyflies in the swarm in parallel . One thread per Crazyflie is started to execute the function . The threads are joined at the end and if one or more of the threads raised an exception this function will also raise an exception . |
39,532 | def take_off ( self , height = DEFAULT , velocity = DEFAULT ) : if self . _is_flying : raise Exception ( 'Already flying' ) if not self . _cf . is_connected ( ) : raise Exception ( 'Crazyflie is not connected' ) self . _is_flying = True self . _reset_position_estimator ( ) self . _activate_controller ( ) self . _activate_high_level_commander ( ) self . _hl_commander = self . _cf . high_level_commander height = self . _height ( height ) duration_s = height / self . _velocity ( velocity ) self . _hl_commander . takeoff ( height , duration_s ) time . sleep ( duration_s ) self . _z = height | Takes off that is starts the motors goes straight up and hovers . Do not call this function if you use the with keyword . Take off is done automatically when the context is created . |
39,533 | def go_to ( self , x , y , z = DEFAULT , velocity = DEFAULT ) : z = self . _height ( z ) dx = x - self . _x dy = y - self . _y dz = z - self . _z distance = math . sqrt ( dx * dx + dy * dy + dz * dz ) duration_s = distance / self . _velocity ( velocity ) self . _hl_commander . go_to ( x , y , z , 0 , duration_s ) time . sleep ( duration_s ) self . _x = x self . _y = y self . _z = z | Go to a position |
39,534 | def request_update_of_all_params ( self ) : for group in self . toc . toc : for name in self . toc . toc [ group ] : complete_name = '%s.%s' % ( group , name ) self . request_param_update ( complete_name ) | Request an update of all the parameters in the TOC |
39,535 | def _check_if_all_updated ( self ) : for g in self . toc . toc : if g not in self . values : return False for n in self . toc . toc [ g ] : if n not in self . values [ g ] : return False return True | Check if all parameters from the TOC has at least been fetched once |
39,536 | def _param_updated ( self , pk ) : if self . _useV2 : var_id = struct . unpack ( '<H' , pk . data [ : 2 ] ) [ 0 ] else : var_id = pk . data [ 0 ] element = self . toc . get_element_by_id ( var_id ) if element : if self . _useV2 : s = struct . unpack ( element . pytype , pk . data [ 2 : ] ) [ 0 ] else : s = struct . unpack ( element . pytype , pk . data [ 1 : ] ) [ 0 ] s = s . __str__ ( ) complete_name = '%s.%s' % ( element . group , element . name ) if element . group not in self . values : self . values [ element . group ] = { } self . values [ element . group ] [ element . name ] = s logger . debug ( 'Updated parameter [%s]' % complete_name ) if complete_name in self . param_update_callbacks : self . param_update_callbacks [ complete_name ] . call ( complete_name , s ) if element . group in self . group_update_callbacks : self . group_update_callbacks [ element . group ] . call ( complete_name , s ) self . all_update_callback . call ( complete_name , s ) if self . _check_if_all_updated ( ) and not self . is_updated : self . is_updated = True self . all_updated . call ( ) else : logger . debug ( 'Variable id [%d] not found in TOC' , var_id ) | Callback with data for an updated parameter |
39,537 | def remove_update_callback ( self , group , name = None , cb = None ) : if not cb : return if not name : if group in self . group_update_callbacks : self . group_update_callbacks [ group ] . remove_callback ( cb ) else : paramname = '{}.{}' . format ( group , name ) if paramname in self . param_update_callbacks : self . param_update_callbacks [ paramname ] . remove_callback ( cb ) | Remove the supplied callback for a group or a group . name |
39,538 | def add_update_callback ( self , group = None , name = None , cb = None ) : if not group and not name : self . all_update_callback . add_callback ( cb ) elif not name : if group not in self . group_update_callbacks : self . group_update_callbacks [ group ] = Caller ( ) self . group_update_callbacks [ group ] . add_callback ( cb ) else : paramname = '{}.{}' . format ( group , name ) if paramname not in self . param_update_callbacks : self . param_update_callbacks [ paramname ] = Caller ( ) self . param_update_callbacks [ paramname ] . add_callback ( cb ) | Add a callback for a specific parameter name . This callback will be executed when a new value is read from the Crazyflie . |
39,539 | def refresh_toc ( self , refresh_done_callback , toc_cache ) : self . _useV2 = self . cf . platform . get_protocol_version ( ) >= 4 toc_fetcher = TocFetcher ( self . cf , ParamTocElement , CRTPPort . PARAM , self . toc , refresh_done_callback , toc_cache ) toc_fetcher . start ( ) | Initiate a refresh of the parameter TOC . |
39,540 | def _disconnected ( self , uri ) : self . param_updater . close ( ) self . is_updated = False self . toc = Toc ( ) self . values = { } | Disconnected callback from Crazyflie API |
39,541 | def request_param_update ( self , complete_name ) : self . param_updater . request_param_update ( self . toc . get_element_id ( complete_name ) ) | Request an update of the value for the supplied parameter . |
39,542 | def set_value ( self , complete_name , value ) : element = self . toc . get_element_by_complete_name ( complete_name ) if not element : logger . warning ( "Cannot set value for [%s], it's not in the TOC!" , complete_name ) raise KeyError ( '{} not in param TOC' . format ( complete_name ) ) elif element . access == ParamTocElement . RO_ACCESS : logger . debug ( '[%s] is read only, no trying to set value' , complete_name ) raise AttributeError ( '{} is read-only!' . format ( complete_name ) ) else : varid = element . ident pk = CRTPPacket ( ) pk . set_header ( CRTPPort . PARAM , WRITE_CHANNEL ) if self . _useV2 : pk . data = struct . pack ( '<H' , varid ) else : pk . data = struct . pack ( '<B' , varid ) try : value_nr = eval ( value ) except TypeError : value_nr = value pk . data += struct . pack ( element . pytype , value_nr ) self . param_updater . request_param_setvalue ( pk ) | Set the value for the supplied parameter . |
39,543 | def _new_packet_cb ( self , pk ) : if pk . channel == READ_CHANNEL or pk . channel == WRITE_CHANNEL : if self . _useV2 : var_id = struct . unpack ( '<H' , pk . data [ : 2 ] ) [ 0 ] if pk . channel == READ_CHANNEL : pk . data = pk . data [ : 2 ] + pk . data [ 3 : ] else : var_id = pk . data [ 0 ] if ( pk . channel != TOC_CHANNEL and self . _req_param == var_id and pk is not None ) : self . updated_callback ( pk ) self . _req_param = - 1 try : self . wait_lock . release ( ) except Exception : pass | Callback for newly arrived packets |
39,544 | def request_param_update ( self , var_id ) : self . _useV2 = self . cf . platform . get_protocol_version ( ) >= 4 pk = CRTPPacket ( ) pk . set_header ( CRTPPort . PARAM , READ_CHANNEL ) if self . _useV2 : pk . data = struct . pack ( '<H' , var_id ) else : pk . data = struct . pack ( '<B' , var_id ) logger . debug ( 'Requesting request to update param [%d]' , var_id ) self . request_queue . put ( pk ) | Place a param update request on the queue |
39,545 | def add_element ( self , element ) : try : self . toc [ element . group ] [ element . name ] = element except KeyError : self . toc [ element . group ] = { } self . toc [ element . group ] [ element . name ] = element | Add a new TocElement to the TOC container . |
39,546 | def get_element_id ( self , complete_name ) : [ group , name ] = complete_name . split ( '.' ) element = self . get_element ( group , name ) if element : return element . ident else : logger . warning ( 'Unable to find variable [%s]' , complete_name ) return None | Get the TocElement element id - number of the element with the supplied name . |
39,547 | def get_element_by_id ( self , ident ) : for group in list ( self . toc . keys ( ) ) : for name in list ( self . toc [ group ] . keys ( ) ) : if self . toc [ group ] [ name ] . ident == ident : return self . toc [ group ] [ name ] return None | Get a TocElement element identified by index number from the container . |
39,548 | def start ( self ) : self . _useV2 = self . cf . platform . get_protocol_version ( ) >= 4 logger . debug ( '[%d]: Using V2 protocol: %d' , self . port , self . _useV2 ) logger . debug ( '[%d]: Start fetching...' , self . port ) self . cf . add_port_callback ( self . port , self . _new_packet_cb ) self . state = GET_TOC_INFO pk = CRTPPacket ( ) pk . set_header ( self . port , TOC_CHANNEL ) if self . _useV2 : pk . data = ( CMD_TOC_INFO_V2 , ) self . cf . send_packet ( pk , expected_reply = ( CMD_TOC_INFO_V2 , ) ) else : pk . data = ( CMD_TOC_INFO , ) self . cf . send_packet ( pk , expected_reply = ( CMD_TOC_INFO , ) ) | Initiate fetching of the TOC . |
39,549 | def _toc_fetch_finished ( self ) : self . cf . remove_port_callback ( self . port , self . _new_packet_cb ) logger . debug ( '[%d]: Done!' , self . port ) self . finished_callback ( ) | Callback for when the TOC fetching is finished |
39,550 | def _new_packet_cb ( self , packet ) : chan = packet . channel if ( chan != 0 ) : return payload = packet . data [ 1 : ] if ( self . state == GET_TOC_INFO ) : if self . _useV2 : [ self . nbr_of_items , self . _crc ] = struct . unpack ( '<HI' , payload [ : 6 ] ) else : [ self . nbr_of_items , self . _crc ] = struct . unpack ( '<BI' , payload [ : 5 ] ) logger . debug ( '[%d]: Got TOC CRC, %d items and crc=0x%08X' , self . port , self . nbr_of_items , self . _crc ) cache_data = self . _toc_cache . fetch ( self . _crc ) if ( cache_data ) : self . toc . toc = cache_data logger . info ( 'TOC for port [%s] found in cache' % self . port ) self . _toc_fetch_finished ( ) else : self . state = GET_TOC_ELEMENT self . requested_index = 0 self . _request_toc_element ( self . requested_index ) elif ( self . state == GET_TOC_ELEMENT ) : if self . _useV2 : ident = struct . unpack ( '<H' , payload [ : 2 ] ) [ 0 ] else : ident = payload [ 0 ] if ident != self . requested_index : return if self . _useV2 : self . toc . add_element ( self . element_class ( ident , payload [ 2 : ] ) ) else : self . toc . add_element ( self . element_class ( ident , payload [ 1 : ] ) ) logger . debug ( 'Added element [%s]' , ident ) if ( self . requested_index < ( self . nbr_of_items - 1 ) ) : logger . debug ( '[%d]: More variables, requesting index %d' , self . port , self . requested_index + 1 ) self . requested_index = self . requested_index + 1 self . _request_toc_element ( self . requested_index ) else : self . _toc_cache . insert ( self . _crc , self . toc . toc ) self . _toc_fetch_finished ( ) | Handle a newly arrived packet |
39,551 | def _request_toc_element ( self , index ) : logger . debug ( 'Requesting index %d on port %d' , index , self . port ) pk = CRTPPacket ( ) if self . _useV2 : pk . set_header ( self . port , TOC_CHANNEL ) pk . data = ( CMD_TOC_ITEM_V2 , index & 0x0ff , ( index >> 8 ) & 0x0ff ) self . cf . send_packet ( pk , expected_reply = ( CMD_TOC_ITEM_V2 , index & 0x0ff , ( index >> 8 ) & 0x0ff ) ) else : pk . set_header ( self . port , TOC_CHANNEL ) pk . data = ( CMD_TOC_ELEMENT , index ) self . cf . send_packet ( pk , expected_reply = ( CMD_TOC_ELEMENT , index ) ) | Request information about a specific item in the TOC |
39,552 | def _start_connection_setup ( self ) : logger . info ( 'We are connected[%s], request connection setup' , self . link_uri ) self . platform . fetch_platform_informations ( self . _platform_info_fetched ) | Start the connection setup by refreshing the TOCs |
39,553 | def _param_toc_updated_cb ( self ) : logger . info ( 'Param TOC finished updating' ) self . connected_ts = datetime . datetime . now ( ) self . connected . call ( self . link_uri ) self . param . request_update_of_all_params ( ) | Called when the param TOC has been fully updated |
39,554 | def _mems_updated_cb ( self ) : logger . info ( 'Memories finished updating' ) self . param . refresh_toc ( self . _param_toc_updated_cb , self . _toc_cache ) | Called when the memories have been identified |
39,555 | def _link_error_cb ( self , errmsg ) : logger . warning ( 'Got link error callback [%s] in state [%s]' , errmsg , self . state ) if ( self . link is not None ) : self . link . close ( ) self . link = None if ( self . state == State . INITIALIZED ) : self . connection_failed . call ( self . link_uri , errmsg ) if ( self . state == State . CONNECTED or self . state == State . SETUP_FINISHED ) : self . disconnected . call ( self . link_uri ) self . connection_lost . call ( self . link_uri , errmsg ) self . state = State . DISCONNECTED | Called from the link driver when there s an error |
39,556 | def _check_for_initial_packet_cb ( self , data ) : self . state = State . CONNECTED self . link_established . call ( self . link_uri ) self . packet_received . remove_callback ( self . _check_for_initial_packet_cb ) | Called when first packet arrives from Crazyflie . |
39,557 | def close_link ( self ) : logger . info ( 'Closing link' ) if ( self . link is not None ) : self . commander . send_setpoint ( 0 , 0 , 0 , 0 ) if ( self . link is not None ) : self . link . close ( ) self . link = None self . _answer_patterns = { } self . disconnected . call ( self . link_uri ) | Close the communication link . |
39,558 | def _no_answer_do_retry ( self , pk , pattern ) : logger . info ( 'Resending for pattern %s' , pattern ) self . send_packet ( pk , expected_reply = pattern , resend = True ) | Resend packets that we have not gotten answers to |
39,559 | def _check_for_answers ( self , pk ) : longest_match = ( ) if len ( self . _answer_patterns ) > 0 : data = ( pk . header , ) + tuple ( pk . data ) for p in list ( self . _answer_patterns . keys ( ) ) : logger . debug ( 'Looking for pattern match on %s vs %s' , p , data ) if len ( p ) <= len ( data ) : if p == data [ 0 : len ( p ) ] : match = data [ 0 : len ( p ) ] if len ( match ) >= len ( longest_match ) : logger . debug ( 'Found new longest match %s' , match ) longest_match = match if len ( longest_match ) > 0 : self . _answer_patterns [ longest_match ] . cancel ( ) del self . _answer_patterns [ longest_match ] | Callback called for every packet received to check if we are waiting for an answer on this port . If so then cancel the retry timer . |
39,560 | def send_packet ( self , pk , expected_reply = ( ) , resend = False , timeout = 0.2 ) : self . _send_lock . acquire ( ) if self . link is not None : if len ( expected_reply ) > 0 and not resend and self . link . needs_resending : pattern = ( pk . header , ) + expected_reply logger . debug ( 'Sending packet and expecting the %s pattern back' , pattern ) new_timer = Timer ( timeout , lambda : self . _no_answer_do_retry ( pk , pattern ) ) self . _answer_patterns [ pattern ] = new_timer new_timer . start ( ) elif resend : pattern = expected_reply if pattern in self . _answer_patterns : logger . debug ( 'We want to resend and the pattern is there' ) if self . _answer_patterns [ pattern ] : new_timer = Timer ( timeout , lambda : self . _no_answer_do_retry ( pk , pattern ) ) self . _answer_patterns [ pattern ] = new_timer new_timer . start ( ) else : logger . debug ( 'Resend requested, but no pattern found: %s' , self . _answer_patterns ) self . link . send_packet ( pk ) self . packet_sent . call ( pk ) self . _send_lock . release ( ) | Send a packet through the link interface . |
39,561 | def add_port_callback ( self , port , cb ) : logger . debug ( 'Adding callback on port [%d] to [%s]' , port , cb ) self . add_header_callback ( cb , port , 0 , 0xff , 0x0 ) | Add a callback for data that comes on a specific port |
39,562 | def remove_port_callback ( self , port , cb ) : logger . debug ( 'Removing callback on port [%d] to [%s]' , port , cb ) for port_callback in self . cb : if port_callback . port == port and port_callback . callback == cb : self . cb . remove ( port_callback ) | Remove a callback for data that comes on a specific port |
39,563 | def add_variable ( self , name , fetch_as = None ) : if fetch_as : self . variables . append ( LogVariable ( name , fetch_as ) ) else : self . default_fetch_as . append ( name ) | Add a new variable to the configuration . |
39,564 | def add_memory ( self , name , fetch_as , stored_as , address ) : self . variables . append ( LogVariable ( name , fetch_as , LogVariable . MEM_TYPE , stored_as , address ) ) | Add a raw memory position to log . |
39,565 | def create ( self ) : pk = CRTPPacket ( ) pk . set_header ( 5 , CHAN_SETTINGS ) if self . useV2 : pk . data = ( CMD_CREATE_BLOCK_V2 , self . id ) else : pk . data = ( CMD_CREATE_BLOCK , self . id ) for var in self . variables : if ( var . is_toc_variable ( ) is False ) : logger . debug ( 'Logging to raw memory %d, 0x%04X' , var . get_storage_and_fetch_byte ( ) , var . address ) pk . data . append ( struct . pack ( '<B' , var . get_storage_and_fetch_byte ( ) ) ) pk . data . append ( struct . pack ( '<I' , var . address ) ) else : logger . debug ( 'Adding %s with id=%d and type=0x%02X' , var . name , self . cf . log . toc . get_element_id ( var . name ) , var . get_storage_and_fetch_byte ( ) ) pk . data . append ( var . get_storage_and_fetch_byte ( ) ) if self . useV2 : ident = self . cf . log . toc . get_element_id ( var . name ) pk . data . append ( ident & 0x0ff ) pk . data . append ( ( ident >> 8 ) & 0x0ff ) else : pk . data . append ( self . cf . log . toc . get_element_id ( var . name ) ) logger . debug ( 'Adding log block id {}' . format ( self . id ) ) if self . useV2 : self . cf . send_packet ( pk , expected_reply = ( CMD_CREATE_BLOCK_V2 , self . id ) ) else : self . cf . send_packet ( pk , expected_reply = ( CMD_CREATE_BLOCK , self . id ) ) | Save the log configuration in the Crazyflie |
39,566 | def start ( self ) : if ( self . cf . link is not None ) : if ( self . _added is False ) : self . create ( ) logger . debug ( 'First time block is started, add block' ) else : logger . debug ( 'Block already registered, starting logging' ' for id=%d' , self . id ) pk = CRTPPacket ( ) pk . set_header ( 5 , CHAN_SETTINGS ) pk . data = ( CMD_START_LOGGING , self . id , self . period ) self . cf . send_packet ( pk , expected_reply = ( CMD_START_LOGGING , self . id ) ) | Start the logging for this entry |
39,567 | def stop ( self ) : if ( self . cf . link is not None ) : if ( self . id is None ) : logger . warning ( 'Stopping block, but no block registered' ) else : logger . debug ( 'Sending stop logging for block id=%d' , self . id ) pk = CRTPPacket ( ) pk . set_header ( 5 , CHAN_SETTINGS ) pk . data = ( CMD_STOP_LOGGING , self . id ) self . cf . send_packet ( pk , expected_reply = ( CMD_STOP_LOGGING , self . id ) ) | Stop the logging for this entry |
39,568 | def delete ( self ) : if ( self . cf . link is not None ) : if ( self . id is None ) : logger . warning ( 'Delete block, but no block registered' ) else : logger . debug ( 'LogEntry: Sending delete logging for block id=%d' % self . id ) pk = CRTPPacket ( ) pk . set_header ( 5 , CHAN_SETTINGS ) pk . data = ( CMD_DELETE_BLOCK , self . id ) self . cf . send_packet ( pk , expected_reply = ( CMD_DELETE_BLOCK , self . id ) ) | Delete this entry in the Crazyflie |
39,569 | def unpack_log_data ( self , log_data , timestamp ) : ret_data = { } data_index = 0 for var in self . variables : size = LogTocElement . get_size_from_id ( var . fetch_as ) name = var . name unpackstring = LogTocElement . get_unpack_string_from_id ( var . fetch_as ) value = struct . unpack ( unpackstring , log_data [ data_index : data_index + size ] ) [ 0 ] data_index += size ret_data [ name ] = value self . data_received_cb . call ( timestamp , ret_data , self ) | Unpack received logging data so it represent real values according to the configuration in the entry |
39,570 | def get_id_from_cstring ( name ) : for key in list ( LogTocElement . types . keys ( ) ) : if ( LogTocElement . types [ key ] [ 0 ] == name ) : return key raise KeyError ( 'Type [%s] not found in LogTocElement.types!' % name ) | Return variable type id given the C - storage name |
39,571 | def add_config ( self , logconf ) : if not self . cf . link : logger . error ( 'Cannot add configs without being connected to a ' 'Crazyflie!' ) return for name in logconf . default_fetch_as : var = self . toc . get_element_by_complete_name ( name ) if not var : logger . warning ( '%s not in TOC, this block cannot be used!' , name ) logconf . valid = False raise KeyError ( 'Variable {} not in TOC' . format ( name ) ) logconf . add_variable ( name , var . ctype ) size = 0 for var in logconf . variables : size += LogTocElement . get_size_from_id ( var . fetch_as ) if var . is_toc_variable ( ) : if ( self . toc . get_element_by_complete_name ( var . name ) is None ) : logger . warning ( 'Log: %s not in TOC, this block cannot be used!' , var . name ) logconf . valid = False raise KeyError ( 'Variable {} not in TOC' . format ( var . name ) ) if ( size <= MAX_LOG_DATA_PACKET_SIZE and ( logconf . period > 0 and logconf . period < 0xFF ) ) : logconf . valid = True logconf . cf = self . cf logconf . id = self . _config_id_counter logconf . useV2 = self . _useV2 self . _config_id_counter = ( self . _config_id_counter + 1 ) % 255 self . log_blocks . append ( logconf ) self . block_added_cb . call ( logconf ) else : logconf . valid = False raise AttributeError ( 'The log configuration is too large or has an invalid ' 'parameter' ) | Add a log configuration to the logging framework . |
39,572 | def refresh_toc ( self , refresh_done_callback , toc_cache ) : self . _useV2 = self . cf . platform . get_protocol_version ( ) >= 4 self . _toc_cache = toc_cache self . _refresh_callback = refresh_done_callback self . toc = None pk = CRTPPacket ( ) pk . set_header ( CRTPPort . LOGGING , CHAN_SETTINGS ) pk . data = ( CMD_RESET_LOGGING , ) self . cf . send_packet ( pk , expected_reply = ( CMD_RESET_LOGGING , ) ) | Start refreshing the table of loggale variables |
39,573 | def init_drivers ( enable_debug_driver = False ) : for driver in DRIVERS : try : if driver != DebugDriver or enable_debug_driver : CLASSES . append ( driver ) except Exception : continue | Initialize all the drivers . |
39,574 | def scan_interfaces ( address = None ) : available = [ ] found = [ ] for driverClass in CLASSES : try : logger . debug ( 'Scanning: %s' , driverClass ) instance = driverClass ( ) found = instance . scan_interface ( address ) available += found except Exception : raise return available | Scan all the interfaces for available Crazyflies |
39,575 | def get_interfaces_status ( ) : status = { } for driverClass in CLASSES : try : instance = driverClass ( ) status [ instance . get_name ( ) ] = instance . get_status ( ) except Exception : raise return status | Get the status of all the interfaces |
39,576 | def get_link_driver ( uri , link_quality_callback = None , link_error_callback = None ) : for driverClass in CLASSES : try : instance = driverClass ( ) instance . connect ( uri , link_quality_callback , link_error_callback ) return instance except WrongUriType : continue return None | Return the link driver for the given URI . Returns None if no driver was found for the URI or the URI was not well formatted for the matching driver . |
39,577 | def send_short_lpp_packet ( self , dest_id , data ) : pk = CRTPPacket ( ) pk . port = CRTPPort . LOCALIZATION pk . channel = self . GENERIC_CH pk . data = struct . pack ( '<BB' , self . LPS_SHORT_LPP_PACKET , dest_id ) + data self . _cf . send_packet ( pk ) | Send ultra - wide - band LPP packet to dest_id |
39,578 | def send_velocity_world_setpoint ( self , vx , vy , vz , yawrate ) : pk = CRTPPacket ( ) pk . port = CRTPPort . COMMANDER_GENERIC pk . data = struct . pack ( '<Bffff' , TYPE_VELOCITY_WORLD , vx , vy , vz , yawrate ) self . _cf . send_packet ( pk ) | Send Velocity in the world frame of reference setpoint . |
39,579 | def send_position_setpoint ( self , x , y , z , yaw ) : pk = CRTPPacket ( ) pk . port = CRTPPort . COMMANDER_GENERIC pk . data = struct . pack ( '<Bffff' , TYPE_POSITION , x , y , z , yaw ) self . _cf . send_packet ( pk ) | Control mode where the position is sent as absolute x y z coordinate in meter and the yaw is the absolute orientation . |
39,580 | def type_to_string ( t ) : if t == MemoryElement . TYPE_I2C : return 'I2C' if t == MemoryElement . TYPE_1W : return '1-wire' if t == MemoryElement . TYPE_DRIVER_LED : return 'LED driver' if t == MemoryElement . TYPE_LOCO : return 'Loco Positioning' if t == MemoryElement . TYPE_TRAJ : return 'Trajectory' if t == MemoryElement . TYPE_LOCO2 : return 'Loco Positioning 2' return 'Unknown' | Get string representation of memory type |
39,581 | def write_data ( self , write_finished_cb ) : self . _write_finished_cb = write_finished_cb data = bytearray ( ) for led in self . leds : R5 = ( ( int ) ( ( ( ( int ( led . r ) & 0xFF ) * 249 + 1014 ) >> 11 ) & 0x1F ) * led . intensity / 100 ) G6 = ( ( int ) ( ( ( ( int ( led . g ) & 0xFF ) * 253 + 505 ) >> 10 ) & 0x3F ) * led . intensity / 100 ) B5 = ( ( int ) ( ( ( ( int ( led . b ) & 0xFF ) * 249 + 1014 ) >> 11 ) & 0x1F ) * led . intensity / 100 ) tmp = ( int ( R5 ) << 11 ) | ( int ( G6 ) << 5 ) | ( int ( B5 ) << 0 ) data += bytearray ( ( tmp >> 8 , tmp & 0xFF ) ) self . mem_handler . write ( self , 0x00 , data , flush_queue = True ) | Write the saved LED - ring data to the Crazyflie |
39,582 | def _parse_and_check_elements ( self , data ) : crc = data [ - 1 ] test_crc = crc32 ( data [ : - 1 ] ) & 0x0ff elem_data = data [ 2 : - 1 ] if test_crc == crc : while len ( elem_data ) > 0 : ( eid , elen ) = struct . unpack ( 'BB' , elem_data [ : 2 ] ) self . elements [ self . element_mapping [ eid ] ] = elem_data [ 2 : 2 + elen ] . decode ( 'ISO-8859-1' ) elem_data = elem_data [ 2 + elen : ] return True return False | Parse and check the CRC and length of the elements part of the memory |
39,583 | def _parse_and_check_header ( self , data ) : ( start , self . pins , self . vid , self . pid , crc ) = struct . unpack ( '<BIBBB' , data ) test_crc = crc32 ( data [ : - 1 ] ) & 0x0ff if start == 0xEB and crc == test_crc : return True return False | Parse and check the CRC of the header part of the memory |
39,584 | def update_id_list ( self , update_ids_finished_cb ) : if not self . _update_ids_finished_cb : self . _update_ids_finished_cb = update_ids_finished_cb self . anchor_ids = [ ] self . active_anchor_ids = [ ] self . anchor_data = { } self . nr_of_anchors = 0 self . ids_valid = False self . data_valid = False logger . debug ( 'Updating ids of memory {}' . format ( self . id ) ) self . mem_handler . read ( self , LocoMemory2 . ADR_ID_LIST , LocoMemory2 . ID_LIST_LEN ) | Request an update of the id list |
39,585 | def update_active_id_list ( self , update_active_ids_finished_cb ) : if not self . _update_active_ids_finished_cb : self . _update_active_ids_finished_cb = update_active_ids_finished_cb self . active_anchor_ids = [ ] self . active_ids_valid = False logger . debug ( 'Updating active ids of memory {}' . format ( self . id ) ) self . mem_handler . read ( self , LocoMemory2 . ADR_ACTIVE_ID_LIST , LocoMemory2 . ID_LIST_LEN ) | Request an update of the active id list |
39,586 | def update_data ( self , update_data_finished_cb ) : if not self . _update_data_finished_cb and self . nr_of_anchors > 0 : self . _update_data_finished_cb = update_data_finished_cb self . anchor_data = { } self . data_valid = False self . _nr_of_anchors_to_fetch = self . nr_of_anchors logger . debug ( 'Updating anchor data of memory {}' . format ( self . id ) ) self . _currently_fetching_index = 0 self . _request_page ( self . anchor_ids [ self . _currently_fetching_index ] ) | Request an update of the anchor data |
39,587 | def write_data ( self , write_finished_cb ) : self . _write_finished_cb = write_finished_cb data = bytearray ( ) for poly4D in self . poly4Ds : data += struct . pack ( '<ffffffff' , * poly4D . x . values ) data += struct . pack ( '<ffffffff' , * poly4D . y . values ) data += struct . pack ( '<ffffffff' , * poly4D . z . values ) data += struct . pack ( '<ffffffff' , * poly4D . yaw . values ) data += struct . pack ( '<f' , poly4D . duration ) self . mem_handler . write ( self , 0x00 , data , flush_queue = True ) | Write trajectory data to the Crazyflie |
39,588 | def get_mem ( self , id ) : for m in self . mems : if m . id == id : return m return None | Fetch the memory with the supplied id |
39,589 | def get_mems ( self , type ) : ret = ( ) for m in self . mems : if m . type == type : ret += ( m , ) return ret | Fetch all the memories of the supplied type |
39,590 | def write ( self , memory , addr , data , flush_queue = False ) : wreq = _WriteRequest ( memory , addr , data , self . cf ) if memory . id not in self . _write_requests : self . _write_requests [ memory . id ] = [ ] self . _write_requests_lock . acquire ( ) if flush_queue : self . _write_requests [ memory . id ] = self . _write_requests [ memory . id ] [ : 1 ] self . _write_requests [ memory . id ] . insert ( len ( self . _write_requests ) , wreq ) if len ( self . _write_requests [ memory . id ] ) == 1 : wreq . start ( ) self . _write_requests_lock . release ( ) return True | Write the specified data to the given memory at the given address |
39,591 | def read ( self , memory , addr , length ) : if memory . id in self . _read_requests : logger . warning ( 'There is already a read operation ongoing for ' 'memory id {}' . format ( memory . id ) ) return False rreq = _ReadRequest ( memory , addr , length , self . cf ) self . _read_requests [ memory . id ] = rreq rreq . start ( ) return True | Read the specified amount of bytes from the given memory at the given address |
39,592 | def refresh ( self , refresh_done_callback ) : self . _refresh_callback = refresh_done_callback self . _fetch_id = 0 for m in self . mems : try : self . mem_read_cb . remove_callback ( m . new_data ) m . disconnect ( ) except Exception as e : logger . info ( 'Error when removing memory after update: {}' . format ( e ) ) self . mems = [ ] self . nbr_of_mems = 0 self . _getting_count = False logger . debug ( 'Requesting number of memories' ) pk = CRTPPacket ( ) pk . set_header ( CRTPPort . MEM , CHAN_INFO ) pk . data = ( CMD_INFO_NBR , ) self . cf . send_packet ( pk , expected_reply = ( CMD_INFO_NBR , ) ) | Start fetching all the detected memories |
39,593 | def reset_to_bootloader1 ( self , cpu_id ) : pk = CRTPPacket ( ) pk . port = CRTPPort . LINKCTRL pk . data = ( 1 , 2 , 3 ) + cpu_id self . link . send_packet ( pk ) pk = None while True : pk = self . link . receive_packet ( 2 ) if not pk : return False if pk . port == CRTPPort . LINKCTRL : break pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = ( 0xFF , 0xFE ) + cpu_id self . link . send_packet ( pk ) pk = None while True : pk = self . link . receive_packet ( 2 ) if not pk : return False if pk . port == 0xFF and tuple ( pk . data ) == ( 0xFF , 0xFE ) + cpu_id : pk . data = ( 0xFF , 0xF0 ) + cpu_id self . link . send_packet ( pk ) break time . sleep ( 0.1 ) self . link . close ( ) self . link = cflib . crtp . get_link_driver ( self . clink_address ) return self . _update_info ( ) | Reset to the bootloader The parameter cpuid shall correspond to the device to reset . |
39,594 | def reset_to_firmware ( self , target_id ) : fake_cpu_id = ( 1 , 2 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ) pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = ( target_id , 0xFF ) + fake_cpu_id self . link . send_packet ( pk ) pk = None while True : pk = self . link . receive_packet ( 2 ) if not pk : return False if ( pk . header == 0xFF and struct . unpack ( 'B' * len ( pk . data ) , pk . data ) [ : 2 ] == ( target_id , 0xFF ) ) : if target_id == 0xFE : pk . data = ( target_id , 0xF0 , 0x01 ) else : pk . data = ( target_id , 0xF0 ) + fake_cpu_id self . link . send_packet ( pk ) break time . sleep ( 0.1 ) | Reset to firmware The parameter cpuid shall correspond to the device to reset . |
39,595 | def check_link_and_get_info ( self , target_id = 0xFF ) : for _ in range ( 0 , 5 ) : if self . _update_info ( target_id ) : if self . _in_boot_cb : self . _in_boot_cb . call ( True , self . targets [ target_id ] . protocol_version ) if self . _info_cb : self . _info_cb . call ( self . targets [ target_id ] ) return True return False | Try to get a connection with the bootloader by requesting info 5 times . This let roughly 10 seconds to boot the copter ... |
39,596 | def _update_info ( self , target_id ) : pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = ( target_id , 0x10 ) self . link . send_packet ( pk ) pk = self . link . receive_packet ( 2 ) if ( pk and pk . header == 0xFF and struct . unpack ( '<BB' , pk . data [ 0 : 2 ] ) == ( target_id , 0x10 ) ) : tab = struct . unpack ( 'BBHHHH' , pk . data [ 0 : 10 ] ) cpuid = struct . unpack ( 'B' * 12 , pk . data [ 10 : 22 ] ) if target_id not in self . targets : self . targets [ target_id ] = Target ( target_id ) self . targets [ target_id ] . addr = target_id if len ( pk . data ) > 22 : self . targets [ target_id ] . protocol_version = pk . datat [ 22 ] self . protocol_version = pk . datat [ 22 ] self . targets [ target_id ] . page_size = tab [ 2 ] self . targets [ target_id ] . buffer_pages = tab [ 3 ] self . targets [ target_id ] . flash_pages = tab [ 4 ] self . targets [ target_id ] . start_page = tab [ 5 ] self . targets [ target_id ] . cpuid = '%02X' % cpuid [ 0 ] for i in cpuid [ 1 : ] : self . targets [ target_id ] . cpuid += ':%02X' % i if ( self . protocol_version == 0x10 and target_id == TargetTypes . STM32 ) : self . _update_mapping ( target_id ) return True return False | Call the command getInfo and fill up the information received in the fields of the object |
39,597 | def upload_buffer ( self , target_id , page , address , buff ) : count = 0 pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = struct . pack ( '=BBHH' , target_id , 0x14 , page , address ) for i in range ( 0 , len ( buff ) ) : pk . data . append ( buff [ i ] ) count += 1 if count > 24 : self . link . send_packet ( pk ) count = 0 pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = struct . pack ( '=BBHH' , target_id , 0x14 , page , i + address + 1 ) self . link . send_packet ( pk ) | Upload data into a buffer on the Crazyflie |
39,598 | def read_flash ( self , addr = 0xFF , page = 0x00 ) : buff = bytearray ( ) page_size = self . targets [ addr ] . page_size for i in range ( 0 , int ( math . ceil ( page_size / 25.0 ) ) ) : pk = None retry_counter = 5 while ( ( not pk or pk . header != 0xFF or struct . unpack ( '<BB' , pk . data [ 0 : 2 ] ) != ( addr , 0x1C ) ) and retry_counter >= 0 ) : pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = struct . pack ( '<BBHH' , addr , 0x1C , page , ( i * 25 ) ) self . link . send_packet ( pk ) pk = self . link . receive_packet ( 1 ) retry_counter -= 1 if ( retry_counter < 0 ) : return None else : buff += pk . data [ 6 : ] return buff [ 0 : page_size ] | Read back a flash page from the Crazyflie and return it |
39,599 | def write_flash ( self , addr , page_buffer , target_page , page_count ) : pk = None pk = self . link . receive_packet ( 0 ) while pk is not None : pk = self . link . receive_packet ( 0 ) retry_counter = 5 while ( ( not pk or pk . header != 0xFF or struct . unpack ( '<BB' , pk . data [ 0 : 2 ] ) != ( addr , 0x18 ) ) and retry_counter >= 0 ) : pk = CRTPPacket ( ) pk . set_header ( 0xFF , 0xFF ) pk . data = struct . pack ( '<BBHHH' , addr , 0x18 , page_buffer , target_page , page_count ) self . link . send_packet ( pk ) pk = self . link . receive_packet ( 1 ) retry_counter -= 1 if retry_counter < 0 : self . error_code = - 1 return False self . error_code = pk . data [ 3 ] return pk . data [ 2 ] == 1 | Initiate flashing of data in the buffer to flash . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.