INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Connect to the crazyflie.
def connect(self): """ Connect to the crazyflie. """ print('Connecting to %s' % self._link_uri) self._cf.open_link(self._link_uri)
Busy loop until connection is established. Will abort after timeout (seconds). Return value is a boolean, whether connection could be established.
def wait_for_connection(self, timeout=10): """ Busy loop until connection is established. Will abort after timeout (seconds). Return value is a boolean, whether connection could be established. """ 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)
Search and return list of 1-wire memories.
def search_memories(self): """ Search and return list of 1-wire memories. """ if not self.connected: raise NotConnected() return self._cf.mem.get_mems(MemoryElement.TYPE_1W)
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) self._cf.packet_received.add_callback(self._got_packet)
Callback froma the log API when data arrives
def _stab_log_data(self, timestamp, data, logconf): """Callback froma the log API when data arrives""" print('[%d][%s]: %s' % (timestamp, logconf.name, data))
Callback when connection initial connection fails (i.e no Crazyflie at the speficied address)
def _connection_failed(self, link_uri, msg): """Callback when connection initial connection fails (i.e no Crazyflie at the speficied address)""" print('Connection to %s failed: %s' % (link_uri, msg)) self.is_connected = False
Fetch platform info from the firmware Should be called at the earliest in the connection sequence
def fetch_platform_informations(self, callback): """ Fetch platform info from the firmware Should be called at the earliest in the connection sequence """ self._protocolVersion = -1 self._callback = callback self._request_protocol_version()
Enable/disable the client side X-mode. When enabled this recalculates the setpoints before sending them to the Crazyflie.
def set_continous_wave(self, enabled): """ Enable/disable the client side X-mode. When enabled this recalculates the setpoints before sending them to the Crazyflie. """ pk = CRTPPacket() pk.set_header(CRTPPort.PLATFORM, PLATFORM_COMMAND) pk.data = (0, enabled) self._cf.send_packet(pk)
Connect the link driver to a specified URI of the format: radio://<dongle nbr>/<radio channel>/[250K,1M,2M] The callback for linkQuality can be called at any moment from the driver to report back the link quality in percentage. The callback from linkError will be called when a error occues with an error message.
def connect(self, uri, link_quality_callback, link_error_callback): """ Connect the link driver to a specified URI of the format: radio://<dongle nbr>/<radio channel>/[250K,1M,2M] The callback for linkQuality can be called at any moment from the driver to report back the link quality in percentage. The callback from linkError will be called when a error occues with an error message. """ # check if the URI is a radio URI if not re.search('^usb://', uri): raise WrongUriType('Not a radio URI') # Open the USB dongle if not re.search('^usb://([0-9]+)$', uri): raise WrongUriType('Wrong radio URI format!') uri_data = re.search('^usb://([0-9]+)$', uri) self.uri = uri if self.cfusb is None: self.cfusb = CfUsb(devid=int(uri_data.group(1))) if self.cfusb.dev: self.cfusb.set_crtp_to_usb(True) else: self.cfusb = None raise Exception('Could not open {}'.format(self.uri)) else: raise Exception('Link already open!') # Prepare the inter-thread communication queue self.in_queue = queue.Queue() # Limited size out queue to avoid "ReadBack" effect self.out_queue = queue.Queue(50) # Launch the comm thread self._thread = _UsbReceiveThread(self.cfusb, self.in_queue, link_quality_callback, link_error_callback) self._thread.start() self.link_error_callback = link_error_callback
Receive a packet though the link. This call is blocking but will timeout and return None if a timeout is supplied.
def receive_packet(self, time=0): """ Receive a packet though the link. This call is blocking but will timeout and return None if a timeout is supplied. """ 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
Send the packet pk though the link
def send_packet(self, pk): """ Send the packet pk though the link """ # if self.out_queue.full(): # self.out_queue.get() if (self.cfusb is None): return try: dataOut = (pk.header,) dataOut += pk.datat self.cfusb.send_packet(dataOut) except queue.Full: if self.link_error_callback: self.link_error_callback( 'UsbDriver: Could not send packet to Crazyflie')
Close the link.
def close(self): """ Close the link. """ # Stop the comm thread self._thread.stop() # Close the USB dongle try: if self.cfusb: self.cfusb.set_crtp_to_usb(False) self.cfusb.close() except Exception as e: # If we pull out the dongle we will not make this call logger.info('Could not close {}'.format(e)) pass self.cfusb = None
Scan interface for Crazyflies
def scan_interface(self, address): """ Scan interface for Crazyflies """ if self.cfusb is None: try: self.cfusb = CfUsb() except Exception as e: logger.warn( 'Exception while scanning for Crazyflie USB: {}'.format( str(e))) return [] else: raise Exception('Cannot scan for links while the link is open!') # FIXME: implements serial number in the Crazyradio driver! # serial = "N/A" found = self.cfusb.scan() self.cfusb.close() self.cfusb = None return found
Run the receiver thread
def run(self): """ Run the receiver thread """ while (True): if (self.sp): break try: # Blocking until USB data available data = self.cfusb.receive_packet() if len(data) > 0: pk = CRTPPacket(data[0], list(data[1:])) self.in_queue.put(pk) except Exception as e: import traceback self.link_error_callback( 'Error communicating with the Crazyflie' ' ,it has probably been unplugged!\n' 'Exception:%s\n\n%s' % (e, traceback.format_exc()))
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) mems = self._cf.mem.get_mems(MemoryElement.TYPE_1W) self._mems_to_update = len(mems) print('Found {} 1-wire memories'.format(len(mems))) for m in mems: print('Updating id={}'.format(m.id)) m.update(self._data_updated)
Register cb as a new callback. Will not register duplicates.
def add_callback(self, cb): """ Register cb as a new callback. Will not register duplicates. """ if ((cb in self.callbacks) is False): self.callbacks.append(cb)
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) self._is_link_open = True self._connect_event.set()
Callback when connection initial connection fails (i.e no Crazyflie at the specified address)
def _connection_failed(self, link_uri, msg): """Callback when connection initial connection fails (i.e no Crazyflie at the specified address)""" print('Connection to %s failed: %s' % (link_uri, msg)) self._is_link_open = False self._error_message = msg self._connect_event.set()
Read a flash page from the specified target
def read_cf1_config(self): """Read a flash page from the specified target""" target = self._cload.targets[0xFF] config_page = target.flash_pages - 1 return self._cload.read_flash(addr=0xFF, page=config_page)
Returns a list of CrazyRadio devices currently connected to the computer
def _find_devices(serial=None): """ Returns a list of CrazyRadio devices currently connected to the computer """ ret = [] if pyusb1: for d in usb.core.find(idVendor=0x1915, idProduct=0x7777, find_all=1, backend=pyusb_backend): if serial is not None and serial == d.serial_number: return d ret.append(d) else: busses = usb.busses() for bus in busses: for device in bus.devices: if device.idVendor == CRADIO_VID: if device.idProduct == CRADIO_PID: if serial == device.serial_number: return device ret += [device, ] return ret
Set the radio channel to be used
def set_channel(self, channel): """ Set the radio channel to be used """ if channel != self.current_channel: _send_vendor_setup(self.handle, SET_RADIO_CHANNEL, channel, 0, ()) self.current_channel = channel
Set the radio address to be used
def set_address(self, address): """ Set the radio address to be used""" 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 datarate to be used
def set_data_rate(self, datarate): """ Set the radio datarate to be used """ if datarate != self.current_datarate: _send_vendor_setup(self.handle, SET_DATA_RATE, datarate, 0, ()) self.current_datarate = datarate
Set the ACK retry count for radio communication
def set_arc(self, arc): """ Set the ACK retry count for radio communication """ _send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ()) self.arc = arc
Set the ACK retry delay for radio communication
def set_ard_time(self, us): """ Set the ACK retry delay for radio communication """ # Auto Retransmit Delay: # 0000 - Wait 250uS # 0001 - Wait 500uS # 0010 - Wait 750uS # ........ # 1111 - Wait 4000uS # Round down, to value representing a multiple of 250uS 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, ())
Send a packet and receive the ack from the radio dongle The ack contains information about the packet transmition and a data payload if the ack packet contained any
def send_packet(self, dataOut): """ Send a packet and receive the ack from the radio dongle The ack contains information about the packet transmition and a data payload if the ack packet contained any """ ackIn = None data = None try: if (pyusb1 is False): self.handle.bulkWrite(1, dataOut, 1000) data = self.handle.bulkRead(0x81, 64, 1000) else: self.handle.write(endpoint=1, data=dataOut, timeout=1000) data = self.handle.read(0x81, 64, timeout=1000) except usb.USBError: pass if data is not None: ackIn = _radio_ack() if data[0] != 0: ackIn.ack = (data[0] & 0x01) != 0 ackIn.powerDet = (data[0] & 0x02) != 0 ackIn.retry = data[0] >> 4 ackIn.data = data[1:] else: ackIn.retry = self.arc return ackIn
Callback for data received from the copter.
def incoming(self, packet): """ Callback for data received from the copter. """ # This might be done prettier ;-) console_text = packet.data.decode('UTF-8') self.receivedChar.call(console_text)
Send the current Crazyflie X, Y, Z position. This is going to be forwarded to the Crazyflie's position estimator.
def send_extpos(self, x, y, z): """ Send the current Crazyflie X, Y, Z position. This is going to be forwarded to the Crazyflie's position estimator. """ self._cf.loc.send_extpos([x, y, z])
Try to get a hit in the cache, return None otherwise
def fetch(self, crc): """ Try to get a hit in the cache, return None otherwise """ 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
Save a new cache to file
def insert(self, crc, toc): """ Save a new cache to file """ 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')
Encode a toc element leaf-node
def _encoder(self, obj): """ Encode a toc element leaf-node """ 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')
Decode a toc element leaf-node
def _decoder(self, obj): """ Decode a toc element leaf-node """ 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
Send a packet with a position to one anchor. :param anchor_id: The id of the targeted anchor. This is the first byte of the anchor address. :param position: The position of the anchor, as an array
def set_position(self, anchor_id, position): """ Send a packet with a position to one anchor. :param anchor_id: The id of the targeted anchor. This is the first byte of the anchor address. :param position: The position of the anchor, as an array """ x = position[0] y = position[1] z = position[2] data = struct.pack('<Bfff', LoPoAnchor.LPP_TYPE_POSITION, x, y, z) 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.
def set_mode(self, anchor_id, mode): """ Send a packet to set the anchor mode. If the anchor receive the packet, it will change mode and resets. """ data = struct.pack('<BB', LoPoAnchor.LPP_TYPE_MODE, mode) self.crazyflie.loc.send_short_lpp_packet(anchor_id, data)
Open links to all individuals in the swarm
def open_links(self): """ Open links to all individuals in the swarm """ 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
Close all open links
def close_links(self): """ Close all open links """ for uri, cf in self._cfs.items(): cf.close_link() self._is_open = False
Execute a function for all Crazyflies in the swarm, in sequence. The first argument of the function that is passed in will be a SyncCrazyflie instance connected to the Crazyflie to operate on. A list of optional parameters (per Crazyflie) may follow defined by the args_dict. The dictionary is keyed on URI. Example: def my_function(scf, optional_param0, optional_param1) ... args_dict = { URI0: [optional_param0_cf0, optional_param1_cf0], URI1: [optional_param0_cf1, optional_param1_cf1], ... } self.sequential(my_function, args_dict) :param func: the function to execute :param args_dict: parameters to pass to the function
def sequential(self, func, args_dict=None): """ Execute a function for all Crazyflies in the swarm, in sequence. The first argument of the function that is passed in will be a SyncCrazyflie instance connected to the Crazyflie to operate on. A list of optional parameters (per Crazyflie) may follow defined by the args_dict. The dictionary is keyed on URI. Example: def my_function(scf, optional_param0, optional_param1) ... args_dict = { URI0: [optional_param0_cf0, optional_param1_cf0], URI1: [optional_param0_cf1, optional_param1_cf1], ... } self.sequential(my_function, args_dict) :param func: the function to execute :param args_dict: parameters to pass to the function """ 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 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. For a description of the arguments, see sequential() :param func: :param args_dict:
def parallel_safe(self, func, args_dict=None): """ 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. For a description of the arguments, see sequential() :param func: :param args_dict: """ 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')
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. :param height: the height (meters) to hover at. None uses the default height set when constructed. :param velocity: the velocity (meters/second) when taking off :return:
def take_off(self, height=DEFAULT, velocity=DEFAULT): """ 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. :param height: the height (meters) to hover at. None uses the default height set when constructed. :param velocity: the velocity (meters/second) when taking off :return: """ 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
Go straight down and turn off the motors. Do not call this function if you use the with keyword. Landing is done automatically when the context goes out of scope. :param velocity: The velocity (meters/second) when going down :return:
def land(self, velocity=DEFAULT): """ Go straight down and turn off the motors. Do not call this function if you use the with keyword. Landing is done automatically when the context goes out of scope. :param velocity: The velocity (meters/second) when going down :return: """ if self._is_flying: duration_s = self._z / self._velocity(velocity) self._hl_commander.land(0, duration_s) time.sleep(duration_s) self._z = 0.0 self._hl_commander.stop() self._is_flying = False
Move in a straight line. positive X is forward positive Y is left positive Z is up :param distance_x_m: The distance to travel along the X-axis (meters) :param distance_y_m: The distance to travel along the Y-axis (meters) :param distance_z_m: The distance to travel along the Z-axis (meters) :param velocity: the velocity of the motion (meters/second) :return:
def move_distance(self, distance_x_m, distance_y_m, distance_z_m, velocity=DEFAULT): """ Move in a straight line. positive X is forward positive Y is left positive Z is up :param distance_x_m: The distance to travel along the X-axis (meters) :param distance_y_m: The distance to travel along the Y-axis (meters) :param distance_z_m: The distance to travel along the Z-axis (meters) :param velocity: the velocity of the motion (meters/second) :return: """ x = self._x + distance_x_m y = self._y + distance_y_m z = self._z + distance_z_m self.go_to(x, y, z, velocity)
Go to a position :param x: X coordinate :param y: Y coordinate :param z: Z coordinate :param velocity: the velocity (meters/second) :return:
def go_to(self, x, y, z=DEFAULT, velocity=DEFAULT): """ Go to a position :param x: X coordinate :param y: Y coordinate :param z: Z coordinate :param velocity: the velocity (meters/second) :return: """ 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
Request an update of all the parameters in the TOC
def request_update_of_all_params(self): """Request an update of all the parameters in the TOC""" 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)
Check if all parameters from the TOC has at least been fetched once
def _check_if_all_updated(self): """Check if all parameters from the TOC has at least been fetched once""" 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
Callback with data for an updated parameter
def _param_updated(self, pk): """Callback with data for an updated parameter""" 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) # Save the value for synchronous access 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) # Once all the parameters are updated call the # callback for "everything updated" (after all the param # updated callbacks) 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)
Remove the supplied callback for a group or a group.name
def remove_update_callback(self, group, name=None, cb=None): """Remove the supplied callback for a group or a group.name""" 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)
Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie.
def add_update_callback(self, group=None, name=None, cb=None): """ Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie. """ 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)
Initiate a refresh of the parameter TOC.
def refresh_toc(self, refresh_done_callback, toc_cache): """ Initiate a refresh of the parameter TOC. """ 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()
Disconnected callback from Crazyflie API
def _disconnected(self, uri): """Disconnected callback from Crazyflie API""" self.param_updater.close() self.is_updated = False # Clear all values from the previous Crazyflie self.toc = Toc() self.values = {}
Request an update of the value for the supplied parameter.
def request_param_update(self, complete_name): """ Request an update of the value for the supplied parameter. """ self.param_updater.request_param_update( self.toc.get_element_id(complete_name))
Set the value for the supplied parameter.
def set_value(self, complete_name, value): """ Set the value for the supplied parameter. """ 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)
Callback for newly arrived packets
def _new_packet_cb(self, pk): """Callback for newly arrived packets""" 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
Place a param update request on the queue
def request_param_update(self, var_id): """Place a param update request on the queue""" 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)
Add a new TocElement to the TOC container.
def add_element(self, element): """Add a new TocElement to the TOC container.""" try: self.toc[element.group][element.name] = element except KeyError: self.toc[element.group] = {} self.toc[element.group][element.name] = element
Get the TocElement element id-number of the element with the supplied name.
def get_element_id(self, complete_name): """Get the TocElement element id-number of the element with the supplied 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 a TocElement element identified by index number from the container.
def get_element_by_id(self, ident): """Get a TocElement element identified by index number from the container.""" 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
Initiate fetching of the TOC.
def start(self): """Initiate fetching of the TOC.""" 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) # Register callback in this class for the port self.cf.add_port_callback(self.port, self._new_packet_cb) # Request the TOC CRC 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,))
Callback for when the TOC fetching is finished
def _toc_fetch_finished(self): """Callback for when the TOC fetching is finished""" self.cf.remove_port_callback(self.port, self._new_packet_cb) logger.debug('[%d]: Done!', self.port) self.finished_callback()
Handle a newly arrived packet
def _new_packet_cb(self, packet): """Handle a newly arrived 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): # Always add new element, but only request new if it's not the # last one. 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: # No more variables in TOC self._toc_cache.insert(self._crc, self.toc.toc) self._toc_fetch_finished()
Request information about a specific item in the TOC
def _request_toc_element(self, index): """Request information about a specific item in the TOC""" 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))
Start the connection setup by refreshing the TOCs
def _start_connection_setup(self): """Start the connection setup by refreshing the TOCs""" logger.info('We are connected[%s], request connection setup', self.link_uri) self.platform.fetch_platform_informations(self._platform_info_fetched)
Called when the param TOC has been fully updated
def _param_toc_updated_cb(self): """Called when the param TOC has been fully updated""" logger.info('Param TOC finished updating') self.connected_ts = datetime.datetime.now() self.connected.call(self.link_uri) # Trigger the update for all the parameters self.param.request_update_of_all_params()
Called when the memories have been identified
def _mems_updated_cb(self): """Called when the memories have been identified""" logger.info('Memories finished updating') self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache)
Called from the link driver when there's an error
def _link_error_cb(self, errmsg): """Called from the link driver when there's an error""" 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 when first packet arrives from Crazyflie. This is used to determine if we are connected to something that is answering.
def _check_for_initial_packet_cb(self, data): """ Called when first packet arrives from Crazyflie. This is used to determine if we are connected to something that is answering. """ self.state = State.CONNECTED self.link_established.call(self.link_uri) self.packet_received.remove_callback(self._check_for_initial_packet_cb)
Open the communication link to a copter at the given URI and setup the connection (download log/parameter TOC).
def open_link(self, link_uri): """ Open the communication link to a copter at the given URI and setup the connection (download log/parameter TOC). """ self.connection_requested.call(link_uri) self.state = State.INITIALIZED self.link_uri = link_uri try: self.link = cflib.crtp.get_link_driver( link_uri, self._link_quality_cb, self._link_error_cb) if not self.link: message = 'No driver found or malformed URI: {}' \ .format(link_uri) logger.warning(message) self.connection_failed.call(link_uri, message) else: # Add a callback so we can check that any data is coming # back from the copter self.packet_received.add_callback( self._check_for_initial_packet_cb) self._start_connection_setup() except Exception as ex: # pylint: disable=W0703 # We want to catch every possible exception here and show # it in the user interface import traceback logger.error("Couldn't load link driver: %s\n\n%s", ex, traceback.format_exc()) exception_text = "Couldn't load link driver: %s\n\n%s" % ( ex, traceback.format_exc()) if self.link: self.link.close() self.link = None self.connection_failed.call(link_uri, exception_text)
Close the communication link.
def close_link(self): """Close the communication link.""" 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)
Resend packets that we have not gotten answers to
def _no_answer_do_retry(self, pk, pattern): """Resend packets that we have not gotten answers to""" logger.info('Resending for pattern %s', pattern) # Set the timer to None before trying to send again self.send_packet(pk, expected_reply=pattern, resend=True)
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.
def _check_for_answers(self, pk): """ 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. """ 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]
Send a packet through the link interface. pk -- Packet to send expect_answer -- True if a packet from the Crazyflie is expected to be sent back, otherwise false
def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2): """ Send a packet through the link interface. pk -- Packet to send expect_answer -- True if a packet from the Crazyflie is expected to be sent back, otherwise false """ 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: # Check if we have gotten an answer, if not try again 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()
Add a callback for data that comes on a specific port
def add_port_callback(self, port, cb): """Add a callback for data that comes on a specific port""" logger.debug('Adding callback on port [%d] to [%s]', port, cb) self.add_header_callback(cb, port, 0, 0xff, 0x0)
Remove a callback for data that comes on a specific port
def remove_port_callback(self, port, cb): """Remove a callback for data that comes on a specific port""" 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)
Add a callback for a specific port/header callback with the possibility to add a mask for channel and port for multiple hits for same callback.
def add_header_callback(self, cb, port, channel, port_mask=0xFF, channel_mask=0xFF): """ Add a callback for a specific port/header callback with the possibility to add a mask for channel and port for multiple hits for same callback. """ self.cb.append(_CallbackContainer(port, port_mask, channel, channel_mask, cb))
Add a new variable to the configuration. name - Complete name of the variable in the form group.name fetch_as - String representation of the type the variable should be fetched as (i.e uint8_t, float, FP16, etc) If no fetch_as type is supplied, then the stored as type will be used (i.e the type of the fetched variable is the same as it's stored in the Crazyflie).
def add_variable(self, name, fetch_as=None): """Add a new variable to the configuration. name - Complete name of the variable in the form group.name fetch_as - String representation of the type the variable should be fetched as (i.e uint8_t, float, FP16, etc) If no fetch_as type is supplied, then the stored as type will be used (i.e the type of the fetched variable is the same as it's stored in the Crazyflie).""" if fetch_as: self.variables.append(LogVariable(name, fetch_as)) else: # We cannot determine the default type until we have connected. So # save the name and we will add these once we are connected. self.default_fetch_as.append(name)
Add a raw memory position to log. name - Arbitrary name of the variable fetch_as - String representation of the type of the data the memory should be fetch as (i.e uint8_t, float, FP16) stored_as - String representation of the type the data is stored as in the Crazyflie address - The address of the data
def add_memory(self, name, fetch_as, stored_as, address): """Add a raw memory position to log. name - Arbitrary name of the variable fetch_as - String representation of the type of the data the memory should be fetch as (i.e uint8_t, float, FP16) stored_as - String representation of the type the data is stored as in the Crazyflie address - The address of the data """ self.variables.append(LogVariable(name, fetch_as, LogVariable.MEM_TYPE, stored_as, address))
Save the log configuration in the Crazyflie
def create(self): """Save the log configuration in the Crazyflie""" 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): # Memory location 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: # Item in TOC 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))
Start the logging for this entry
def start(self): """Start the logging for this entry""" 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))
Stop the logging for this entry
def stop(self): """Stop the logging for this entry""" 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))
Delete this entry in the Crazyflie
def delete(self): """Delete this entry in the Crazyflie""" 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))
Unpack received logging data so it represent real values according to the configuration in the entry
def unpack_log_data(self, log_data, timestamp): """Unpack received logging data so it represent real values according to the configuration in the entry""" 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)
Return variable type id given the C-storage name
def get_id_from_cstring(name): """Return variable type id given the C-storage 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)
Add a log configuration to the logging framework. When doing this the contents of the log configuration will be validated and listeners for new log configurations will be notified. When validating the configuration the variables are checked against the TOC to see that they actually exist. If they don't then the configuration cannot be used. Since a valid TOC is required, a Crazyflie has to be connected when calling this method, otherwise it will fail.
def add_config(self, logconf): """Add a log configuration to the logging framework. When doing this the contents of the log configuration will be validated and listeners for new log configurations will be notified. When validating the configuration the variables are checked against the TOC to see that they actually exist. If they don't then the configuration cannot be used. Since a valid TOC is required, a Crazyflie has to be connected when calling this method, otherwise it will fail.""" if not self.cf.link: logger.error('Cannot add configs without being connected to a ' 'Crazyflie!') return # If the log configuration contains variables that we added without # type (i.e we want the stored as type for fetching as well) then # resolve this now and add them to the block again. 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)) # Now that we know what type this variable has, add it to the log # config again with the correct type logconf.add_variable(name, var.ctype) # Now check that all the added variables are in the TOC and that # the total size constraint of a data packet with logging data is # not size = 0 for var in logconf.variables: size += LogTocElement.get_size_from_id(var.fetch_as) # Check that we are able to find the variable in the TOC so # we can return error already now and not when the config is sent 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')
Start refreshing the table of loggale variables
def refresh_toc(self, refresh_done_callback, toc_cache): """Start refreshing the table of loggale variables""" 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,))
Callback for newly arrived packets with TOC information
def _new_packet_cb(self, packet): """Callback for newly arrived packets with TOC information""" chan = packet.channel cmd = packet.data[0] payload = packet.data[1:] if (chan == CHAN_SETTINGS): id = payload[0] error_status = payload[1] block = self._find_block(id) if cmd == CMD_CREATE_BLOCK or cmd == CMD_CREATE_BLOCK_V2: if (block is not None): if error_status == 0 or error_status == errno.EEXIST: if not block.added: logger.debug('Have successfully added id=%d', id) pk = CRTPPacket() pk.set_header(5, CHAN_SETTINGS) pk.data = (CMD_START_LOGGING, id, block.period) self.cf.send_packet(pk, expected_reply=( CMD_START_LOGGING, id)) block.added = True else: msg = self._err_codes[error_status] logger.warning('Error %d when adding id=%d (%s)', error_status, id, msg) block.err_no = error_status block.added_cb.call(False) block.error_cb.call(block, msg) else: logger.warning('No LogEntry to assign block to !!!') if (cmd == CMD_START_LOGGING): if (error_status == 0x00): logger.info('Have successfully started logging for id=%d', id) if block: block.started = True else: msg = self._err_codes[error_status] logger.warning('Error %d when starting id=%d (%s)', error_status, id, msg) if block: block.err_no = error_status block.started_cb.call(self, False) # This is a temporary fix, we are adding a new issue # for this. For some reason we get an error back after # the block has been started and added. This will show # an error in the UI, but everything is still working. # block.error_cb.call(block, msg) if (cmd == CMD_STOP_LOGGING): if (error_status == 0x00): logger.info('Have successfully stopped logging for id=%d', id) if block: block.started = False if (cmd == CMD_DELETE_BLOCK): # Accept deletion of a block that isn't added. This could # happen due to timing (i.e add/start/delete in fast sequence) if error_status == 0x00 or error_status == errno.ENOENT: logger.info('Have successfully deleted id=%d', id) if block: block.started = False block.added = False if (cmd == CMD_RESET_LOGGING): # Guard against multiple responses due to re-sending if not self.toc: logger.debug('Logging reset, continue with TOC download') self.log_blocks = [] self.toc = Toc() toc_fetcher = TocFetcher(self.cf, LogTocElement, CRTPPort.LOGGING, self.toc, self._refresh_callback, self._toc_cache) toc_fetcher.start() if (chan == CHAN_LOGDATA): chan = packet.channel id = packet.data[0] block = self._find_block(id) timestamps = struct.unpack('<BBB', packet.data[1:4]) timestamp = ( timestamps[0] | timestamps[1] << 8 | timestamps[2] << 16) logdata = packet.data[4:] if (block is not None): block.unpack_log_data(logdata, timestamp) else: logger.warning('Error no LogEntry to handle id=%d', id)
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) mems = self._cf.mem.get_mems(MemoryElement.TYPE_I2C) print('Found {} EEPOM(s)'.format(len(mems))) if len(mems) > 0: print('Writing default configuration to' ' memory {}'.format(mems[0].id)) elems = mems[0].elements elems['version'] = 1 elems['pitch_trim'] = 0.0 elems['roll_trim'] = 0.0 elems['radio_channel'] = 80 elems['radio_speed'] = 0 elems['radio_address'] = 0xE7E7E7E7E7 mems[0].write_data(self._data_written)
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) # The definition of the logconfig can be made before connecting self._lg_stab = LogConfig(name='Stabilizer', period_in_ms=10) self._lg_stab.add_variable('stabilizer.roll', 'float') self._lg_stab.add_variable('stabilizer.pitch', 'float') self._lg_stab.add_variable('stabilizer.yaw', 'float') # Adding the configuration cannot be done until a Crazyflie is # connected, since we need to check that the variables we # would like to log are in the TOC. try: self._cf.log.add_config(self._lg_stab) # This callback will receive the data self._lg_stab.data_received_cb.add_callback(self._stab_log_data) # This callback will be called on errors self._lg_stab.error_cb.add_callback(self._stab_log_error) # Start the logging self._lg_stab.start() except KeyError as e: print('Could not start log configuration,' '{} not found in TOC'.format(str(e))) except AttributeError: print('Could not add Stabilizer log config, bad configuration.') # Start a timer to disconnect in 10s t = Timer(5, self._cf.close_link) t.start()
Initialize all the drivers.
def init_drivers(enable_debug_driver=False): """Initialize all the drivers.""" for driver in DRIVERS: try: if driver != DebugDriver or enable_debug_driver: CLASSES.append(driver) except Exception: # pylint: disable=W0703 continue
Scan all the interfaces for available Crazyflies
def scan_interfaces(address=None): """ Scan all the interfaces for available Crazyflies """ 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
Get the status of all the interfaces
def get_interfaces_status(): """Get the status of all the interfaces""" status = {} for driverClass in CLASSES: try: instance = driverClass() status[instance.get_name()] = instance.get_status() except Exception: raise return status
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.
def get_link_driver(uri, link_quality_callback=None, link_error_callback=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.""" for driverClass in CLASSES: try: instance = driverClass() instance.connect(uri, link_quality_callback, link_error_callback) return instance except WrongUriType: continue return None
Callback for data received from the copter.
def _incoming(self, packet): """ Callback for data received from the copter. """ if len(packet.data) < 1: logger.warning('Localization packet received with incorrect' + 'length (length is {})'.format(len(packet.data))) return pk_type = struct.unpack('<B', packet.data[:1])[0] data = packet.data[1:] # Decoding the known packet types # TODO: more generic decoding scheme? decoded_data = None if pk_type == self.RANGE_STREAM_REPORT: if len(data) % 5 != 0: logger.error('Wrong range stream report data lenght') return decoded_data = {} raw_data = data for i in range(int(len(data) / 5)): anchor_id, distance = struct.unpack('<Bf', raw_data[:5]) decoded_data[anchor_id] = distance raw_data = raw_data[5:] pk = LocalizationPacket(pk_type, data, decoded_data) self.receivedLocationPacket.call(pk)
Send the current Crazyflie X, Y, Z position. This is going to be forwarded to the Crazyflie's position estimator.
def send_extpos(self, pos): """ Send the current Crazyflie X, Y, Z position. This is going to be forwarded to the Crazyflie's position estimator. """ pk = CRTPPacket() pk.port = CRTPPort.LOCALIZATION pk.channel = self.POSITION_CH pk.data = struct.pack('<fff', pos[0], pos[1], pos[2]) self._cf.send_packet(pk)
Send ultra-wide-band LPP packet to dest_id
def send_short_lpp_packet(self, dest_id, data): """ Send ultra-wide-band LPP packet to dest_id """ 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 a new control setpoint for roll/pitch/yaw/thrust to the copter The arguments roll/pitch/yaw/trust is the new setpoints that should be sent to the copter
def send_setpoint(self, roll, pitch, yaw, thrust): """ Send a new control setpoint for roll/pitch/yaw/thrust to the copter The arguments roll/pitch/yaw/trust is the new setpoints that should be sent to the copter """ if thrust > 0xFFFF or thrust < 0: raise ValueError('Thrust must be between 0 and 0xFFFF') if self._x_mode: roll, pitch = 0.707 * (roll - pitch), 0.707 * (roll + pitch) pk = CRTPPacket() pk.port = CRTPPort.COMMANDER pk.data = struct.pack('<fffH', roll, -pitch, yaw, thrust) self._cf.send_packet(pk)
Send STOP setpoing, stopping the motors and (potentially) falling.
def send_stop_setpoint(self): """ Send STOP setpoing, stopping the motors and (potentially) falling. """ pk = CRTPPacket() pk.port = CRTPPort.COMMANDER_GENERIC pk.data = struct.pack('<B', TYPE_STOP) self._cf.send_packet(pk)
Send Velocity in the world frame of reference setpoint. vx, vy, vz are in m/s yawrate is in degrees/s
def send_velocity_world_setpoint(self, vx, vy, vz, yawrate): """ Send Velocity in the world frame of reference setpoint. vx, vy, vz are in m/s yawrate is in degrees/s """ pk = CRTPPacket() pk.port = CRTPPort.COMMANDER_GENERIC pk.data = struct.pack('<Bffff', TYPE_VELOCITY_WORLD, vx, vy, vz, yawrate) self._cf.send_packet(pk)
Control mode where the height is send as an absolute setpoint (intended to be the distance to the surface under the Crazflie). Roll, pitch, yawrate are defined as degrees, degrees, degrees/s
def send_zdistance_setpoint(self, roll, pitch, yawrate, zdistance): """ Control mode where the height is send as an absolute setpoint (intended to be the distance to the surface under the Crazflie). Roll, pitch, yawrate are defined as degrees, degrees, degrees/s """ pk = CRTPPacket() pk.port = CRTPPort.COMMANDER_GENERIC pk.data = struct.pack('<Bffff', TYPE_ZDISTANCE, roll, pitch, yawrate, zdistance) self._cf.send_packet(pk)
Control mode where the height is send as an absolute setpoint (intended to be the distance to the surface under the Crazflie). vx and vy are in m/s yawrate is in degrees/s
def send_hover_setpoint(self, vx, vy, yawrate, zdistance): """ Control mode where the height is send as an absolute setpoint (intended to be the distance to the surface under the Crazflie). vx and vy are in m/s yawrate is in degrees/s """ pk = CRTPPacket() pk.port = CRTPPort.COMMANDER_GENERIC pk.data = struct.pack('<Bffff', TYPE_HOVER, vx, vy, yawrate, zdistance) 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. x and y are in m yaw is in degrees
def send_position_setpoint(self, x, y, z, yaw): """ Control mode where the position is sent as absolute x,y,z coordinate in meter and the yaw is the absolute orientation. x and y are in m yaw is in degrees """ pk = CRTPPacket() pk.port = CRTPPort.COMMANDER_GENERIC pk.data = struct.pack('<Bffff', TYPE_POSITION, x, y, z, yaw) self._cf.send_packet(pk)
Get string representation of memory type
def type_to_string(t): """Get string representation of memory type""" 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'