signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def update(self, update_finished_cb):
if not self._update_finished_cb:<EOL><INDENT>self._update_finished_cb = update_finished_cb<EOL>self.valid = False<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self.mem_handler.read(self, <NUM_LIT:0>, <NUM_LIT:16>)<EOL><DEDENT>
Request an update of the memory content
f1070:c2:m3
def new_data(self, mem, addr, data):
if mem.id == self.id:<EOL><INDENT>if addr == <NUM_LIT:0>:<EOL><INDENT>done = False<EOL>if data[<NUM_LIT:0>:<NUM_LIT:4>] == EEPROM_TOKEN:<EOL><INDENT>logger.debug('<STR_LIT>'.format(data))<EOL>[self.elements['<STR_LIT:version>'],<EOL>self.elements['<STR_LIT>'],<EOL>self.elements['<STR_LIT>'],<EOL>self.elements['<STR_LIT>'],<EOL>self.elements['<STR_LIT>']] = struct.unpack('<STR_LIT>',<EOL>data[<NUM_LIT:4>:<NUM_LIT:15>])<EOL>if self.elements['<STR_LIT:version>'] == <NUM_LIT:0>:<EOL><INDENT>done = True<EOL><DEDENT>elif self.elements['<STR_LIT:version>'] == <NUM_LIT:1>:<EOL><INDENT>self.datav0 = data<EOL>self.mem_handler.read(self, <NUM_LIT:16>, <NUM_LIT:5>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.valid = False<EOL>if self._update_finished_cb:<EOL><INDENT>self._update_finished_cb(self)<EOL>self._update_finished_cb = None<EOL><DEDENT><DEDENT><DEDENT>if addr == <NUM_LIT:16>:<EOL><INDENT>[radio_address_upper, radio_address_lower] = struct.unpack(<EOL>'<STR_LIT>', self.datav0[<NUM_LIT:15>:<NUM_LIT:16>] + data[<NUM_LIT:0>:<NUM_LIT:4>])<EOL>self.elements['<STR_LIT>'] = int(<EOL>radio_address_upper) << <NUM_LIT:32> | radio_address_lower<EOL>logger.debug(self.elements)<EOL>data = self.datav0 + data<EOL>done = True<EOL><DEDENT>if done:<EOL><INDENT>if self._checksum256(data[:len(data) - <NUM_LIT:1>]) ==data[len(data) - <NUM_LIT:1>]:<EOL><INDENT>self.valid = True<EOL><DEDENT>if self._update_finished_cb:<EOL><INDENT>self._update_finished_cb(self)<EOL>self._update_finished_cb = None<EOL><DEDENT><DEDENT><DEDENT>
Callback for when new memory data has been fetched
f1070:c3:m1
def update(self, update_finished_cb):
if not self._update_finished_cb:<EOL><INDENT>self._update_finished_cb = update_finished_cb<EOL>self.valid = False<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self.mem_handler.read(self, <NUM_LIT:0>, <NUM_LIT:16>)<EOL><DEDENT>
Request an update of the memory content
f1070:c3:m4
def __init__(self, id, type, size, addr, mem_handler):
super(OWElement, self).__init__(id=id, type=type, size=size,<EOL>mem_handler=mem_handler)<EOL>self.addr = addr<EOL>self.valid = False<EOL>self.vid = None<EOL>self.pid = None<EOL>self.name = None<EOL>self.pins = None<EOL>self.elements = {}<EOL>self._update_finished_cb = None<EOL>self._write_finished_cb = None<EOL>self._rev_element_mapping = {}<EOL>for key in list(OWElement.element_mapping.keys()):<EOL><INDENT>self._rev_element_mapping[OWElement.element_mapping[key]] = key<EOL><DEDENT>
Initialize the memory with good defaults
f1070:c4:m0
def new_data(self, mem, addr, data):
if mem.id == self.id:<EOL><INDENT>if addr == <NUM_LIT:0>:<EOL><INDENT>if self._parse_and_check_header(data[<NUM_LIT:0>:<NUM_LIT:8>]):<EOL><INDENT>if self._parse_and_check_elements(data[<NUM_LIT:9>:<NUM_LIT:11>]):<EOL><INDENT>self.valid = True<EOL>self._update_finished_cb(self)<EOL>self._update_finished_cb = None<EOL><DEDENT>else:<EOL><INDENT>(elem_ver, elem_len) = struct.unpack('<STR_LIT>', data[<NUM_LIT:8>:<NUM_LIT:10>])<EOL>self.mem_handler.read(self, <NUM_LIT:8>, elem_len + <NUM_LIT:3>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self._update_finished_cb:<EOL><INDENT>self._update_finished_cb(self)<EOL>self._update_finished_cb = None<EOL><DEDENT><DEDENT><DEDENT>elif addr == <NUM_LIT>:<EOL><INDENT>if self._parse_and_check_elements(data):<EOL><INDENT>self.valid = True<EOL><DEDENT>if self._update_finished_cb:<EOL><INDENT>self._update_finished_cb(self)<EOL>self._update_finished_cb = None<EOL><DEDENT><DEDENT><DEDENT>
Callback for when new memory data has been fetched
f1070:c4:m1
def _parse_and_check_elements(self, data):
crc = data[-<NUM_LIT:1>]<EOL>test_crc = crc32(data[:-<NUM_LIT:1>]) & <NUM_LIT><EOL>elem_data = data[<NUM_LIT:2>:-<NUM_LIT:1>]<EOL>if test_crc == crc:<EOL><INDENT>while len(elem_data) > <NUM_LIT:0>:<EOL><INDENT>(eid, elen) = struct.unpack('<STR_LIT>', elem_data[:<NUM_LIT:2>])<EOL>self.elements[self.element_mapping[eid]] =elem_data[<NUM_LIT:2>:<NUM_LIT:2> + elen].decode('<STR_LIT>')<EOL>elem_data = elem_data[<NUM_LIT:2> + elen:]<EOL><DEDENT>return True<EOL><DEDENT>return False<EOL>
Parse and check the CRC and length of the elements part of the memory
f1070:c4:m2
def update(self, update_finished_cb):
if not self._update_finished_cb:<EOL><INDENT>self._update_finished_cb = update_finished_cb<EOL>self.valid = False<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self.mem_handler.read(self, <NUM_LIT:0>, <NUM_LIT:11>)<EOL><DEDENT>
Request an update of the memory content
f1070:c4:m6
def _parse_and_check_header(self, data):
(start, self.pins, self.vid, self.pid, crc) = struct.unpack('<STR_LIT>',<EOL>data)<EOL>test_crc = crc32(data[:-<NUM_LIT:1>]) & <NUM_LIT><EOL>if start == <NUM_LIT> and crc == test_crc:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
Parse and check the CRC of the header part of the memory
f1070:c4:m7
def __str__(self):
return ('<STR_LIT>'.format(<EOL>self.addr, self.vid, self.pid, self.elements))<EOL>
Generate debug string for memory
f1070:c4:m8
def new_data(self, mem, addr, data):
done = False<EOL>if mem.id == self.id:<EOL><INDENT>if addr == LocoMemory.MEM_LOCO_INFO:<EOL><INDENT>self.nr_of_anchors = data[<NUM_LIT:0>]<EOL>if self.nr_of_anchors == <NUM_LIT:0>:<EOL><INDENT>done = True<EOL><DEDENT>else:<EOL><INDENT>self.anchor_data =[AnchorData() for _ in range(self.nr_of_anchors)]<EOL>self._request_page(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>page = int((addr - LocoMemory.MEM_LOCO_ANCHOR_BASE) /<EOL>LocoMemory.MEM_LOCO_ANCHOR_PAGE_SIZE)<EOL>self.anchor_data[page].set_from_mem_data(data)<EOL>next_page = page + <NUM_LIT:1><EOL>if next_page < self.nr_of_anchors:<EOL><INDENT>self._request_page(next_page)<EOL><DEDENT>else:<EOL><INDENT>done = True<EOL><DEDENT><DEDENT><DEDENT>if done:<EOL><INDENT>self.valid = True<EOL>if self._update_finished_cb:<EOL><INDENT>self._update_finished_cb(self)<EOL>self._update_finished_cb = None<EOL><DEDENT><DEDENT>
Callback for when new memory data has been fetched
f1070:c6:m1
def update(self, update_finished_cb):
if not self._update_finished_cb:<EOL><INDENT>self._update_finished_cb = update_finished_cb<EOL>self.anchor_data = []<EOL>self.nr_of_anchors = <NUM_LIT:0><EOL>self.valid = False<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self.mem_handler.read(self, LocoMemory.MEM_LOCO_INFO,<EOL>LocoMemory.MEM_LOCO_INFO_LEN)<EOL><DEDENT>
Request an update of the memory content
f1070:c6:m2
def new_data(self, mem, addr, data):
if mem.id == self.id:<EOL><INDENT>if addr == LocoMemory2.ADR_ID_LIST:<EOL><INDENT>self._handle_id_list_data(data)<EOL><DEDENT>elif addr == LocoMemory2.ADR_ACTIVE_ID_LIST:<EOL><INDENT>self._handle_active_id_list_data(data)<EOL><DEDENT>else:<EOL><INDENT>id = int((addr - LocoMemory2.ADR_ANCHOR_BASE) /<EOL>LocoMemory2.ANCHOR_PAGE_SIZE)<EOL>self._handle_anchor_data(id, data)<EOL><DEDENT><DEDENT>
Callback for when new memory data has been fetched
f1070:c8:m1
def update_id_list(self, update_ids_finished_cb):
if not self._update_ids_finished_cb:<EOL><INDENT>self._update_ids_finished_cb = update_ids_finished_cb<EOL>self.anchor_ids = []<EOL>self.active_anchor_ids = []<EOL>self.anchor_data = {}<EOL>self.nr_of_anchors = <NUM_LIT:0><EOL>self.ids_valid = False<EOL>self.data_valid = False<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self.mem_handler.read(self, LocoMemory2.ADR_ID_LIST,<EOL>LocoMemory2.ID_LIST_LEN)<EOL><DEDENT>
Request an update of the id list
f1070:c8:m2
def update_active_id_list(self, update_active_ids_finished_cb):
if not self._update_active_ids_finished_cb:<EOL><INDENT>self._update_active_ids_finished_cb = update_active_ids_finished_cb<EOL>self.active_anchor_ids = []<EOL>self.active_ids_valid = False<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self.mem_handler.read(self, LocoMemory2.ADR_ACTIVE_ID_LIST,<EOL>LocoMemory2.ID_LIST_LEN)<EOL><DEDENT>
Request an update of the active id list
f1070:c8:m3
def update_data(self, update_data_finished_cb):
if not self._update_data_finished_cb and self.nr_of_anchors > <NUM_LIT:0>:<EOL><INDENT>self._update_data_finished_cb = update_data_finished_cb<EOL>self.anchor_data = {}<EOL>self.data_valid = False<EOL>self._nr_of_anchors_to_fetch = self.nr_of_anchors<EOL>logger.debug('<STR_LIT>'.format(self.id))<EOL>self._currently_fetching_index = <NUM_LIT:0><EOL>self._request_page(self.anchor_ids[self._currently_fetching_index])<EOL><DEDENT>
Request an update of the anchor data
f1070:c8:m4
def __init__(self, id, type, size, mem_handler):
super(TrajectoryMemory, self).__init__(id=id, type=type, size=size,<EOL>mem_handler=mem_handler)<EOL>self._write_finished_cb = None<EOL>self.poly4Ds = []<EOL>
Initialize trajectory memory
f1070:c10:m0
def write_data(self, write_finished_cb):
self._write_finished_cb = write_finished_cb<EOL>data = bytearray()<EOL>for poly4D in self.poly4Ds:<EOL><INDENT>data += struct.pack('<STR_LIT>', *poly4D.x.values)<EOL>data += struct.pack('<STR_LIT>', *poly4D.y.values)<EOL>data += struct.pack('<STR_LIT>', *poly4D.z.values)<EOL>data += struct.pack('<STR_LIT>', *poly4D.yaw.values)<EOL>data += struct.pack('<STR_LIT>', poly4D.duration)<EOL><DEDENT>self.mem_handler.write(self, <NUM_LIT>, data, flush_queue=True)<EOL>
Write trajectory data to the Crazyflie
f1070:c10:m1
def __init__(self, mem, addr, length, cf):
self.mem = mem<EOL>self.addr = addr<EOL>self._bytes_left = length<EOL>self.data = bytearray()<EOL>self.cf = cf<EOL>self._current_addr = addr<EOL>
Initialize the object with good defaults
f1070:c11:m0
def start(self):
self._request_new_chunk()<EOL>
Start the fetching of the data
f1070:c11:m1
def _request_new_chunk(self):
<EOL>new_len = self._bytes_left<EOL>if new_len > _ReadRequest.MAX_DATA_LENGTH:<EOL><INDENT>new_len = _ReadRequest.MAX_DATA_LENGTH<EOL><DEDENT>logger.debug('<STR_LIT>'.format(<EOL>new_len, self._current_addr))<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.MEM, CHAN_READ)<EOL>pk.data = struct.pack('<STR_LIT>', self.mem.id, self._current_addr, new_len)<EOL>reply = struct.unpack('<STR_LIT>', pk.data[:-<NUM_LIT:1>])<EOL>self.cf.send_packet(pk, expected_reply=reply, timeout=<NUM_LIT:1>)<EOL>
Called to request a new chunk of data to be read from the Crazyflie
f1070:c11:m3
def add_data(self, addr, data):
data_len = len(data)<EOL>if not addr == self._current_addr:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>self.data += data<EOL>self._bytes_left -= data_len<EOL>self._current_addr += data_len<EOL>if self._bytes_left > <NUM_LIT:0>:<EOL><INDENT>self._request_new_chunk()<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>
Callback when data is received from the Crazyflie
f1070:c11:m4
def __init__(self, mem, addr, data, cf):
self.mem = mem<EOL>self.addr = addr<EOL>self._bytes_left = len(data)<EOL>self._data = data<EOL>self.data = bytearray()<EOL>self.cf = cf<EOL>self._current_addr = addr<EOL>self._sent_packet = None<EOL>self._sent_reply = None<EOL>self._addr_add = <NUM_LIT:0><EOL>
Initialize the object with good defaults
f1070:c12:m0
def start(self):
self._write_new_chunk()<EOL>
Start the fetching of the data
f1070:c12:m1
def _write_new_chunk(self):
<EOL>new_len = len(self._data)<EOL>if new_len > _WriteRequest.MAX_DATA_LENGTH:<EOL><INDENT>new_len = _WriteRequest.MAX_DATA_LENGTH<EOL><DEDENT>logger.debug('<STR_LIT>'.format(<EOL>new_len, self._current_addr))<EOL>data = self._data[:new_len]<EOL>self._data = self._data[new_len:]<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.MEM, CHAN_WRITE)<EOL>pk.data = struct.pack('<STR_LIT>', self.mem.id, self._current_addr)<EOL>reply = struct.unpack('<STR_LIT>', pk.data)<EOL>self._sent_reply = reply<EOL>pk.data += struct.pack('<STR_LIT:B>' * len(data), *data)<EOL>self._sent_packet = pk<EOL>self.cf.send_packet(pk, expected_reply=reply, timeout=<NUM_LIT:1>)<EOL>self._addr_add = len(data)<EOL>
Called to request a new chunk of data to be read from the Crazyflie
f1070:c12:m3
def write_done(self, addr):
if not addr == self._current_addr:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>if len(self._data) > <NUM_LIT:0>:<EOL><INDENT>self._current_addr += self._addr_add<EOL>self._write_new_chunk()<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>')<EOL>return True<EOL><DEDENT>
Callback when data is received from the Crazyflie
f1070:c12:m4
def __init__(self, crazyflie=None):
<EOL>self.mem_added_cb = Caller()<EOL>self.mem_read_cb = Caller()<EOL>self.mem_write_cb = Caller()<EOL>self.cf = crazyflie<EOL>self.cf.add_port_callback(CRTPPort.MEM, self._new_packet_cb)<EOL>self.cf.disconnected.add_callback(self._disconnected)<EOL>self._write_requests_lock = Lock()<EOL>self._clear_state()<EOL>
Instantiate class and connect callbacks
f1070:c13:m0
def _mem_update_done(self, mem):
if mem.id in self._ow_mems_left_to_update:<EOL><INDENT>self._ow_mems_left_to_update.remove(mem.id)<EOL><DEDENT>logger.debug(mem)<EOL>if len(self._ow_mems_left_to_update) == <NUM_LIT:0>:<EOL><INDENT>if self._refresh_callback:<EOL><INDENT>self._refresh_callback()<EOL>self._refresh_callback = None<EOL><DEDENT><DEDENT>
Callback from each individual memory (only 1-wire) when reading of header/elements are done
f1070:c13:m2
def get_mem(self, id):
for m in self.mems:<EOL><INDENT>if m.id == id:<EOL><INDENT>return m<EOL><DEDENT><DEDENT>return None<EOL>
Fetch the memory with the supplied id
f1070:c13:m3
def get_mems(self, type):
ret = ()<EOL>for m in self.mems:<EOL><INDENT>if m.type == type:<EOL><INDENT>ret += (m,)<EOL><DEDENT><DEDENT>return ret<EOL>
Fetch all the memories of the supplied type
f1070:c13:m4
def ow_search(self, vid=<NUM_LIT>, pid=None, name=None):
for m in self.get_mems(MemoryElement.TYPE_1W):<EOL><INDENT>if pid and m.pid == pid or name and m.name == name:<EOL><INDENT>return m<EOL><DEDENT><DEDENT>return None<EOL>
Search for specific memory id/name and return it
f1070:c13:m5
def write(self, memory, addr, data, flush_queue=False):
wreq = _WriteRequest(memory, addr, data, self.cf)<EOL>if memory.id not in self._write_requests:<EOL><INDENT>self._write_requests[memory.id] = []<EOL><DEDENT>self._write_requests_lock.acquire()<EOL>if flush_queue:<EOL><INDENT>self._write_requests[memory.id] = self._write_requests[<EOL>memory.id][:<NUM_LIT:1>]<EOL><DEDENT>self._write_requests[memory.id].insert(len(self._write_requests), wreq)<EOL>if len(self._write_requests[memory.id]) == <NUM_LIT:1>:<EOL><INDENT>wreq.start()<EOL><DEDENT>self._write_requests_lock.release()<EOL>return True<EOL>
Write the specified data to the given memory at the given address
f1070:c13:m6
def read(self, memory, addr, length):
if memory.id in self._read_requests:<EOL><INDENT>logger.warning('<STR_LIT>'<EOL>'<STR_LIT>'.format(memory.id))<EOL>return False<EOL><DEDENT>rreq = _ReadRequest(memory, addr, length, self.cf)<EOL>self._read_requests[memory.id] = rreq<EOL>rreq.start()<EOL>return True<EOL>
Read the specified amount of bytes from the given memory at the given address
f1070:c13:m7
def refresh(self, refresh_done_callback):
self._refresh_callback = refresh_done_callback<EOL>self._fetch_id = <NUM_LIT:0><EOL>for m in self.mems:<EOL><INDENT>try:<EOL><INDENT>self.mem_read_cb.remove_callback(m.new_data)<EOL>m.disconnect()<EOL><DEDENT>except Exception as e:<EOL><INDENT>logger.info(<EOL>'<STR_LIT>'.format(e))<EOL><DEDENT><DEDENT>self.mems = []<EOL>self.nbr_of_mems = <NUM_LIT:0><EOL>self._getting_count = False<EOL>logger.debug('<STR_LIT>')<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.MEM, CHAN_INFO)<EOL>pk.data = (CMD_INFO_NBR,)<EOL>self.cf.send_packet(pk, expected_reply=(CMD_INFO_NBR,))<EOL>
Start fetching all the detected memories
f1070:c13:m8
def _disconnected(self, uri):
self._clear_state()<EOL>
The link to the Crazyflie has been broken. Reset state
f1070:c13:m9
def _new_packet_cb(self, packet):
chan = packet.channel<EOL>cmd = packet.data[<NUM_LIT:0>]<EOL>payload = packet.data[<NUM_LIT:1>:]<EOL>if chan == CHAN_INFO:<EOL><INDENT>if cmd == CMD_INFO_NBR:<EOL><INDENT>self.nbr_of_mems = payload[<NUM_LIT:0>]<EOL>logger.info('<STR_LIT>'.format(self.nbr_of_mems))<EOL>if self.nbr_of_mems > <NUM_LIT:0>:<EOL><INDENT>if not self._getting_count:<EOL><INDENT>self._getting_count = True<EOL>logger.debug('<STR_LIT>')<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.MEM, CHAN_INFO)<EOL>pk.data = (CMD_INFO_DETAILS, <NUM_LIT:0>)<EOL>self.cf.send_packet(pk, expected_reply=(<EOL>CMD_INFO_DETAILS, <NUM_LIT:0>))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._refresh_callback()<EOL><DEDENT><DEDENT>if cmd == CMD_INFO_DETAILS:<EOL><INDENT>if len(payload) < <NUM_LIT:5>:<EOL><INDENT>logger.error(<EOL>'<STR_LIT>')<EOL>self.nbr_of_mems = <NUM_LIT:1><EOL>if self._refresh_callback:<EOL><INDENT>self._refresh_callback()<EOL>self._refresh_callback = None<EOL><DEDENT>return<EOL><DEDENT>mem_id = payload[<NUM_LIT:0>]<EOL>mem_type = payload[<NUM_LIT:1>]<EOL>mem_size = struct.unpack('<STR_LIT:I>', payload[<NUM_LIT:2>:<NUM_LIT:6>])[<NUM_LIT:0>]<EOL>mem_addr_raw = struct.unpack('<STR_LIT:B>' * <NUM_LIT:8>, payload[<NUM_LIT:6>:<NUM_LIT>])<EOL>mem_addr = '<STR_LIT>'<EOL>for m in mem_addr_raw:<EOL><INDENT>mem_addr += '<STR_LIT>'.format(m)<EOL><DEDENT>if (not self.get_mem(mem_id)):<EOL><INDENT>if mem_type == MemoryElement.TYPE_1W:<EOL><INDENT>mem = OWElement(id=mem_id, type=mem_type,<EOL>size=mem_size,<EOL>addr=mem_addr, mem_handler=self)<EOL>self.mem_read_cb.add_callback(mem.new_data)<EOL>self.mem_write_cb.add_callback(mem.write_done)<EOL>self._ow_mems_left_to_update.append(mem.id)<EOL><DEDENT>elif mem_type == MemoryElement.TYPE_I2C:<EOL><INDENT>mem = I2CElement(id=mem_id, type=mem_type,<EOL>size=mem_size,<EOL>mem_handler=self)<EOL>self.mem_read_cb.add_callback(mem.new_data)<EOL>self.mem_write_cb.add_callback(mem.write_done)<EOL><DEDENT>elif mem_type == MemoryElement.TYPE_DRIVER_LED:<EOL><INDENT>mem = LEDDriverMemory(id=mem_id, type=mem_type,<EOL>size=mem_size, mem_handler=self)<EOL>logger.debug(mem)<EOL>self.mem_read_cb.add_callback(mem.new_data)<EOL>self.mem_write_cb.add_callback(mem.write_done)<EOL><DEDENT>elif mem_type == MemoryElement.TYPE_LOCO:<EOL><INDENT>mem = LocoMemory(id=mem_id, type=mem_type,<EOL>size=mem_size, mem_handler=self)<EOL>logger.debug(mem)<EOL>self.mem_read_cb.add_callback(mem.new_data)<EOL><DEDENT>elif mem_type == MemoryElement.TYPE_TRAJ:<EOL><INDENT>mem = TrajectoryMemory(id=mem_id, type=mem_type,<EOL>size=mem_size, mem_handler=self)<EOL>logger.debug(mem)<EOL>self.mem_write_cb.add_callback(mem.write_done)<EOL><DEDENT>elif mem_type == MemoryElement.TYPE_LOCO2:<EOL><INDENT>mem = LocoMemory2(id=mem_id, type=mem_type,<EOL>size=mem_size, mem_handler=self)<EOL>logger.debug(mem)<EOL>self.mem_read_cb.add_callback(mem.new_data)<EOL><DEDENT>else:<EOL><INDENT>mem = MemoryElement(id=mem_id, type=mem_type,<EOL>size=mem_size, mem_handler=self)<EOL>logger.debug(mem)<EOL><DEDENT>self.mems.append(mem)<EOL>self.mem_added_cb.call(mem)<EOL>self._fetch_id = mem_id + <NUM_LIT:1><EOL><DEDENT>if self.nbr_of_mems - <NUM_LIT:1> >= self._fetch_id:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>'.format(<EOL>self._fetch_id))<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.MEM, CHAN_INFO)<EOL>pk.data = (CMD_INFO_DETAILS, self._fetch_id)<EOL>self.cf.send_packet(pk, expected_reply=(<EOL>CMD_INFO_DETAILS, self._fetch_id))<EOL><DEDENT>else:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>')<EOL>ows = self.get_mems(MemoryElement.TYPE_1W)<EOL>for ow_mem in ows:<EOL><INDENT>ow_mem.update(self._mem_update_done)<EOL><DEDENT>if len(ows) == <NUM_LIT:0>:<EOL><INDENT>if self._refresh_callback:<EOL><INDENT>self._refresh_callback()<EOL>self._refresh_callback = None<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if chan == CHAN_WRITE:<EOL><INDENT>id = cmd<EOL>(addr, status) = struct.unpack('<STR_LIT>', payload[<NUM_LIT:0>:<NUM_LIT:5>])<EOL>logger.debug(<EOL>'<STR_LIT>'.format(<EOL>id, addr, status))<EOL>if id in self._write_requests:<EOL><INDENT>self._write_requests_lock.acquire()<EOL>wreq = self._write_requests[id][<NUM_LIT:0>]<EOL>if status == <NUM_LIT:0>:<EOL><INDENT>if wreq.write_done(addr):<EOL><INDENT>self._write_requests[id].pop(<NUM_LIT:0>)<EOL>self.mem_write_cb.call(wreq.mem, wreq.addr)<EOL>if len(self._write_requests[id]) > <NUM_LIT:0>:<EOL><INDENT>self._write_requests[id][<NUM_LIT:0>].start()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>'.format(status))<EOL>wreq.resend()<EOL><DEDENT>self._write_requests_lock.release()<EOL><DEDENT><DEDENT>if chan == CHAN_READ:<EOL><INDENT>id = cmd<EOL>(addr, status) = struct.unpack('<STR_LIT>', payload[<NUM_LIT:0>:<NUM_LIT:5>])<EOL>data = struct.unpack('<STR_LIT:B>' * len(payload[<NUM_LIT:5>:]), payload[<NUM_LIT:5>:])<EOL>logger.debug('<STR_LIT>'<EOL>'<STR_LIT>'.format(id, addr, status, data))<EOL>if id in self._read_requests:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(id))<EOL>rreq = self._read_requests[id]<EOL>if status == <NUM_LIT:0>:<EOL><INDENT>if rreq.add_data(addr, payload[<NUM_LIT:5>:]):<EOL><INDENT>self._read_requests.pop(id, None)<EOL>self.mem_read_cb.call(rreq.mem, rreq.addr, rreq.data)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>'.format(status))<EOL>rreq.resend()<EOL><DEDENT><DEDENT><DEDENT>
Callback for newly arrived packets for the memory port
f1070:c13:m10
def fetch(self, crc):
cache_data = None<EOL>pattern = '<STR_LIT>' % crc<EOL>hit = None<EOL>for name in self._cache_files:<EOL><INDENT>if (name.endswith(pattern)):<EOL><INDENT>hit = name<EOL><DEDENT><DEDENT>if (hit):<EOL><INDENT>try:<EOL><INDENT>cache = open(hit)<EOL>cache_data = json.load(cache,<EOL>object_hook=self._decoder)<EOL>cache.close()<EOL><DEDENT>except Exception as exp:<EOL><INDENT>logger.warning('<STR_LIT>',<EOL>hit, str(exp))<EOL><DEDENT><DEDENT>return cache_data<EOL>
Try to get a hit in the cache, return None otherwise
f1071:c0:m1
def insert(self, crc, toc):
if self._rw_cache:<EOL><INDENT>try:<EOL><INDENT>filename = '<STR_LIT>' % (self._rw_cache, crc)<EOL>cache = open(filename, '<STR_LIT:w>')<EOL>cache.write(json.dumps(toc, indent=<NUM_LIT:2>,<EOL>default=self._encoder))<EOL>cache.close()<EOL>logger.info('<STR_LIT>', filename)<EOL>self._cache_files += [filename]<EOL><DEDENT>except Exception as exp:<EOL><INDENT>logger.warning('<STR_LIT>',<EOL>filename, str(exp))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>
Save a new cache to file
f1071:c0:m2
def _encoder(self, obj):
return {'<STR_LIT>': obj.__class__.__name__,<EOL>'<STR_LIT>': obj.ident,<EOL>'<STR_LIT>': obj.group,<EOL>'<STR_LIT:name>': obj.name,<EOL>'<STR_LIT>': obj.ctype,<EOL>'<STR_LIT>': obj.pytype,<EOL>'<STR_LIT>': obj.access}<EOL>raise TypeError(repr(obj) + '<STR_LIT>')<EOL>
Encode a toc element leaf-node
f1071:c0:m3
def _decoder(self, obj):
if '<STR_LIT>' in obj:<EOL><INDENT>elem = eval(obj['<STR_LIT>'])()<EOL>elem.ident = obj['<STR_LIT>']<EOL>elem.group = str(obj['<STR_LIT>'])<EOL>elem.name = str(obj['<STR_LIT:name>'])<EOL>elem.ctype = str(obj['<STR_LIT>'])<EOL>elem.pytype = str(obj['<STR_LIT>'])<EOL>elem.access = obj['<STR_LIT>']<EOL>return elem<EOL><DEDENT>return obj<EOL>
Decode a toc element leaf-node
f1071:c0:m4
def __init__(self, crazyflie):
self.receivedChar = Caller()<EOL>self.cf = crazyflie<EOL>self.cf.add_port_callback(CRTPPort.CONSOLE, self.incoming)<EOL>
Initialize the console and register it to receive data from the copter.
f1072:c0:m0
def incoming(self, packet):
<EOL>console_text = packet.data.decode('<STR_LIT>')<EOL>self.receivedChar.call(console_text)<EOL>
Callback for data received from the copter.
f1072:c0:m1
def __init__(self, ident=<NUM_LIT:0>, data=None):
self.ident = ident<EOL>if (data):<EOL><INDENT>strs = struct.unpack('<STR_LIT:s>' * len(data[<NUM_LIT:1>:]), data[<NUM_LIT:1>:])<EOL>if sys.version_info < (<NUM_LIT:3>,):<EOL><INDENT>strs = ('<STR_LIT:{}>' * len(strs)).format(*strs).split('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>s = '<STR_LIT>'<EOL>for ch in strs:<EOL><INDENT>s += ch.decode('<STR_LIT>')<EOL><DEDENT>strs = s.split('<STR_LIT:\x00>')<EOL><DEDENT>self.group = strs[<NUM_LIT:0>]<EOL>self.name = strs[<NUM_LIT:1>]<EOL>metadata = data[<NUM_LIT:0>]<EOL>if type(metadata) == str:<EOL><INDENT>metadata = ord(metadata)<EOL><DEDENT>self.ctype = self.types[metadata & <NUM_LIT>][<NUM_LIT:0>]<EOL>self.pytype = self.types[metadata & <NUM_LIT>][<NUM_LIT:1>]<EOL>if ((metadata & <NUM_LIT>) != <NUM_LIT:0>):<EOL><INDENT>self.access = ParamTocElement.RO_ACCESS<EOL><DEDENT>else:<EOL><INDENT>self.access = ParamTocElement.RW_ACCESS<EOL><DEDENT><DEDENT>
TocElement creator. Data is the binary payload of the element.
f1073:c0:m0
def request_update_of_all_params(self):
for group in self.toc.toc:<EOL><INDENT>for name in self.toc.toc[group]:<EOL><INDENT>complete_name = '<STR_LIT>' % (group, name)<EOL>self.request_param_update(complete_name)<EOL><DEDENT><DEDENT>
Request an update of all the parameters in the TOC
f1073:c1:m1
def _check_if_all_updated(self):
for g in self.toc.toc:<EOL><INDENT>if g not in self.values:<EOL><INDENT>return False<EOL><DEDENT>for n in self.toc.toc[g]:<EOL><INDENT>if n not in self.values[g]:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>
Check if all parameters from the TOC has at least been fetched once
f1073:c1:m2
def _param_updated(self, pk):
if self._useV2:<EOL><INDENT>var_id = struct.unpack('<STR_LIT>', pk.data[:<NUM_LIT:2>])[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>var_id = pk.data[<NUM_LIT:0>]<EOL><DEDENT>element = self.toc.get_element_by_id(var_id)<EOL>if element:<EOL><INDENT>if self._useV2:<EOL><INDENT>s = struct.unpack(element.pytype, pk.data[<NUM_LIT:2>:])[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>s = struct.unpack(element.pytype, pk.data[<NUM_LIT:1>:])[<NUM_LIT:0>]<EOL><DEDENT>s = s.__str__()<EOL>complete_name = '<STR_LIT>' % (element.group, element.name)<EOL>if element.group not in self.values:<EOL><INDENT>self.values[element.group] = {}<EOL><DEDENT>self.values[element.group][element.name] = s<EOL>logger.debug('<STR_LIT>' % complete_name)<EOL>if complete_name in self.param_update_callbacks:<EOL><INDENT>self.param_update_callbacks[complete_name].call(<EOL>complete_name, s)<EOL><DEDENT>if element.group in self.group_update_callbacks:<EOL><INDENT>self.group_update_callbacks[element.group].call(<EOL>complete_name, s)<EOL><DEDENT>self.all_update_callback.call(complete_name, s)<EOL>if self._check_if_all_updated() and not self.is_updated:<EOL><INDENT>self.is_updated = True<EOL>self.all_updated.call()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>', var_id)<EOL><DEDENT>
Callback with data for an updated parameter
f1073:c1:m3
def remove_update_callback(self, group, name=None, cb=None):
if not cb:<EOL><INDENT>return<EOL><DEDENT>if not name:<EOL><INDENT>if group in self.group_update_callbacks:<EOL><INDENT>self.group_update_callbacks[group].remove_callback(cb)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>paramname = '<STR_LIT>'.format(group, name)<EOL>if paramname in self.param_update_callbacks:<EOL><INDENT>self.param_update_callbacks[paramname].remove_callback(cb)<EOL><DEDENT><DEDENT>
Remove the supplied callback for a group or a group.name
f1073:c1:m4
def add_update_callback(self, group=None, name=None, cb=None):
if not group and not name:<EOL><INDENT>self.all_update_callback.add_callback(cb)<EOL><DEDENT>elif not name:<EOL><INDENT>if group not in self.group_update_callbacks:<EOL><INDENT>self.group_update_callbacks[group] = Caller()<EOL><DEDENT>self.group_update_callbacks[group].add_callback(cb)<EOL><DEDENT>else:<EOL><INDENT>paramname = '<STR_LIT>'.format(group, name)<EOL>if paramname not in self.param_update_callbacks:<EOL><INDENT>self.param_update_callbacks[paramname] = Caller()<EOL><DEDENT>self.param_update_callbacks[paramname].add_callback(cb)<EOL><DEDENT>
Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie.
f1073:c1:m5
def refresh_toc(self, refresh_done_callback, toc_cache):
self._useV2 = self.cf.platform.get_protocol_version() >= <NUM_LIT:4><EOL>toc_fetcher = TocFetcher(self.cf, ParamTocElement,<EOL>CRTPPort.PARAM, self.toc,<EOL>refresh_done_callback, toc_cache)<EOL>toc_fetcher.start()<EOL>
Initiate a refresh of the parameter TOC.
f1073:c1:m6
def _disconnected(self, uri):
self.param_updater.close()<EOL>self.is_updated = False<EOL>self.toc = Toc()<EOL>self.values = {}<EOL>
Disconnected callback from Crazyflie API
f1073:c1:m7
def request_param_update(self, complete_name):
self.param_updater.request_param_update(<EOL>self.toc.get_element_id(complete_name))<EOL>
Request an update of the value for the supplied parameter.
f1073:c1:m8
def set_value(self, complete_name, value):
element = self.toc.get_element_by_complete_name(complete_name)<EOL>if not element:<EOL><INDENT>logger.warning("<STR_LIT>",<EOL>complete_name)<EOL>raise KeyError('<STR_LIT>'.format(complete_name))<EOL><DEDENT>elif element.access == ParamTocElement.RO_ACCESS:<EOL><INDENT>logger.debug('<STR_LIT>',<EOL>complete_name)<EOL>raise AttributeError('<STR_LIT>'.format(complete_name))<EOL><DEDENT>else:<EOL><INDENT>varid = element.ident<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.PARAM, WRITE_CHANNEL)<EOL>if self._useV2:<EOL><INDENT>pk.data = struct.pack('<STR_LIT>', varid)<EOL><DEDENT>else:<EOL><INDENT>pk.data = struct.pack('<STR_LIT>', varid)<EOL><DEDENT>try:<EOL><INDENT>value_nr = eval(value)<EOL><DEDENT>except TypeError:<EOL><INDENT>value_nr = value<EOL><DEDENT>pk.data += struct.pack(element.pytype, value_nr)<EOL>self.param_updater.request_param_setvalue(pk)<EOL><DEDENT>
Set the value for the supplied parameter.
f1073:c1:m9
def __init__(self, cf, useV2, updated_callback):
Thread.__init__(self)<EOL>self.setDaemon(True)<EOL>self.wait_lock = Lock()<EOL>self.cf = cf<EOL>self._useV2 = useV2<EOL>self.updated_callback = updated_callback<EOL>self.request_queue = Queue()<EOL>self.cf.add_port_callback(CRTPPort.PARAM, self._new_packet_cb)<EOL>self._should_close = False<EOL>self._req_param = -<NUM_LIT:1><EOL>
Initialize the thread
f1073:c2:m0
def request_param_setvalue(self, pk):
self.request_queue.put(pk)<EOL>
Place a param set value request on the queue. When this is sent to the Crazyflie it will answer with the update param value.
f1073:c2:m2
def _new_packet_cb(self, pk):
if pk.channel == READ_CHANNEL or pk.channel == WRITE_CHANNEL:<EOL><INDENT>if self._useV2:<EOL><INDENT>var_id = struct.unpack('<STR_LIT>', pk.data[:<NUM_LIT:2>])[<NUM_LIT:0>]<EOL>if pk.channel == READ_CHANNEL:<EOL><INDENT>pk.data = pk.data[:<NUM_LIT:2>] + pk.data[<NUM_LIT:3>:]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>var_id = pk.data[<NUM_LIT:0>]<EOL><DEDENT>if (pk.channel != TOC_CHANNEL and self._req_param == var_id and<EOL>pk is not None):<EOL><INDENT>self.updated_callback(pk)<EOL>self._req_param = -<NUM_LIT:1><EOL>try:<EOL><INDENT>self.wait_lock.release()<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>
Callback for newly arrived packets
f1073:c2:m3
def request_param_update(self, var_id):
self._useV2 = self.cf.platform.get_protocol_version() >= <NUM_LIT:4><EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.PARAM, READ_CHANNEL)<EOL>if self._useV2:<EOL><INDENT>pk.data = struct.pack('<STR_LIT>', var_id)<EOL><DEDENT>else:<EOL><INDENT>pk.data = struct.pack('<STR_LIT>', var_id)<EOL><DEDENT>logger.debug('<STR_LIT>', var_id)<EOL>self.request_queue.put(pk)<EOL>
Place a param update request on the queue
f1073:c2:m4
def __init__(self, crazyflie, log_config):
if isinstance(crazyflie, SyncCrazyflie):<EOL><INDENT>self._cf = crazyflie.cf<EOL><DEDENT>else:<EOL><INDENT>self._cf = crazyflie<EOL><DEDENT>self._log_config = log_config<EOL>self._cf.log.add_config(self._log_config)<EOL>self._queue = Queue()<EOL>self._is_connected = False<EOL>
Construct an instance of a SyncLogger Takes an Crazyflie or SyncCrazyflie instance and a log configuration
f1074:c0:m0
def __init__(self, uris, factory=_Factory()):
self._cfs = {}<EOL>self._is_open = False<EOL>for uri in uris:<EOL><INDENT>self._cfs[uri] = factory.construct(uri)<EOL><DEDENT>
Constructs a Swarm instance and instances used to connect to the Crazyflies :param uris: A set of uris to use when connecting to the Crazyflies in the swarm :param factory: A factory class used to create the instances that are used to open links to the Crazyflies. Mainly used for unit testing.
f1075:c2:m0
def open_links(self):
if self._is_open:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>self.parallel_safe(lambda scf: scf.open_link())<EOL>self._is_open = True<EOL><DEDENT>except Exception as e:<EOL><INDENT>self.close_links()<EOL>raise e<EOL><DEDENT>
Open links to all individuals in the swarm
f1075:c2:m1
def close_links(self):
for uri, cf in self._cfs.items():<EOL><INDENT>cf.close_link()<EOL><DEDENT>self._is_open = False<EOL>
Close all open links
f1075:c2:m2
def sequential(self, func, args_dict=None):
for uri, cf in self._cfs.items():<EOL><INDENT>args = self._process_args_dict(cf, uri, args_dict)<EOL>func(*args)<EOL><DEDENT>
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
f1075:c2:m5
def parallel(self, func, args_dict=None):
try:<EOL><INDENT>self.parallel_safe(func, args_dict)<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>
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. Exceptions raised by the threads are ignored. For a description of the arguments, see sequential() :param func: :param args_dict:
f1075:c2:m6
def parallel_safe(self, func, args_dict=None):
threads = []<EOL>reporter = self.Reporter()<EOL>for uri, scf in self._cfs.items():<EOL><INDENT>args = [func, reporter] +self._process_args_dict(scf, uri, args_dict)<EOL>thread = Thread(target=self._thread_function_wrapper, args=args)<EOL>threads.append(thread)<EOL>thread.start()<EOL><DEDENT>for thread in threads:<EOL><INDENT>thread.join()<EOL><DEDENT>if reporter.is_error_reported():<EOL><INDENT>raise Exception('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>
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:
f1075:c2:m7
def is_toc_variable(self):
return self.type == LogVariable.TOC_TYPE<EOL>
Return true if the variable should be in the TOC, false if raw memory variable
f1076:c0:m1
def get_storage_and_fetch_byte(self):
return (self.fetch_as | (self.stored_as << <NUM_LIT:4>))<EOL>
Return what the variable is stored as and fetched as
f1076:c0:m2
def __init__(self, name, period_in_ms):
self.data_received_cb = Caller()<EOL>self.error_cb = Caller()<EOL>self.started_cb = Caller()<EOL>self.added_cb = Caller()<EOL>self.err_no = <NUM_LIT:0><EOL>self.id = <NUM_LIT:0><EOL>self.cf = None<EOL>self.useV2 = False<EOL>self.period = int(period_in_ms / <NUM_LIT:10>)<EOL>self.period_in_ms = period_in_ms<EOL>self._added = False<EOL>self._started = False<EOL>self.valid = False<EOL>self.variables = []<EOL>self.default_fetch_as = []<EOL>self.name = name<EOL>
Initialize the entry
f1076:c1:m0
def add_variable(self, name, fetch_as=None):
if fetch_as:<EOL><INDENT>self.variables.append(LogVariable(name, fetch_as))<EOL><DEDENT>else:<EOL><INDENT>self.default_fetch_as.append(name)<EOL><DEDENT>
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).
f1076:c1:m1
def add_memory(self, name, fetch_as, stored_as, address):
self.variables.append(LogVariable(name, fetch_as, LogVariable.MEM_TYPE,<EOL>stored_as, address))<EOL>
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
f1076:c1:m2
def create(self):
pk = CRTPPacket()<EOL>pk.set_header(<NUM_LIT:5>, CHAN_SETTINGS)<EOL>if self.useV2:<EOL><INDENT>pk.data = (CMD_CREATE_BLOCK_V2, self.id)<EOL><DEDENT>else:<EOL><INDENT>pk.data = (CMD_CREATE_BLOCK, self.id)<EOL><DEDENT>for var in self.variables:<EOL><INDENT>if (var.is_toc_variable() is False): <EOL><INDENT>logger.debug('<STR_LIT>',<EOL>var.get_storage_and_fetch_byte(), var.address)<EOL>pk.data.append(struct.pack('<STR_LIT>',<EOL>var.get_storage_and_fetch_byte()))<EOL>pk.data.append(struct.pack('<STR_LIT>', var.address))<EOL><DEDENT>else: <EOL><INDENT>logger.debug('<STR_LIT>',<EOL>var.name,<EOL>self.cf.log.toc.get_element_id(<EOL>var.name), var.get_storage_and_fetch_byte())<EOL>pk.data.append(var.get_storage_and_fetch_byte())<EOL>if self.useV2:<EOL><INDENT>ident = self.cf.log.toc.get_element_id(var.name)<EOL>pk.data.append(ident & <NUM_LIT>)<EOL>pk.data.append((ident >> <NUM_LIT:8>) & <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>pk.data.append(self.cf.log.toc.get_element_id(var.name))<EOL><DEDENT><DEDENT><DEDENT>logger.debug('<STR_LIT>'.format(self.id))<EOL>if self.useV2:<EOL><INDENT>self.cf.send_packet(pk, expected_reply=(<EOL>CMD_CREATE_BLOCK_V2, self.id))<EOL><DEDENT>else:<EOL><INDENT>self.cf.send_packet(pk, expected_reply=(CMD_CREATE_BLOCK, self.id))<EOL><DEDENT>
Save the log configuration in the Crazyflie
f1076:c1:m7
def start(self):
if (self.cf.link is not None):<EOL><INDENT>if (self._added is False):<EOL><INDENT>self.create()<EOL>logger.debug('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>'<EOL>'<STR_LIT>', self.id)<EOL>pk = CRTPPacket()<EOL>pk.set_header(<NUM_LIT:5>, CHAN_SETTINGS)<EOL>pk.data = (CMD_START_LOGGING, self.id, self.period)<EOL>self.cf.send_packet(pk, expected_reply=(<EOL>CMD_START_LOGGING, self.id))<EOL><DEDENT><DEDENT>
Start the logging for this entry
f1076:c1:m8
def stop(self):
if (self.cf.link is not None):<EOL><INDENT>if (self.id is None):<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>', self.id)<EOL>pk = CRTPPacket()<EOL>pk.set_header(<NUM_LIT:5>, CHAN_SETTINGS)<EOL>pk.data = (CMD_STOP_LOGGING, self.id)<EOL>self.cf.send_packet(<EOL>pk, expected_reply=(CMD_STOP_LOGGING, self.id))<EOL><DEDENT><DEDENT>
Stop the logging for this entry
f1076:c1:m9
def delete(self):
if (self.cf.link is not None):<EOL><INDENT>if (self.id is None):<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>'<EOL>% self.id)<EOL>pk = CRTPPacket()<EOL>pk.set_header(<NUM_LIT:5>, CHAN_SETTINGS)<EOL>pk.data = (CMD_DELETE_BLOCK, self.id)<EOL>self.cf.send_packet(<EOL>pk, expected_reply=(CMD_DELETE_BLOCK, self.id))<EOL><DEDENT><DEDENT>
Delete this entry in the Crazyflie
f1076:c1:m10
def unpack_log_data(self, log_data, timestamp):
ret_data = {}<EOL>data_index = <NUM_LIT:0><EOL>for var in self.variables:<EOL><INDENT>size = LogTocElement.get_size_from_id(var.fetch_as)<EOL>name = var.name<EOL>unpackstring = LogTocElement.get_unpack_string_from_id(<EOL>var.fetch_as)<EOL>value = struct.unpack(<EOL>unpackstring, log_data[data_index:data_index + size])[<NUM_LIT:0>]<EOL>data_index += size<EOL>ret_data[name] = value<EOL><DEDENT>self.data_received_cb.call(timestamp, ret_data, self)<EOL>
Unpack received logging data so it represent real values according to the configuration in the entry
f1076:c1:m11
@staticmethod<EOL><INDENT>def get_id_from_cstring(name):<DEDENT>
for key in list(LogTocElement.types.keys()):<EOL><INDENT>if (LogTocElement.types[key][<NUM_LIT:0>] == name):<EOL><INDENT>return key<EOL><DEDENT><DEDENT>raise KeyError('<STR_LIT>' % name)<EOL>
Return variable type id given the C-storage name
f1076:c2:m0
@staticmethod<EOL><INDENT>def get_cstring_from_id(ident):<DEDENT>
try:<EOL><INDENT>return LogTocElement.types[ident][<NUM_LIT:0>]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError('<STR_LIT>'<EOL>'<STR_LIT:!>' % ident)<EOL><DEDENT>
Return the C-storage name given the variable type id
f1076:c2:m1
@staticmethod<EOL><INDENT>def get_size_from_id(ident):<DEDENT>
try:<EOL><INDENT>return LogTocElement.types[ident][<NUM_LIT:2>]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError('<STR_LIT>'<EOL>'<STR_LIT:!>' % ident)<EOL><DEDENT>
Return the size in bytes given the variable type id
f1076:c2:m2
@staticmethod<EOL><INDENT>def get_unpack_string_from_id(ident):<DEDENT>
try:<EOL><INDENT>return LogTocElement.types[ident][<NUM_LIT:1>]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError(<EOL>'<STR_LIT>' % ident)<EOL><DEDENT>
Return the Python unpack string given the variable type id
f1076:c2:m3
def __init__(self, ident=<NUM_LIT:0>, data=None):
self.ident = ident<EOL>if (data):<EOL><INDENT>naming = data[<NUM_LIT:1>:]<EOL>zt = bytearray((<NUM_LIT:0>, ))<EOL>self.group = naming[:naming.find(zt)].decode('<STR_LIT>')<EOL>self.name = naming[naming.find(zt) + <NUM_LIT:1>:-<NUM_LIT:1>].decode('<STR_LIT>')<EOL>self.ctype = LogTocElement.get_cstring_from_id(data[<NUM_LIT:0>])<EOL>self.pytype = LogTocElement.get_unpack_string_from_id(data[<NUM_LIT:0>])<EOL>self.access = data[<NUM_LIT:0>] & <NUM_LIT><EOL><DEDENT>
TocElement creator. Data is the binary payload of the element.
f1076:c2:m4
def add_config(self, logconf):
if not self.cf.link:<EOL><INDENT>logger.error('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>for name in logconf.default_fetch_as:<EOL><INDENT>var = self.toc.get_element_by_complete_name(name)<EOL>if not var:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>', name)<EOL>logconf.valid = False<EOL>raise KeyError('<STR_LIT>'.format(name))<EOL><DEDENT>logconf.add_variable(name, var.ctype)<EOL><DEDENT>size = <NUM_LIT:0><EOL>for var in logconf.variables:<EOL><INDENT>size += LogTocElement.get_size_from_id(var.fetch_as)<EOL>if var.is_toc_variable():<EOL><INDENT>if (self.toc.get_element_by_complete_name(var.name) is None):<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>',<EOL>var.name)<EOL>logconf.valid = False<EOL>raise KeyError('<STR_LIT>'.format(var.name))<EOL><DEDENT><DEDENT><DEDENT>if (size <= MAX_LOG_DATA_PACKET_SIZE and<EOL>(logconf.period > <NUM_LIT:0> and logconf.period < <NUM_LIT>)):<EOL><INDENT>logconf.valid = True<EOL>logconf.cf = self.cf<EOL>logconf.id = self._config_id_counter<EOL>logconf.useV2 = self._useV2<EOL>self._config_id_counter = (self._config_id_counter + <NUM_LIT:1>) % <NUM_LIT:255><EOL>self.log_blocks.append(logconf)<EOL>self.block_added_cb.call(logconf)<EOL><DEDENT>else:<EOL><INDENT>logconf.valid = False<EOL>raise AttributeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>
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.
f1076:c3:m1
def refresh_toc(self, refresh_done_callback, toc_cache):
self._useV2 = self.cf.platform.get_protocol_version() >= <NUM_LIT:4><EOL>self._toc_cache = toc_cache<EOL>self._refresh_callback = refresh_done_callback<EOL>self.toc = None<EOL>pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.LOGGING, CHAN_SETTINGS)<EOL>pk.data = (CMD_RESET_LOGGING,)<EOL>self.cf.send_packet(pk, expected_reply=(CMD_RESET_LOGGING,))<EOL>
Start refreshing the table of loggale variables
f1076:c3:m2
def _new_packet_cb(self, packet):
chan = packet.channel<EOL>cmd = packet.data[<NUM_LIT:0>]<EOL>payload = packet.data[<NUM_LIT:1>:]<EOL>if (chan == CHAN_SETTINGS):<EOL><INDENT>id = payload[<NUM_LIT:0>]<EOL>error_status = payload[<NUM_LIT:1>]<EOL>block = self._find_block(id)<EOL>if cmd == CMD_CREATE_BLOCK or cmd == CMD_CREATE_BLOCK_V2:<EOL><INDENT>if (block is not None):<EOL><INDENT>if error_status == <NUM_LIT:0> or error_status == errno.EEXIST:<EOL><INDENT>if not block.added:<EOL><INDENT>logger.debug('<STR_LIT>', id)<EOL>pk = CRTPPacket()<EOL>pk.set_header(<NUM_LIT:5>, CHAN_SETTINGS)<EOL>pk.data = (CMD_START_LOGGING, id, block.period)<EOL>self.cf.send_packet(pk, expected_reply=(<EOL>CMD_START_LOGGING, id))<EOL>block.added = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = self._err_codes[error_status]<EOL>logger.warning('<STR_LIT>',<EOL>error_status, id, msg)<EOL>block.err_no = error_status<EOL>block.added_cb.call(False)<EOL>block.error_cb.call(block, msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT><DEDENT>if (cmd == CMD_START_LOGGING):<EOL><INDENT>if (error_status == <NUM_LIT>):<EOL><INDENT>logger.info('<STR_LIT>',<EOL>id)<EOL>if block:<EOL><INDENT>block.started = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = self._err_codes[error_status]<EOL>logger.warning('<STR_LIT>',<EOL>error_status, id, msg)<EOL>if block:<EOL><INDENT>block.err_no = error_status<EOL>block.started_cb.call(self, False)<EOL><DEDENT><DEDENT><DEDENT>if (cmd == CMD_STOP_LOGGING):<EOL><INDENT>if (error_status == <NUM_LIT>):<EOL><INDENT>logger.info('<STR_LIT>',<EOL>id)<EOL>if block:<EOL><INDENT>block.started = False<EOL><DEDENT><DEDENT><DEDENT>if (cmd == CMD_DELETE_BLOCK):<EOL><INDENT>if error_status == <NUM_LIT> or error_status == errno.ENOENT:<EOL><INDENT>logger.info('<STR_LIT>', id)<EOL>if block:<EOL><INDENT>block.started = False<EOL>block.added = False<EOL><DEDENT><DEDENT><DEDENT>if (cmd == CMD_RESET_LOGGING):<EOL><INDENT>if not self.toc:<EOL><INDENT>logger.debug('<STR_LIT>')<EOL>self.log_blocks = []<EOL>self.toc = Toc()<EOL>toc_fetcher = TocFetcher(self.cf, LogTocElement,<EOL>CRTPPort.LOGGING,<EOL>self.toc, self._refresh_callback,<EOL>self._toc_cache)<EOL>toc_fetcher.start()<EOL><DEDENT><DEDENT><DEDENT>if (chan == CHAN_LOGDATA):<EOL><INDENT>chan = packet.channel<EOL>id = packet.data[<NUM_LIT:0>]<EOL>block = self._find_block(id)<EOL>timestamps = struct.unpack('<STR_LIT>', packet.data[<NUM_LIT:1>:<NUM_LIT:4>])<EOL>timestamp = (<EOL>timestamps[<NUM_LIT:0>] | timestamps[<NUM_LIT:1>] << <NUM_LIT:8> | timestamps[<NUM_LIT:2>] << <NUM_LIT:16>)<EOL>logdata = packet.data[<NUM_LIT:4>:]<EOL>if (block is not None):<EOL><INDENT>block.unpack_log_data(logdata, timestamp)<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', id)<EOL><DEDENT><DEDENT>
Callback for newly arrived packets with TOC information
f1076:c3:m4
def __init__(self, crazyflie=None):
self._cf = crazyflie<EOL>self._x_mode = False<EOL>
Initialize the commander object. By default the commander is in +-mode (not x-mode).
f1077:c0:m0
def set_client_xmode(self, enabled):
self._x_mode = enabled<EOL>
Enable/disable the client side X-mode. When enabled this recalculates the setpoints before sending them to the Crazyflie.
f1077:c0:m1
def send_setpoint(self, roll, pitch, yaw, thrust):
if thrust > <NUM_LIT> or thrust < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self._x_mode:<EOL><INDENT>roll, pitch = <NUM_LIT> * (roll - pitch), <NUM_LIT> * (roll + pitch)<EOL><DEDENT>pk = CRTPPacket()<EOL>pk.port = CRTPPort.COMMANDER<EOL>pk.data = struct.pack('<STR_LIT>', roll, -pitch, yaw, thrust)<EOL>self._cf.send_packet(pk)<EOL>
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
f1077:c0:m2
def send_stop_setpoint(self):
pk = CRTPPacket()<EOL>pk.port = CRTPPort.COMMANDER_GENERIC<EOL>pk.data = struct.pack('<STR_LIT>', TYPE_STOP)<EOL>self._cf.send_packet(pk)<EOL>
Send STOP setpoing, stopping the motors and (potentially) falling.
f1077:c0:m3
def send_velocity_world_setpoint(self, vx, vy, vz, yawrate):
pk = CRTPPacket()<EOL>pk.port = CRTPPort.COMMANDER_GENERIC<EOL>pk.data = struct.pack('<STR_LIT>', TYPE_VELOCITY_WORLD,<EOL>vx, vy, vz, yawrate)<EOL>self._cf.send_packet(pk)<EOL>
Send Velocity in the world frame of reference setpoint. vx, vy, vz are in m/s yawrate is in degrees/s
f1077:c0:m4
def send_zdistance_setpoint(self, roll, pitch, yawrate, zdistance):
pk = CRTPPacket()<EOL>pk.port = CRTPPort.COMMANDER_GENERIC<EOL>pk.data = struct.pack('<STR_LIT>', TYPE_ZDISTANCE,<EOL>roll, pitch, yawrate, zdistance)<EOL>self._cf.send_packet(pk)<EOL>
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
f1077:c0:m5
def send_hover_setpoint(self, vx, vy, yawrate, zdistance):
pk = CRTPPacket()<EOL>pk.port = CRTPPort.COMMANDER_GENERIC<EOL>pk.data = struct.pack('<STR_LIT>', TYPE_HOVER,<EOL>vx, vy, yawrate, zdistance)<EOL>self._cf.send_packet(pk)<EOL>
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
f1077:c0:m6
def send_position_setpoint(self, x, y, z, yaw):
pk = CRTPPacket()<EOL>pk.port = CRTPPort.COMMANDER_GENERIC<EOL>pk.data = struct.pack('<STR_LIT>', TYPE_POSITION,<EOL>x, y, z, yaw)<EOL>self._cf.send_packet(pk)<EOL>
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
f1077:c0:m7
def __init__(self, crazyflie=None):
self._cf = crazyflie<EOL>self._cf.add_port_callback(CRTPPort.PLATFORM,<EOL>self._platform_callback)<EOL>self._cf.add_port_callback(CRTPPort.LINKCTRL,<EOL>self._crt_service_callback)<EOL>self._has_protocol_version = False<EOL>self._protocolVersion = -<NUM_LIT:1><EOL>self._callback = None<EOL>
Initialize the platform object.
f1078:c0:m0
def fetch_platform_informations(self, callback):
self._protocolVersion = -<NUM_LIT:1><EOL>self._callback = callback<EOL>self._request_protocol_version()<EOL>
Fetch platform info from the firmware Should be called at the earliest in the connection sequence
f1078:c0:m1
def set_continous_wave(self, enabled):
pk = CRTPPacket()<EOL>pk.set_header(CRTPPort.PLATFORM, PLATFORM_COMMAND)<EOL>pk.data = (<NUM_LIT:0>, enabled)<EOL>self._cf.send_packet(pk)<EOL>
Enable/disable the client side X-mode. When enabled this recalculates the setpoints before sending them to the Crazyflie.
f1078:c0:m2
def get_protocol_version(self):
return self._protocolVersion<EOL>
Return version of the CRTP protocol
f1078:c0:m3
def __init__(self, link=None, ro_cache=None, rw_cache=None):
<EOL>self.disconnected = Caller()<EOL>self.connection_lost = Caller()<EOL>self.link_established = Caller()<EOL>self.connection_requested = Caller()<EOL>self.connected = Caller()<EOL>self.connection_failed = Caller()<EOL>self.packet_received = Caller()<EOL>self.packet_sent = Caller()<EOL>self.link_quality_updated = Caller()<EOL>self.state = State.DISCONNECTED<EOL>self.link = link<EOL>self._toc_cache = TocCache(ro_cache=ro_cache,<EOL>rw_cache=rw_cache)<EOL>self.incoming = _IncomingPacketHandler(self)<EOL>self.incoming.setDaemon(True)<EOL>self.incoming.start()<EOL>self.commander = Commander(self)<EOL>self.high_level_commander = HighLevelCommander(self)<EOL>self.loc = Localization(self)<EOL>self.extpos = Extpos(self)<EOL>self.log = Log(self)<EOL>self.console = Console(self)<EOL>self.param = Param(self)<EOL>self.mem = Memory(self)<EOL>self.platform = PlatformService(self)<EOL>self.link_uri = '<STR_LIT>'<EOL>self.packet_received.add_callback(self._check_for_initial_packet_cb)<EOL>self.packet_received.add_callback(self._check_for_answers)<EOL>self._answer_patterns = {}<EOL>self._send_lock = Lock()<EOL>self.connected_ts = None<EOL>self.disconnected.add_callback(<EOL>lambda uri: logger.info('<STR_LIT>', uri))<EOL>self.disconnected.add_callback(self._disconnected)<EOL>self.link_established.add_callback(<EOL>lambda uri: logger.info('<STR_LIT>', uri))<EOL>self.connection_lost.add_callback(<EOL>lambda uri, errmsg: logger.info(<EOL>'<STR_LIT>', uri, errmsg))<EOL>self.connection_failed.add_callback(<EOL>lambda uri, errmsg: logger.info(<EOL>'<STR_LIT>', uri, errmsg))<EOL>self.connection_requested.add_callback(<EOL>lambda uri: logger.info(<EOL>'<STR_LIT>', uri))<EOL>self.connected.add_callback(<EOL>lambda uri: logger.info(<EOL>'<STR_LIT>', uri))<EOL>
Create the objects from this module and register callbacks. ro_cache -- Path to read-only cache (string) rw_cache -- Path to read-write cache (string)
f1079:c1:m0
def _disconnected(self, link_uri):
self.connected_ts = None<EOL>
Callback when disconnected.
f1079:c1:m1
def _start_connection_setup(self):
logger.info('<STR_LIT>',<EOL>self.link_uri)<EOL>self.platform.fetch_platform_informations(self._platform_info_fetched)<EOL>
Start the connection setup by refreshing the TOCs
f1079:c1:m2
def _param_toc_updated_cb(self):
logger.info('<STR_LIT>')<EOL>self.connected_ts = datetime.datetime.now()<EOL>self.connected.call(self.link_uri)<EOL>self.param.request_update_of_all_params()<EOL>
Called when the param TOC has been fully updated
f1079:c1:m4
def _mems_updated_cb(self):
logger.info('<STR_LIT>')<EOL>self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache)<EOL>
Called when the memories have been identified
f1079:c1:m5
def _log_toc_updated_cb(self):
logger.info('<STR_LIT>')<EOL>self.mem.refresh(self._mems_updated_cb)<EOL>
Called when the log TOC has been fully updated
f1079:c1:m6
def _link_error_cb(self, errmsg):
logger.warning('<STR_LIT>',<EOL>errmsg, self.state)<EOL>if (self.link is not None):<EOL><INDENT>self.link.close()<EOL><DEDENT>self.link = None<EOL>if (self.state == State.INITIALIZED):<EOL><INDENT>self.connection_failed.call(self.link_uri, errmsg)<EOL><DEDENT>if (self.state == State.CONNECTED or<EOL>self.state == State.SETUP_FINISHED):<EOL><INDENT>self.disconnected.call(self.link_uri)<EOL>self.connection_lost.call(self.link_uri, errmsg)<EOL><DEDENT>self.state = State.DISCONNECTED<EOL>
Called from the link driver when there's an error
f1079:c1:m7
def _link_quality_cb(self, percentage):
self.link_quality_updated.call(percentage)<EOL>
Called from link driver to report link quality
f1079:c1:m8