desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Stop the logging of this block'
def stop(self):
self._doing_transaction = True self._block.delete()
'Return True if a block is being added or started, False when it\'s been added/started/failed'
def doing_transaction(self):
return self._doing_transaction
'Callback when a block has been added to the Crazyflie'
def _set_added(self, conf, started):
logger.debug('%s added: %s', self.name, started)
'Return a string containing all the variable names of the children'
def var_list(self):
return self._var_list
'Return the number of children this node has'
def child_count(self):
return len(self.children)
'Force a refresh of the view though the model'
def refresh(self):
self.layoutChanged.emit()
'Callback when a cell has been clicked (mouse down/up on same cell)'
def clicked(self, index):
node = index.internalPointer() if ((not node.parent) and (index.column() == 3)): if node.logging_started(): node.stop() else: node.start() if ((not node.parent) and (index.column() == 4)): if node.writing_to_file(): node.stop_writing_to_file() else: node.start_writing_to_file() self.layoutChanged.emit()
'Re-implemented method to get the parent of the given index'
def parent(self, index):
if (not index.isValid()): return QModelIndex() node = index.internalPointer() if (node.parent is None): return QModelIndex() else: return self.createIndex(self._nodes.index(node.parent), 0, node.parent)
'Remove a block from the view'
def remove_block(self, block):
raise NotImplementedError()
'Re-implemented method to get the number of columns'
def columnCount(self, parent):
return len(self._column_headers)
'Re-implemented method to get the headers'
def headerData(self, section, orientation, role):
if (role == Qt.DisplayRole): return self._column_headers[section]
'Re-implemented method to get the number of rows for a given index'
def rowCount(self, parent):
parent_item = parent.internalPointer() if parent.isValid(): parent_item = parent.internalPointer() return parent_item.child_count() else: return len(self._nodes)
'Re-implemented method to get the index for a specified row/column/parent combination'
def index(self, row, column, parent):
if (not self._nodes): return QModelIndex() node = parent.internalPointer() if (not node): index = self.createIndex(row, column, self._nodes[row]) self._nodes[row].index = index return index else: return self.createIndex(row, column, node.get_child(row))
'Re-implemented method to get the data for a given index and role'
def data(self, index, role):
node = index.internalPointer() parent = node.parent if parent: if ((role == Qt.DisplayRole) and (index.column() == 5)): return node.name elif ((not parent) and (role == Qt.DisplayRole) and (index.column() == 5)): return node.var_list() elif ((not parent) and (role == Qt.DisplayRole)): if (index.column() == 0): return node.id if (index.column() == 1): return node.name if (index.column() == 2): return str(node.period) if ((role == Qt.TextAlignmentRole) and ((index.column() == 4) or (index.column() == 3))): return (Qt.AlignHCenter | Qt.AlignVCenter) return None
'Reset the model'
def reset(self):
for node in self._nodes: if node.writing_to_file(): node.stop_writing_to_file() self._nodes = [] self.layoutChanged.emit()
'Re-implemented paint method'
def paint(self, painter, option, index):
item = index.internalPointer() col = index.column() if ((not item.parent) and ((col == 3) or (col == 4))): s = QStyleOptionButton() checkbox_rect = QApplication.style().subElementRect(QStyle.SE_CheckBoxIndicator, option) s.rect = option.rect center_offset = ((s.rect.width() / 2) - (checkbox_rect.width() / 2)) s.rect.adjust(center_offset, 0, 0, 0) if (col == 3): if (not item.doing_transaction()): s.state = QStyle.State_Enabled if item.logging_started(): s.state |= QStyle.State_On if (col == 4): s.state = QStyle.State_Enabled if item.writing_to_file(): s.state |= QStyle.State_On QApplication.style().drawControl(QStyle.CE_CheckBox, s, painter) else: super(CheckboxDelegate, self).paint(painter, option, index)
'Initialize the tab'
def __init__(self, tabWidget, helper, *args):
super(LogBlockTab, self).__init__(*args) self.setupUi(self) self.tabName = 'Log Blocks' self.menuName = 'Log Blocks' self._helper = helper self.tabWidget = tabWidget self._helper.cf.log.block_added_cb.add_callback(self._block_added) self._disconnected_signal.connect(self._disconnected) self._helper.cf.disconnected.add_callback(self._disconnected_signal.emit) self._model = LogBlockModel(self._block_tree) self._block_tree.setModel(self._model) self._block_tree.clicked.connect(self._model.clicked) self._block_tree.setItemDelegate(CheckboxDelegate()) self._block_tree.setSelectionMode(QAbstractItemView.NoSelection)
'Callback from logging layer when a new block is added'
def _block_added(self, block):
self._model.add_block(block, self._helper.cf.connected_ts)
'Callback when the Crazyflie is disconnected'
def _disconnected(self, link_uri):
self._model.beginResetModel() self._model.reset() self._model.endResetModel()
'Callback for when the Crazyflie has been disconnected'
def _disconnected(self, link_uri):
return
'Callback from the log layer when an error occurs'
def _logging_error(self, log_conf, msg):
QMessageBox.about(self, 'Plot error', ('Error when starting log config [%s]: %s' % (log_conf.name, msg)))
'Callback from reset button'
def _reset_max(self):
self._max_speed = 0.0 self._speed_max.setText(str(self._max_speed)) self._long.setText('') self._lat.setText('') self._height.setText('') self._speed.setText('') self._heading.setText('') self._accuracy.setText('') self._fix_type.setText('')
'Callback when the log layer receives new data'
def _log_data_received(self, timestamp, data, logconf):
long = (float(data['gps.lon']) / 10000000.0) lat = (float(data['gps.lat']) / 10000000.0) if ((self._lat != lat) or (self._long != long)): self._long.setText('{:.6f}'.format(long)) self._lat.setText('{:.6f}'.format(lat)) self._nbr_locked_sats.setText(str(data['gps.nsat'])) self._height.setText('{:.2f}'.format(float(data['gps.hMSL']))) self._place_cf(long, lat, 1) self._lat = lat self._long = long
'Initialize the node'
def __init__(self, parent, name, crazyflie):
self.parent = parent self.name = name self.ctype = None self.access = None self.value = '' self._cf = crazyflie self.is_updating = True
'Callback from the param layer when a parameter has been updated'
def updated(self, name, value):
self.value = value self.is_updating = False self.parent.model.refresh()
'Send the update value to the Crazyflie. It will automatically be read again after sending and then the updated callback will be called'
def set_value(self, value):
complete_name = ('%s.%s' % (self.parent.name, self.name)) self._cf.param.set_value(complete_name, value) self.is_updating = True
'Return the number of children this node has'
def child_count(self):
return 0
'Initialize the parent node'
def __init__(self, name, model):
super(ParamGroupItem, self).__init__() self.parent = None self.children = [] self.name = name self.model = model
'Return the number of children this node has'
def child_count(self):
return len(self.children)
'Create the empty model'
def __init__(self, parent):
super(ParamBlockModel, self).__init__(parent) self._nodes = [] self._column_headers = ['Name', 'Type', 'Access', 'Value'] self._red_brush = QBrush(QColor('red'))
'Populate the model with data from the param TOC'
def set_toc(self, toc, crazyflie):
for group in sorted(toc.keys()): new_group = ParamGroupItem(group, self) for param in sorted(toc[group].keys()): new_param = ParamChildItem(new_group, param, crazyflie) new_param.ctype = toc[group][param].ctype new_param.access = toc[group][param].get_readable_access() crazyflie.param.add_update_callback(group=group, name=param, cb=new_param.updated) new_group.children.append(new_param) self._nodes.append(new_group) self.layoutChanged.emit()
'Force a refresh of the view though the model'
def refresh(self):
self.layoutChanged.emit()
'Re-implemented method to get the parent of the given index'
def parent(self, index):
if (not index.isValid()): return QModelIndex() node = index.internalPointer() if (node.parent is None): return QModelIndex() else: return self.createIndex(self._nodes.index(node.parent), 0, node.parent)
'Re-implemented method to get the number of columns'
def columnCount(self, parent):
return len(self._column_headers)
'Re-implemented method to get the headers'
def headerData(self, section, orientation, role):
if (role == Qt.DisplayRole): return self._column_headers[section]
'Re-implemented method to get the number of rows for a given index'
def rowCount(self, parent):
parent_item = parent.internalPointer() if parent.isValid(): parent_item = parent.internalPointer() return parent_item.child_count() else: return len(self._nodes)
'Re-implemented method to get the index for a specified row/column/parent combination'
def index(self, row, column, parent):
if (not self._nodes): return QModelIndex() node = parent.internalPointer() if (not node): index = self.createIndex(row, column, self._nodes[row]) self._nodes[row].index = index return index else: return self.createIndex(row, column, node.children[row])
'Re-implemented method to get the data for a given index and role'
def data(self, index, role):
node = index.internalPointer() parent = node.parent if (not parent): if ((role == Qt.DisplayRole) and (index.column() == 0)): return node.name elif (role == Qt.DisplayRole): if (index.column() == 0): return node.name if (index.column() == 1): return node.ctype if (index.column() == 2): return node.access if (index.column() == 3): return node.value elif ((role == Qt.EditRole) and (index.column() == 3)): return node.value elif ((role == Qt.BackgroundRole) and (index.column() == 3) and node.is_updating): return self._red_brush return None
'Re-implemented function called when a value has been edited'
def setData(self, index, value, role):
node = index.internalPointer() if (role == Qt.EditRole): new_val = str(value) node.set_value(new_val) return True return False
'Re-implemented function for getting the flags for a certain index'
def flags(self, index):
flag = super(ParamBlockModel, self).flags(index) node = index.internalPointer() if ((index.column() == 3) and node.parent and (node.access == 'RW')): flag |= Qt.ItemIsEditable return flag
'Reset the model'
def reset(self):
super(ParamBlockModel, self).beginResetModel() self._nodes = [] super(ParamBlockModel, self).endResetModel() self.layoutChanged.emit()
'Create the parameter tab'
def __init__(self, tabWidget, helper, *args):
super(ParamTab, self).__init__(*args) self.setupUi(self) self.tabName = 'Parameters' self.menuName = 'Parameters' self.helper = helper self.tabWidget = tabWidget self.cf = helper.cf self.cf.connected.add_callback(self._connected_signal.emit) self._connected_signal.connect(self._connected) self.cf.disconnected.add_callback(self._disconnected_signal.emit) self._disconnected_signal.connect(self._disconnected) self._model = ParamBlockModel(None) self.paramTree.setModel(self._model)
'Callback when a new logblock has been created'
def _block_added(self, block):
block.added_cb.add_callback(self._blocks_updated_signal.emit) block.started_cb.add_callback(self._blocks_updated_signal.emit)
'Update the block tree'
def _update_tree(self, conf, value):
self._block_tree.clear() for block in self._helper.cf.log.log_blocks: item = QtWidgets.QTreeWidgetItem() item.setFlags((Qt.ItemIsEnabled | Qt.ItemIsSelectable)) item.setData(0, Qt.DisplayRole, block.id) item.setData(1, Qt.EditRole, block.name) item.setData(2, Qt.DisplayRole, block.period_in_ms) item.setData(3, Qt.DisplayRole, block.added) item.setData(4, Qt.EditRole, block.started) item.setData(5, Qt.EditRole, block.err_no) for var in block.variables: subItem = QtWidgets.QTreeWidgetItem() subItem.setFlags((Qt.ItemIsEnabled | Qt.ItemIsSelectable)) subItem.setData(6, Qt.EditRole, var.name) item.addChild(subItem) self._block_tree.addTopLevelItem(item) self._block_tree.expandItem(item)
'Callback when the Crazyflie is disconnected'
def _disconnected(self, link_uri):
self._block_tree.clear()
'Show or hide the tab.'
@pyqtSlot(bool) def toggleVisibility(self, checked):
if checked: self.tabWidget.addTab(self, self.getTabName()) s = '' try: s = Config().get('open_tabs') if (len(s) > 0): s += ',' except Exception: logger.warning('Exception while adding tab to config and reading tab config') if (self.tabName not in s): s += ('%s' % self.tabName) Config().set('open_tabs', str(s)) if (not checked): self.tabWidget.removeTab(self.tabWidget.indexOf(self)) try: parts = Config().get('open_tabs').split(',') except Exception: logger.warning('Exception while removing tab from config and reading tab config') parts = [] s = '' for p in parts: if (self.tabName != p): s += ('%s,' % p) s = s[0:(len(s) - 1)] Config().set('open_tabs', str(s))
'Return the name of the tab that will be shown in the menu'
def getMenuName(self):
return self.menuName
'Return the name of the tab that will be shown in the tab'
def getTabName(self):
return self.tabName
'Read and parse log configurations'
def _read_config_files(self):
configsfound = [os.path.basename(f) for f in glob.glob((cfclient.config_path + '/log/[A-Za-z_-]*.json'))] new_dsList = [] for conf in configsfound: try: logger.info('Parsing [%s]', conf) json_data = open((cfclient.config_path + ('/log/%s' % conf))) self.data = json.load(json_data) infoNode = self.data['logconfig']['logblock'] logConf = LogConfig(infoNode['name'], int(infoNode['period'])) for v in self.data['logconfig']['logblock']['variables']: if (v['type'] == 'TOC'): logConf.add_variable(str(v['name']), v['fetch_as']) else: logConf.add_variable('Mem', v['fetch_as'], v['stored_as'], int(v['address'], 16)) new_dsList.append(logConf) json_data.close() except Exception as e: logger.warning('Exception while parsing logconfig file: %s', e) self.dsList = new_dsList
'Callback that is called once Crazyflie is connected'
def _connected(self, link_uri):
self._read_config_files() for d in self.dsList: try: self._cf.log.add_config(d) except KeyError as e: logger.warning(str(e)) except AttributeError as e: logger.warning(str(e))
'Return the log configurations'
def getLogConfigs(self):
return self.dsList
'Save a log configuration to file'
def saveLogConfigFile(self, logconfig):
filename = (((cfclient.config_path + '/log/') + logconfig.name) + '.json') logger.info('Saving config for [%s]', filename) saveConfig = {} logconf = {'logblock': {'variables': []}} logconf['logblock']['name'] = logconfig.name logconf['logblock']['period'] = logconfig.period_in_ms for v in logconfig.variables: newC = {} newC['name'] = v.name newC['stored_as'] = v.stored_as_string newC['fetch_as'] = v.fetch_as_string newC['type'] = 'TOC' logconf['logblock']['variables'].append(newC) saveConfig['logconfig'] = logconf json_data = open(filename, 'w') json_data.write(json.dumps(saveConfig, indent=2)) json_data.close()
'Called when creating new class'
def __call__(cls, *args, **kwargs):
if (cls not in cls._instances): cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
'Initialize'
def __init__(self, receiver, callback, *args):
super(_PullReader, self).__init__(*args) self._receiver = receiver self._cb = callback self.daemon = True self.lock = Lock()
'Called when new data arrives via ZMQ'
def _cmd_callback(self, data):
if (len(self._cf.mem.get_mems(MemoryElement.TYPE_DRIVER_LED)) > 0): logger.info('Updating memory') memory = self._cf.mem.get_mems(MemoryElement.TYPE_DRIVER_LED)[0] for i_led in range(len(data['rgbleds'])): memory.leds[i_led].set(data['rgbleds'][i_led][0], data['rgbleds'][i_led][1], data['rgbleds'][i_led][2]) memory.write_data(self._write_cb)
'Start the timer'
def start(self):
if self._thread: logger.warning('Timer already started, not restarting') return self._thread = _PeriodicTimerThread(self._period, self._callbacks) self._thread.setDaemon(True) self._thread.start()
'Stop the timer'
def stop(self):
if self._thread: self._thread.stop() self._thread = None
'Initialize the writer'
def __init__(self, logblock, connected_ts=None, directory=None):
self._block = logblock self._dir = directory self._connected_ts = connected_ts self._dir = os.path.join(cfclient.config_path, 'logdata', connected_ts.strftime('%Y%m%dT%H-%M-%S')) self._file = None self._header_written = False self._header_values = [] self._filename = None
'Write the header to the file'
def _write_header(self):
if (not self._header_written): s = 'Timestamp' for v in self._block.variables: s += (',' + v.name) self._header_values.append(v.name) s += '\n' self._file.write(s) self._header_written = True
'Callback when new data arrives from the Crazyflie'
def _new_data(self, timestamp, data, logconf):
if self._file: s = ('%d' % timestamp) for col in self._header_values: s += (',' + str(data[col])) s += '\n' self._file.write(s)
'Return True if the file is open and we are using it, otherwise false'
def writing(self):
return (True if self._file else False)
'Stop the logging to file'
def stop(self):
if self._file: self._file.close() self._file = None self._block.data_received_cb.remove_callback(self._new_data) logger.info('Stopped logging of block [%s] to file [%s]', self._block.name, self._filename) self._header_values = []
'Start the logging to file'
def start(self):
try: os.makedirs(self._dir) except OSError: logger.debug('logdata directory already exists') if (not self._file): time_now = datetime.datetime.now() name = '{0}-{1}.csv'.format(self._block.name, time_now.strftime('%Y%m%dT%H-%M-%S')) self._filename = os.path.join(self._dir, name) self._file = open(self._filename, 'w') self._write_header() self._block.data_received_cb.add_callback(self._new_data) logger.info('Started logging of block [%s] to file [%s]', self._block.name, self._filename)
'List all the available connections'
def devices(self):
raise NotImplemented()
'Initialize the reading and open the device with deviceId and set the mapping for axis/buttons using the inputMap'
def open(self, device_id):
return
'Read input from the selected device.'
def read(self, device_id):
raise NotImplemented()
'List all the available connections'
def devices(self):
return [{'id': 0, 'name': 'WII@{}'.format(self.wm)}]
'Initialize the reading and open the device with deviceId and set the mapping for axis/buttons using the inputMap'
def open(self, device_id):
return
'Read input from the selected device.'
def read(self, device_id):
return self.data
'List all the available connections'
def devices(self):
return [{'id': 0, 'name': 'ZMQ@{}'.format(self._bind_addr)}]
'Initialize the reading and open the device with deviceId and set the mapping for axis/buttons using the inputMap'
def open(self, deviceId):
return
'Read input from the selected device.'
def read(self, id):
return self.data
'List all the available devices.'
def devices(self):
dev = [] if self._controller.is_connected: dev.append({'id': 0, 'name': 'Leapmotion'}) return dev
'Initialize the reader'
def __init__(self, dev_name, dev_id, dev_reader):
self.supports_mapping = True self.limit_rp = True self.limit_thrust = True self.limit_yaw = True self.input = None self._reader = dev_reader self.id = dev_id self.name = dev_name self.input_map = None self.input_map_name = '' self.data = None self._prev_pressed = None self.reader_name = dev_reader.name self.data = InputData() self._old_thrust = 0 self._old_raw_thrust = 0 self._prev_thrust = 0 self._last_time = 0 self.thrust_stop_limit = (-90)
'Initialize the reading and open the device with deviceId and set the mapping for axis/buttons using the inputMap'
def open(self):
return
'Read input from the selected device.'
def read(self):
return None
'List all the available devices.'
@staticmethod def devices():
return []
'Get the raw device from a name'
def _get_device_from_name(self, device_name):
for d in readers.devices(): if (d.name == device_name): return d return None
'Set if altitude hold is available or not (depending on HW)'
def set_alt_hold_available(self, available):
self.has_pressure_sensor = available
'List all available and approved input devices. This function will filter available devices by using the blacklist configuration and only return approved devices.'
def available_devices(self):
devs = readers.devices() devs += interfaces.devices() approved_devs = [] for dev in devs: if ((not self._dev_blacklist) or (self._dev_blacklist and (not self._dev_blacklist.match(dev.name)))): dev.input = self approved_devs.append(dev) return approved_devs
'Enable raw reading of the input device with id deviceId. This is used to get raw values for setting up of input devices. Values are read without using a mapping.'
def enableRawReading(self, device_name):
if self._input_device: self._input_device.close() self._input_device = None for d in readers.devices(): if (d.name == device_name): self._input_device = d self._input_device.input_map = None self._input_device.open()
'Return the saved mapping for a given device'
def get_saved_device_mapping(self, device_name):
config = None device_config_mapping = Config().get('device_config_mapping') if (device_name in list(device_config_mapping.keys())): config = device_config_mapping[device_name] logging.debug('For [{}] we recommend [{}]'.format(device_name, config)) return config
'Disable raw reading of input device.'
def stop_raw_reading(self):
if self._input_device: self._input_device.close() self._input_device = None
'Read raw values from the input device.'
def read_raw_values(self):
[axes, buttons, mapped_values] = self._input_device.read(include_raw=True) dict_axes = {} dict_buttons = {} for (i, a) in enumerate(axes): dict_axes[i] = a for (i, b) in enumerate(buttons): dict_buttons[i] = b return [dict_axes, dict_buttons, mapped_values]
'Set an input device map'
def set_raw_input_map(self, input_map):
if self._input_device: self._input_device.input_map = input_map
'Load and set an input device map with the given name'
def set_input_map(self, device_name, input_map_name):
settings = ConfigManager().get_settings(input_map_name) if settings: self.springy_throttle = settings['springythrottle'] self._input_map = ConfigManager().get_config(input_map_name) self._get_device_from_name(device_name).input_map = self._input_map self._get_device_from_name(device_name).input_map_name = input_map_name Config().get('device_config_mapping')[device_name] = input_map_name
'Start reading input from the device with name device_name using config config_name. Returns True if device supports mapping, otherwise False'
def start_input(self, device_name, role='Device', config_name=None):
try: device = self._get_device_from_name(device_name) self._selected_mux.add_device(device, role) self.limiting_updated.call(device.limit_rp, device.limit_yaw, device.limit_thrust) self._read_timer.start() return device.supports_mapping except Exception: self.device_error.call(('Error while opening/initializing input device\n\n%s' % traceback.format_exc())) if (not self._input_device): self.device_error.call('Could not find device {}'.format(device_name)) return False
'Stop reading from the input device.'
def pause_input(self, device_name=None):
self._read_timer.stop() self._selected_mux.pause()
'Read input data from the selected device'
def read_input(self):
try: data = self._selected_mux.read() if data: if data.toggled.assistedControl: if ((self._assisted_control == JoystickReader.ASSISTED_CONTROL_POSHOLD) or (self._assisted_control == JoystickReader.ASSISTED_CONTROL_HOVER)): if (data.assistedControl and (self._assisted_control != JoystickReader.ASSISTED_CONTROL_HOVER)): for d in self._selected_mux.devices(): d.limit_thrust = False d.limit_rp = False elif data.assistedControl: for d in self._selected_mux.devices(): d.limit_thrust = True d.limit_rp = False else: for d in self._selected_mux.devices(): d.limit_thrust = True d.limit_rp = True if (self._assisted_control == JoystickReader.ASSISTED_CONTROL_ALTHOLD): self.assisted_control_updated.call(data.assistedControl) if ((self._assisted_control == JoystickReader.ASSISTED_CONTROL_HEIGHTHOLD) or (self._assisted_control == JoystickReader.ASSISTED_CONTROL_HOVER)): try: self.assisted_control_updated.call(data.assistedControl) if (not data.assistedControl): self.heighthold_input_updated.call(0, 0, 0, INITAL_TAGET_HEIGHT) self.hover_input_updated.call(0, 0, 0, INITAL_TAGET_HEIGHT) except Exception as e: logger.warning('Exception while doing callback from input-device for assited control: {}'.format(e)) if data.toggled.estop: try: self.emergency_stop_updated.call(data.estop) except Exception as e: logger.warning('Exception while doing callback frominput-device for estop: {}'.format(e)) if data.toggled.alt1: try: self.alt1_updated.call(data.alt1) except Exception as e: logger.warning('Exception while doing callback frominput-device for alt1: {}'.format(e)) if data.toggled.alt2: try: self.alt2_updated.call(data.alt2) except Exception as e: logger.warning('Exception while doing callback frominput-device for alt2: {}'.format(e)) if ((not data.assistedControl) or ((self._assisted_control != JoystickReader.ASSISTED_CONTROL_HEIGHTHOLD) and (self._assisted_control != JoystickReader.ASSISTED_CONTROL_HOVER))): self._target_height = INITAL_TAGET_HEIGHT if ((self._assisted_control == JoystickReader.ASSISTED_CONTROL_POSHOLD) and data.assistedControl): vx = data.roll vy = data.pitch vz = data.thrust yawrate = data.yaw self.assisted_input_updated.call(vy, (- vx), vz, yawrate) elif ((self._assisted_control == JoystickReader.ASSISTED_CONTROL_HOVER) and data.assistedControl): vx = data.roll vy = data.pitch vz = ((data.thrust - 32767) / 32767.0) self._target_height += (vz * INPUT_READ_PERIOD) if (self._target_height > MAX_TARGET_HEIGHT): self._target_height = MAX_TARGET_HEIGHT if (self._target_height < MIN_HOVER_HEIGHT): self._target_height = MIN_HOVER_HEIGHT yawrate = data.yaw self.hover_input_updated.call(vy, (- vx), yawrate, self._target_height) else: if (data.toggled.pitchNeg and data.pitchNeg): self.trim_pitch -= 1 if (data.toggled.pitchPos and data.pitchPos): self.trim_pitch += 1 if (data.toggled.rollNeg and data.rollNeg): self.trim_roll -= 1 if (data.toggled.rollPos and data.rollPos): self.trim_roll += 1 if (data.toggled.pitchNeg or data.toggled.pitchPos or data.toggled.rollNeg or data.toggled.rollPos): self.rp_trim_updated.call(self.trim_roll, self.trim_pitch) if ((self._assisted_control == JoystickReader.ASSISTED_CONTROL_HEIGHTHOLD) and data.assistedControl): roll = (data.roll + self.trim_roll) pitch = (data.pitch + self.trim_pitch) yawrate = data.yaw vz = ((data.thrust - 32767) / 32767.0) self._target_height += (vz * INPUT_READ_PERIOD) if (self._target_height > MAX_TARGET_HEIGHT): self._target_height = MAX_TARGET_HEIGHT if (self._target_height < MIN_TARGET_HEIGHT): self._target_height = MIN_TARGET_HEIGHT self.heighthold_input_updated.call(roll, (- pitch), yawrate, self._target_height) else: if (not data.assistedControl): data.thrust = JoystickReader.p2t(data.thrust) if (data.thrust < 0): data.thrust = 0 if (data.thrust > 65535): data.thrust = 65535 self.input_updated.call((data.roll + self.trim_roll), (data.pitch + self.trim_pitch), data.yaw, data.thrust) else: self.input_updated.call(0, 0, 0, 0) except Exception: logger.warning('Exception while reading inputdevice: %s', traceback.format_exc()) self.device_error.call(('Error reading from input device\n\n%s' % traceback.format_exc())) self.input_updated.call(0, 0, 0, 0) self._read_timer.stop()
'Convert a percentage to raw thrust'
@staticmethod def p2t(percentage):
return int((MAX_THRUST * (percentage / 100.0)))
'Close down the MUX and close all it\'s devices'
def close(self):
for d in [key for key in list(self._devs.keys()) if self._devs[key]]: self._devs[d].close() self._devs[d] = None
'Initialize the reading and open the device with deviceId and set the mapping for axis/buttons using the inputMap'
def open(self, device_id):
self._event_dispatcher.enable = True self._js[device_id].open()
'Close the device'
def close(self, device_id):
self._event_dispatcher.enable = False self._js[device_id].close()
'Read input from the selected device.'
def read(self, device_id):
return self._js[device_id].read()
'List all the available devices.'
def devices(self):
logger.info('Looking for devices') names = [] if (len(self._devices) == 0): nbrOfInputs = sdl2.joystick.SDL_NumJoysticks() logger.info('Found {} devices'.format(nbrOfInputs)) for sdl_index in range(0, nbrOfInputs): j = sdl2.joystick.SDL_JoystickOpen(sdl_index) name = sdl2.joystick.SDL_JoystickName(j).decode('UTF-8') if (names.count(name) > 0): name = '{0} #{1}'.format(name, (names.count(name) + 1)) sdl_id = sdl2.joystick.SDL_JoystickInstanceID(j) self._devices.append({'id': sdl_id, 'name': name}) self._js[sdl_id] = _JS(sdl_index, sdl_id, name) names.append(name) sdl2.joystick.SDL_JoystickClose(j) return self._devices
'Open the joystick device'
def close(self):
if (not self._f): return logger.info('Closed {} ({})'.format(self.name, self.num)) self._f.close() self._f = None
'Read the buttons and axes initial values from the js device'
def __initvalues(self):
for _ in range((len(self.axes) + len(self.buttons))): data = self._f.read(struct.calcsize(JS_EVENT_FMT)) jsdata = struct.unpack(JS_EVENT_FMT, data) self.__updatestate(jsdata)
'Update the internal absolute state of buttons and axes'
def __updatestate(self, jsdata):
if ((jsdata[JE_TYPE] & JS_EVENT_AXIS) != 0): self.axes[jsdata[JE_NUMBER]] = (jsdata[JE_VALUE] / 32768.0) elif ((jsdata[JE_TYPE] & JS_EVENT_BUTTON) != 0): self.buttons[jsdata[JE_NUMBER]] = jsdata[JE_VALUE]
'Decode a jsdev event into a dict'
def __decode_event(self, jsdata):
if ((jsdata[JE_TYPE] & JS_EVENT_AXIS) != 0): return JEvent(evt_type=TYPE_AXIS, number=jsdata[JE_NUMBER], value=(jsdata[JE_VALUE] / 32768.0)) if ((jsdata[JE_TYPE] & JS_EVENT_BUTTON) != 0): return JEvent(evt_type=TYPE_BUTTON, number=jsdata[JE_NUMBER], value=(jsdata[JE_VALUE] / 32768.0))
'Consume all the events queued up in the JS device'
def _read_all_events(self):
try: while True: data = self._f.read(struct.calcsize(JS_EVENT_FMT)) jsdata = struct.unpack(JS_EVENT_FMT, data) self.__updatestate(jsdata) except IOError as e: if (e.errno != 11): logger.info(str(e)) self._f.close() self._f = None raise IOError('Device has been disconnected') except TypeError: pass except ValueError: pass