def test_unknown_resource():
    set_ament_prefix_path(['prefix1'])
    exists = has_resource('resource_type4', 'bar')
    assert not exists, 'Resource should not exist'

    with pytest.raises(LookupError):
        get_resource('resource_type4', 'bar')
示例#2
0
def test_unknown_resource():
    set_ament_prefix_path(['prefix1'])
    exists = has_resource('resource_type4', 'bar')
    assert not exists, 'Resource should not exist'

    try:
        get_resource('resource_type4', 'bar')
        assert False, 'get_resource() failed to raise exception'
    except LookupError:
        pass
    except Exception as e:
        assert False, 'get_resource() raised wrong exception: ' + type(e)
def test_unknown_resource():
    set_ament_prefix_path(['prefix1'])
    exists = has_resource('resource_type4', 'bar')
    assert not exists, 'Resource should not exist'

    try:
        get_resource('resource_type4', 'bar')
        assert False, 'get_resource() failed to raise exception'
    except LookupError:
        pass
    except Exception as e:
        assert False, 'get_resource() raised wrong exception: ' + type(e)
示例#4
0
def get_ros2_services():
    pkgs = []
    srvs = []
    rules = []
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        pkgs.append(package_name)
        resource, _ = ament_index_python.get_resource(resource_type,
                                                      package_name)
        interfaces = resource.splitlines()
        service_names = [i[:-4] for i in interfaces if i.endswith('.srv')]
        for service_name in service_names:
            srvs.append(Message(package_name, service_name, prefix_path))
        # check package manifest for mapping rules
        package_path = os.path.join(prefix_path, 'share', package_name)
        pkg = parse_package(package_path)
        for export in pkg.exports:
            if export.tagname != 'ros1_bridge':
                continue
            if 'mapping_rules' not in export.attributes:
                continue
            rule_file = os.path.join(package_path,
                                     export.attributes['mapping_rules'])
            with open(rule_file, 'r') as h:
                for data in yaml.load(h):
                    if all(n not in data for n in ('ros1_message_name',
                                                   'ros2_message_name')):
                        try:
                            rules.append(ServiceMappingRule(
                                data, package_name))
                        except Exception as e:
                            print('%s' % str(e), file=sys.stderr)
    return pkgs, srvs, rules
示例#5
0
def get_ros2_services():
    pkgs = []
    srvs = []
    rules = []
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        pkgs.append(package_name)
        resource, _ = ament_index_python.get_resource(resource_type, package_name)
        interfaces = resource.splitlines()
        service_names = [i[:-4] for i in interfaces if i.endswith('.srv')]
        for service_name in service_names:
            srvs.append(Message(package_name, service_name, prefix_path))
        # check package manifest for mapping rules
        package_path = os.path.join(prefix_path, 'share', package_name)
        pkg = parse_package(package_path)
        for export in pkg.exports:
            if export.tagname != 'ros1_bridge':
                continue
            if 'mapping_rules' not in export.attributes:
                continue
            rule_file = os.path.join(package_path, export.attributes['mapping_rules'])
            with open(rule_file, 'r') as h:
                for data in yaml.load(h):
                    if all(n not in data for n in ('ros1_message_name', 'ros2_message_name')):
                        try:
                            rules.append(ServiceMappingRule(data, package_name))
                        except Exception as e:
                            print('%s' % str(e), file=sys.stderr)
    return pkgs, srvs, rules
示例#6
0
    def __init__(self, min_val, max_val):
        super(DoubleEditor, self).__init__()

        # Preconditions
        assert min_val < max_val

        # Cache values
        self._min_val = min_val
        self._max_val = max_val

        # Load editor UI
        _, package_path = get_resource('packages',
                                       'rqt_joint_trajectory_controller')
        ui_file = os.path.join(package_path, 'share',
                               'rqt_joint_trajectory_controller', 'resource',
                               'double_editor.ui')
        loadUi(ui_file, self)

        # Setup widget ranges and slider scale factor
        self.slider.setRange(0, 100)
        self.slider.setSingleStep(1)
        self._scale = (max_val - min_val) / \
                      (self.slider.maximum() - self.slider.minimum())
        self.spin_box.setRange(min_val, max_val)
        self.spin_box.setSingleStep(self._scale)

        # Couple slider and spin box together
        self.slider.valueChanged.connect(self._on_slider_changed)
        self.spin_box.valueChanged.connect(self._on_spinbox_changed)

        # Ensure initial sync of slider and spin box
        self._on_spinbox_changed()
示例#7
0
def import_type_support(pkg_name, rmw_implementation):
    """
    Import the appropriate type support module of a package for a given rmw implementation.

    This function will determine the correct type support module to import based on the rmw
    implementation given.
    This module will provide the c type support of the given rmw implementation for the rosidl
    files in the specified package, such that the ROS message structures in the package can be
    converted to and from message structures used by the rmw implementation.

    :param pkg_name str: name of the package
    :param rmw_implementation str: name of the rmw implementation
    :returns: the type support Python module for the specified package and rmw implementation pair
    """
    if not ament_index_python.has_resource('rmw_typesupport_c',
                                           rmw_implementation):
        raise UnsupportedTypeSupport(rmw_implementation)

    type_support_name, _ = ament_index_python.get_resource(
        'rmw_typesupport_c', rmw_implementation)
    import_package = '{pkg_name}'.format(pkg_name=pkg_name, )
    module_name = '.{pkg_name}_s__{type_support_name}'.format(
        pkg_name=pkg_name,
        type_support_name=type_support_name,
    )
    return importlib.import_module(module_name, package=import_package)
示例#8
0
def import_type_support(pkg_name, rmw_implementation):
    """
    Import the appropriate type support module of a package for a given rmw implementation.

    This function will determine the correct type support module to import based on the rmw
    implementation given.
    This module will provide the c type support of the given rmw implementation for the rosidl
    files in the specified package, such that the ROS message structures in the package can be
    converted to and from message structures used by the rmw implementation.

    :param pkg_name str: name of the package
    :param rmw_implementation str: name of the rmw implementation
    :returns: the type support Python module for the specified package and rmw implementation pair
    """
    if not ament_index_python.has_resource('rmw_typesupport_c', rmw_implementation):
        raise UnsupportedTypeSupport(rmw_implementation)

    type_support_name = ament_index_python.get_resource('rmw_typesupport_c', rmw_implementation)
    import_package = '{pkg_name}'.format(
        pkg_name=pkg_name,
    )
    module_name = '.{pkg_name}_s__{type_support_name}'.format(
        pkg_name=pkg_name,
        type_support_name=type_support_name,
    )
    return importlib.import_module(module_name, package=import_package)
示例#9
0
def test_resource():
    set_ament_prefix_path(['prefix1'])
    exists = has_resource('resource_type4', 'foo')
    assert exists, 'Resource should exist'

    resource = get_resource('resource_type4', 'foo')
    assert resource == 'foo', 'Expected different content'
示例#10
0
文件: list.py 项目: utiasASRL/rosbag2
    def main(self, *, args):  # noqa: D102
        # the following is the resource index which is created when installing a pluginlib xml file
        if args.plugin_type == 'storage':
            pluginlib_resource_index = 'rosbag2_storage__pluginlib__plugin'
        else:
            pluginlib_resource_index = 'rosbag2_cpp__pluginlib__plugin'

        resources = get_resources(pluginlib_resource_index)
        if args.verbose:
            print('available %s plugins are:' % args.plugin_type)
        for resource in resources:
            plugin_xml_file_paths, base_folder = get_resource(
                pluginlib_resource_index, resource)
            for file_path in list(
                    filter(None, plugin_xml_file_paths.split('\n'))):
                abs_path = os.path.join(base_folder, file_path)
                if not os.path.exists(abs_path):
                    return 'path does not exist: %s' % abs_path

                xmldoc = minidom.parse(abs_path)
                class_item = xmldoc.getElementsByTagName('class')[0]
                class_name = class_item.attributes['name']
                type_name = class_item.attributes['type']
                base_class_name = class_item.attributes['base_class_type']
                description = xmldoc.getElementsByTagName('description')[0]

                print('%s%s' %
                      (('name: ' if args.verbose else ''), class_name.value))
                if args.verbose:
                    print('\t%s' % description.childNodes[0].data)
                    print('\ttype: %s' % type_name.value)
                    print('\tbase_class: %s' % base_class_name.value)
示例#11
0
def import_type_support(pkg_name, subfolder, rosidl_name, rmw_implementation):
    """Import the appropriate type support module for a given rosidl and rmw implementation.

    This function will determine the correct type support package to import
    from based on the rmw implementation given.
    For example, giving `opensplice_static` as the rmw implementation would
    result in the `rosidl_typesupport_opensplice_c` type support package being
    used when importing.

    :param pkg_name str: name of the package which contains the rosidl
    :param subfolder str: name of the rosidl containing folder, e.g. `msg`, `srv`, etc.
    :param rosidl_name str: name of the rosidl
    :param rmw_implementation str: name of the rmw implementation
    :returns: the type support Python module for this specific rosidl and rmw implementation pair
    """
    if not ament_index_python.has_resource('rmw_typesupport_c', rmw_implementation):
        raise UnsupportedTypeSupport(rmw_implementation)

    type_support_name = ament_index_python.get_resource('rmw_typesupport_c', rmw_implementation)
    import_package = '{pkg_name}'.format(
        pkg_name=pkg_name,
    )
    module_name = '.{pkg_name}_s__{type_support_name}'.format(
        pkg_name=pkg_name,
        type_support_name=type_support_name,
    )
    return importlib.import_module(module_name, package=import_package)
示例#12
0
def get_rmw_output_filter(rmw_implementation):
    prefix_with_resource = ament_index_python.has_resource(
        'rmw_output_filter', rmw_implementation)
    if not prefix_with_resource:
        return []

    rmw_output_filter = ament_index_python.get_resource('rmw_output_filter', rmw_implementation)
    additional_filtered_prefixes = [
        str.encode(l) for l in rmw_output_filter.splitlines()]
    return additional_filtered_prefixes
示例#13
0
def get_message_types(package_name):
    if not has_resource('packages', package_name):
        raise LookupError('Unknown package name')
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    # TODO(dirk-thomas) this logic should come from a rosidl related package
    return [n[:-4] for n in interface_names if n.endswith('.msg')]
示例#14
0
def get_interface(package_name):
    if not has_resource('packages', package_name):
        raise LookupError('Unknown package {}'.format(package_name))
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    return list(
        sorted({n.rsplit('.', 1)[0]
                for n in interface_names if '_' not in n}))
示例#15
0
def get_package_component_types(*, package_name=None):
    """
    Get all component types registered in the ament index for the given package.

    :param package_name: whose component types are to be retrieved.
    :return: a list of component type names.
    """
    if not has_resource(COMPONENTS_RESOURCE_TYPE, package_name):
        return []
    component_registry, _ = get_resource(COMPONENTS_RESOURCE_TYPE, package_name)
    return [line.split(';')[0] for line in component_registry.splitlines()]
示例#16
0
def _get_rosidl_class_helper(message_type, mode, logger=None):  # noqa: C901
    """
    A helper function for common logic to be used by get_message_class and get_service_class.

    :param message_type: name of the message or service class in the form
      'package_name/MessageName' or 'package_name/msg/MessageName'
    :type message_type: str
    :param mode: one of MSG_MODE, SRV_MODE or ACTION_MODE
    :type mode: str
    :param logger: The logger to be used for warnings and info
    :type logger: either rclpy.impl.rcutils_logger.RcutilsLogger or None

    :returns: The message or service class or None
    """
    if logger is None:
        logger = logging.get_logger('_get_message_service_class_helper')

    if mode not in ROSIDL_FILTERS.keys():
        logger.warn('invalid mode {}'.format(mode))
        return None

    message_info = message_type.split('/')
    if len(message_info) not in (2, 3):
        logger.error('Malformed message_type: {}'.format(message_type))
        return None
    if len(message_info) == 3 and message_info[1] != mode:
        logger.error('Malformed {} message_type: {}'.format(mode, message_type))
        return None

    package = message_info[0]
    base_type = message_info[-1]

    try:
        _, resource_path = get_resource('rosidl_interfaces', package)
    except LookupError:
        return None
    python_pkg = None
    class_val = None

    try:
        # import the package
        python_pkg = importlib.import_module('%s.%s' % (package, mode))
    except ImportError:
        logger.info('Failed to import class: {} as {}.{}'.format(message_type, package, mode))
        return None

    try:
        class_val = getattr(python_pkg, base_type)
        return class_val

    except AttributeError:
        logger.info('Failed to load class: {}'.format(message_type))
        return None
示例#17
0
    def __init__(self, context):
        super(Ros2KnowledgeGraph, self).__init__(context)

        self._node = context.node
        self._logger = self._node.get_logger().get_child(
            'ros2_knowledge_graph_viewer.ros2_knowledge_graph.Ros2KnowledgeGraph'
        )
        self.setObjectName('Ros2KnowledgeGraph')

        self._ros2_knowledge_graph = Ros2KnowledgeGraphImpl()
        self._current_dotcode = None

        self._widget = QWidget()

        self.dotcode_factory = PydotFactory()
        self.dotcode_generator = Ros2KnowledgeGraphDotcodeGenerator()
        self.dot_to_qt = DotToQtGenerator()

        _, package_path = get_resource('packages',
                                       'ros2_knowledge_graph_viewer')
        ui_file = os.path.join(package_path, 'share',
                               'ros2_knowledge_graph_viewer', 'resource',
                               'Ros2KnowledgeGraph.ui')
        loadUi(ui_file, self._widget,
               {'InteractiveGraphicsView': InteractiveGraphicsView})
        self._widget.setObjectName('Ros2KnowledgeGraphUi')
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() +
                                        (' (%d)' % context.serial_number()))

        self._scene = QGraphicsScene()
        self._scene.setBackgroundBrush(Qt.white)
        self._widget.graphics_view.setScene(self._scene)

        self._widget.save_as_svg_push_button.setIcon(
            QIcon.fromTheme('document-save-as'))
        self._widget.save_as_svg_push_button.pressed.connect(self._save_svg)
        self._widget.save_as_image_push_button.setIcon(
            QIcon.fromTheme('image'))
        self._widget.save_as_image_push_button.pressed.connect(
            self._save_image)

        self._update_ros2_knowledge_graph()
        self._deferred_fit_in_view.connect(self._fit_in_view,
                                           Qt.QueuedConnection)
        self._deferred_fit_in_view.emit()

        context.add_widget(self._widget)

        self._updateTimer = QtCore.QTimer()
        self._updateTimer.timeout.connect(self.do_update)
        self._updateTimer.start(10)
示例#18
0
    def __init__(self, text):
        """
        :param text: value to set the text of the widget to, ''str''
        """
        super(TextBrowseDialog, self).__init__()

        _, package_path = get_resource('packages', 'rqt_console')
        ui_file = os.path.join(package_path, 'share', 'rqt_console',
                               'resource', 'text_browse_dialog.ui')

        self.setFont(QFont('Mono'))

        loadUi(ui_file, self)
        self.text_browser.setText(text)
示例#19
0
def _get_interfaces(package_names: Iterable[str] = []) -> Dict[str, List[str]]:
    interfaces = {}
    if len(package_names) == 0:
        package_names = get_resources('rosidl_interfaces')

    for package_name in package_names:
        if not has_resource('packages', package_name):
            raise LookupError(f"Unknown package '{package_name}'")
        try:
            content, _ = get_resource('rosidl_interfaces', package_name)
        except LookupError:
            continue
        interfaces[package_name] = content.splitlines()
    return interfaces
示例#20
0
def get_service_types(package_name):
    if not has_resource('packages', package_name):
        raise LookupError('Unknown package name')
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    # TODO(dirk-thomas) this logic should come from a rosidl related package
    # Only return services in srv folder
    return [
        n[4:-4] for n in interface_names
        if n.startswith('srv/') and n.endswith('.srv')
    ]
示例#21
0
def parse_package(pkg: str) -> Sequence[MessageMetadata]:
    rosidl_interfaces = ament_index_python.get_resource(
        "rosidl_interfaces", pkg)[0].split("\n")
    message_meta = []
    for interface in rosidl_interfaces:
        if interface.endswith(".msg"):
            file = f"{ament_index_python.get_package_share_directory(pkg)}/{interface}"
            message_meta.append(
                MessageMetadata(
                    get_import_prefix(pkg, interface),
                    parse_message_file(pkg, file),
                ))

    return message_meta
示例#22
0
def get_action_types(package_name):
    if not has_resource('packages', package_name):
        raise LookupError('Unknown package name')
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    # TODO(jacobperron) this logic should come from a rosidl related package
    # Only return actions in action folder
    return list(sorted({
        n[7:-7]
        for n in interface_names
        if n.startswith('action/') and n[-7:] in ('.idl', '.action')}))
示例#23
0
def get_message_types(package_name):
    if not has_resource('packages', package_name):
        raise LookupError('Unknown package name')
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    # TODO(dirk-thomas) this logic should come from a rosidl related package
    # Only return messages in msg folder
    return {
        n[4:-4]
        for n in interface_names
        if n.startswith('msg/') and n[-4:] in ('.idl', '.msg')
    }
示例#24
0
文件: __init__.py 项目: kyrofa/launch
def get_rmw_output_filter(rmw_implementation, filter_type):
    supported_filter_types = ['prefixes', 'patterns']
    if filter_type not in supported_filter_types:
        raise TypeError(
            'Unsupported filter_type "{0}". Supported types: {1}'.format(
                filter_type, supported_filter_types))
    resource_name = 'rmw_output_' + filter_type
    prefix_with_resource = ament_index_python.has_resource(
        resource_name, rmw_implementation)
    if not prefix_with_resource:
        return []

    # Treat each line of the resource as an independent filter.
    rmw_output_filter, _ = ament_index_python.get_resource(
        resource_name, rmw_implementation)
    return [str.encode(l) for l in rmw_output_filter.splitlines()]
示例#25
0
def get_rosidl_types_of_type(package_name, rosidl_type):
    """
    Retrieve a list of rosidl interfaces of a specific type provided by a ROS2 package.

    :param package_name: ROS2 package name
    :type package_name: str
    :param rosidl_type: rosidl type to filter by, one of ['msg', 'srv', 'action']
    :type rosidl_type: str
    :returns: a list of the filtered rosidl types
    """
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    return _filter_rosidl_types(rosidl_type, interface_names)
示例#26
0
    def main(self, *, args):  # noqa: D102
        # the following is the resource index which is created when installing a pluginlib xml file
        if args.plugin_type == 'storage':
            pluginlib_resource_index = 'rosbag2_storage__pluginlib__plugin'
        elif args.plugin_type == 'compressor' or args.plugin_type == 'decompressor':
            pluginlib_resource_index = 'rosbag2_compression__pluginlib__plugin'
        else:
            pluginlib_resource_index = 'rosbag2_cpp__pluginlib__plugin'

        resources = get_resources(pluginlib_resource_index)
        if args.verbose:
            print('available %s plugins are:' % args.plugin_type)
        for resource in resources:
            plugin_xml_file_paths, base_folder = get_resource(
                pluginlib_resource_index, resource)
            for file_path in list(
                    filter(None, plugin_xml_file_paths.split('\n'))):
                abs_path = os.path.join(base_folder, file_path)
                if not os.path.exists(abs_path):
                    return 'path does not exist: %s' % abs_path

                xmldoc = minidom.parse(abs_path)
                for class_item in xmldoc.getElementsByTagName('class'):
                    class_name = class_item.attributes['name']
                    type_name = class_item.attributes['type']
                    base_class_name = class_item.attributes['base_class_type']
                    description = class_item.getElementsByTagName(
                        'description')[0]

                    # Compression and decompression plugins share the same resource index
                    # so they must be filtered using their base class
                    if args.plugin_type == 'compressor' and \
                            base_class_name.value != \
                            'rosbag2_compression::BaseCompressorInterface':
                        continue
                    elif args.plugin_type == 'decompressor' and \
                            base_class_name.value != \
                            'rosbag2_compression::BaseDecompressorInterface':
                        continue

                    print(
                        '%s%s' %
                        (('name: ' if args.verbose else ''), class_name.value))
                    if args.verbose:
                        print('\t%s' % description.childNodes[0].data)
                        print('\ttype: %s' % type_name.value)
                        print('\tbase_class: %s' % base_class_name.value)
示例#27
0
    def __init__(self):
        super(ParameditWidget, self).__init__()

        _, package_path = get_resource('packages', 'rqt_reconfigure')
        ui_file = os.path.join(package_path, 'share', 'rqt_reconfigure',
                               'resource', 'paramedit_pane.ui')
        loadUi(ui_file, self, {'ParameditWidget': ParameditWidget})

        self._param_client_widgets = OrderedDict()

        # Adding the list of Items
        self._vlayout = QVBoxLayout(self.scrollarea_holder_widget)

        # causes error
        # self._set_index_widgets(self.listview, paramitems_dict)

        self.destroyed.connect(self.close)
示例#28
0
def get_ros2_messages():
    pkgs = []
    msgs = []
    rules = []
    # get messages from packages
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        pkgs.append(package_name)
        resource, _ = ament_index_python.get_resource(resource_type,
                                                      package_name)
        interfaces = resource.splitlines()
        message_names = {
            i[4:-4]
            for i in interfaces
            if i.startswith('msg/') and i[-4:] in ('.idl', '.msg')
        }

        for message_name in sorted(message_names):
            msgs.append(Message(package_name, message_name, prefix_path))
        # check package manifest for mapping rules
        package_path = os.path.join(prefix_path, 'share', package_name)
        pkg = parse_package(package_path)
        for export in pkg.exports:
            if export.tagname != 'ros1_bridge':
                continue
            if 'mapping_rules' not in export.attributes:
                continue
            rule_file = os.path.join(package_path,
                                     export.attributes['mapping_rules'])
            with open(rule_file, 'r') as h:
                content = yaml.safe_load(h)
            if not isinstance(content, list):
                print(
                    "The content of the mapping rules in '%s' is not a list" %
                    rule_file,
                    file=sys.stderr)
                continue
            for data in content:
                if all(n not in data
                       for n in ('ros1_service_name', 'ros2_service_name')):
                    try:
                        rules.append(MessageMappingRule(data, package_name))
                    except Exception as e:  # noqa: B902
                        print('%s' % str(e), file=sys.stderr)
    return pkgs, msgs, rules
示例#29
0
def get_rosidl_types(package_name):
    """
    Retrieve a dictionary of lists for all rosidl interface types provided by a ROS2 package.

    :param package_name: ROS2 package name
    :type package_name: str
    :returns: a dictionary mapping rosidl type to a list {'msg': [...], 'srv': ... }
    """
    rosidl_types = {}
    try:
        content, _ = get_resource('rosidl_interfaces', package_name)
    except LookupError:
        return []
    interface_names = content.splitlines()
    for filter_type in ROSIDL_FILTERS.keys():
        rosidl_types[filter_type] = _filter_rosidl_types(filter_type, interface_names)
    return rosidl_types
示例#30
0
    def __init__(self, context):
        """Initialize the plugin."""
        super().__init__(context)
        self._context = context
        self.subscription = None
        self.graph = None
        self.filename = None

        # only declare the parameter if running standalone or it's the first instance
        if self._context.serial_number() <= 1:
            self._context.node.declare_parameter("title", "Dot Graph Viewer")
        self.title = self._context.node.get_parameter("title").value

        supported_formats = QImageWriter.supportedImageFormats()
        self.image_filter = (
            ";;".join([f"*.{fo.data().decode()}"
                       for fo in supported_formats]) + ";;*.svg")

        self._widget = QWidget()
        self.setObjectName(self.title)

        _, package_path = get_resource("packages", "rqt_dotgraph")
        ui_file = os.path.join(package_path, "share", "rqt_dotgraph",
                               "resource", "rqt_dotgraph.ui")
        loadUi(ui_file, self._widget, {"DotWidget": DotWidget})
        self._widget.setObjectName(self.title + "UI")

        self._widget.refreshButton.clicked[bool].connect(
            self.update_subscriber)
        self._widget.loadButton.clicked[bool].connect(self.load_graph)
        self._widget.saveButton.clicked[bool].connect(self.save_graph)

        title = self.title
        if self._context.serial_number() > 1:
            title += f" ({self._context.serial_number()})"

        self._context.add_widget(self._widget)

        self._widget.setWindowTitle(title)
        # only set main window title if running standalone
        if self._context.serial_number() < 1:
            self._widget.window().setWindowTitle(self.title)

        self.setup_subscription("dot_graph")
示例#31
0
def get_ros2_messages():
    msgs = []
    pkgs = []
    # get messages from packages
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        pkgs.append(package_name)
        resource, _ = ament_index_python.get_resource(resource_type,
                                                      package_name)
        interfaces = resource.splitlines()
        message_names = {
            i[4:-4]
            for i in interfaces
            if i.startswith('msg/') and i[-4:] in ('.idl', '.msg')
        }
        for message_name in sorted(message_names):
            msgs.append(Message(package_name, message_name, prefix_path))
    return pkgs, msgs
示例#32
0
    def _get_message_types(self, package_name):
        """
        Implementation taken from ros2cli.

        https://github.com/ros2/ros2cli/blob/master/ros2msg/ros2msg/api/__init__.py
        """
        if not has_resource('packages', package_name):
            raise LookupError('Unknown package name "{}"'.format(package_name))
        try:
            content, _ = get_resource('rosidl_interfaces', package_name)
        except LookupError:
            return []
        interface_names = content.splitlines()
        # TODO(dirk-thomas) this logic should come from a rosidl related package
        # Only return messages in msg folder
        return [
            n[4:-4] for n in interface_names
            if n.startswith('msg/') and n.endswith('.msg')
        ]
示例#33
0
def get_ros2_messages():
    pkgs = []
    msgs = []
    rules = []
    # get messages from packages
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        pkgs.append(package_name)
        resource, _ = ament_index_python.get_resource(resource_type, package_name)
        interfaces = resource.splitlines()
        message_names = {
            i[4:-4]
            for i in interfaces
            if i.startswith('msg/') and i[-4:] in ('.idl', '.msg')}

        for message_name in sorted(message_names):
            msgs.append(Message(package_name, message_name, prefix_path))
        # check package manifest for mapping rules
        package_path = os.path.join(prefix_path, 'share', package_name)
        pkg = parse_package(package_path)
        for export in pkg.exports:
            if export.tagname != 'ros1_bridge':
                continue
            if 'mapping_rules' not in export.attributes:
                continue
            rule_file = os.path.join(package_path, export.attributes['mapping_rules'])
            with open(rule_file, 'r') as h:
                content = yaml.safe_load(h)
            if not isinstance(content, list):
                print(
                    "The content of the mapping rules in '%s' is not a list" % rule_file,
                    file=sys.stderr)
                continue
            for data in content:
                if all(n not in data for n in ('ros1_service_name', 'ros2_service_name')):
                    try:
                        rules.append(MessageMappingRule(data, package_name))
                    except Exception as e:
                        print('%s' % str(e), file=sys.stderr)
    return pkgs, msgs, rules
示例#34
0
def get_ros2_messages():
    msgs = []
    rules = []
    # get messages from packages
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        resource = ament_index_python.get_resource(resource_type, package_name)
        interfaces = resource.splitlines()
        message_names = [i[:-4] for i in interfaces if i.endswith('.msg')]
        for message_name in message_names:
            msgs.append(Message(package_name, message_name, prefix_path))
        # check package manifest for mapping rules
        package_path = os.path.join(prefix_path, 'share', package_name)
        pkg = parse_package(package_path)
        for export in pkg.exports:
            if export.tagname != 'ros1_bridge':
                continue
            if 'mapping_rules' not in export.attributes:
                continue
            rule_file = os.path.join(package_path, export.attributes['mapping_rules'])
            rules += read_mapping_rules(rule_file, package_name)
    return msgs, rules
示例#35
0
    def __init__(self, parentfilter, display_list_args=None):
        """
        Widget for displaying interactive data related to text filtering.

        Taken from rqt_console and simplified to be usable in broader
        situations.

        :type parentfilter: BaseFilter
        :param parentfilter: buddy filter were data is stored, ''TimeFilter''
        :param display_list_args: empty list, ''list''
        """
        super(TextFilterWidget, self).__init__()
        _, package_path = get_resource('packages', 'rqt_reconfigure')
        ui_file = os.path.join(package_path, 'share', 'rqt_reconfigure',
                               'resource', 'text_filter_widget.ui')
        loadUi(ui_file, self)
        self.setObjectName('TextFilterWidget')
        # When data is changed it is stored in the parent filter
        self._parentfilter = parentfilter

        self.text_edit.textChanged.connect(self.handle_text_changed)

        self.handle_text_changed()
示例#36
0
def get_ros2_messages():
    msgs = []
    rules = []
    # get messages from packages
    resource_type = 'rosidl_interfaces'
    resources = ament_index_python.get_resources(resource_type)
    for package_name, prefix_path in resources.items():
        resource = ament_index_python.get_resource(resource_type, package_name)
        interfaces = resource.splitlines()
        message_names = [i[:-4] for i in interfaces if i.endswith('.msg')]
        for message_name in message_names:
            msgs.append(Message(package_name, message_name, prefix_path))
        # check package manifest for mapping rules
        package_path = os.path.join(prefix_path, 'share', package_name)
        pkg = parse_package(package_path)
        for export in pkg.exports:
            if export.tagname != 'ros1_bridge':
                continue
            if 'mapping_rules' not in export.attributes:
                continue
            rule_file = os.path.join(package_path,
                                     export.attributes['mapping_rules'])
            rules += read_mapping_rules(rule_file, package_name)
    return msgs, rules
示例#37
0
    def __init__(self, context):
        super(JointTrajectoryController, self).__init__(context)
        self.setObjectName('JointTrajectoryController')

        self._node = context.node

        # Get the robot_description via a topic
        qos_profile = QoSProfile(depth=1,
                                 history=HistoryPolicy.KEEP_LAST,
                                 durability=DurabilityPolicy.TRANSIENT_LOCAL)
        self._robot_description_sub = self._node.create_subscription(
            String, 'robot_description',
            self._robot_description_cb, qos_profile)
        self._robot_description = None

        self._publisher = None
        self._widget = QWidget()

        _, package_path = get_resource('packages', 'rqt_joint_trajectory_controller')
        ui_file = os.path.join(package_path, 'share', 'rqt_joint_trajectory_controller', 'resource', 'joint_trajectory_controller.ui')
        loadUi(ui_file, self._widget)

        self._widget.setObjectName('JointTrajectoryControllerUi')
        if context.serial_number() > 1:
            self._widget.setWindowTitle(
                self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        ns = self._node.get_namespace()
        self._widget.controller_group.setTitle('ns: ' + ns)

        # Setup speed scaler
        speed_scaling = DoubleEditor(1.0, 100.0)
        speed_scaling.spin_box.setSuffix('%')
        speed_scaling.spin_box.setValue(50.0)
        speed_scaling.spin_box.setDecimals(0)
        speed_scaling.setEnabled(False)
        self._widget.speed_scaling_layout.addWidget(speed_scaling)
        self._speed_scaling_widget = speed_scaling
        speed_scaling.valueChanged.connect(self._on_speed_scaling_change)
        self._on_speed_scaling_change(speed_scaling.value())

        # Show _widget.windowTitle on left-top of each plugin (when
        # it's set in _widget). This is useful when you open multiple
        # plugins at once. Also if you open multiple instances of your
        # plugin at once, these lines add number to make it easy to
        # tell from pane to pane.
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() +
                                        (' (%d)' % context.serial_number()))
        # Add widget to the user interface
        context.add_widget(self._widget)

        # Initialize members
        self._jtc_name = []  # Name of selected joint trajectory controller
        self._cm_ns = []  # Namespace of the selected controller manager
        self._joint_pos = {}  # name->pos map for joints of selected controller
        self._joint_names = []  # Ordered list of selected controller joints
        self._robot_joint_limits = {} # Lazily evaluated on first use

        # Timer for sending commands to active controller
        self._update_cmd_timer = QTimer(self)
        self._update_cmd_timer.setInterval(1000.0 / self._cmd_pub_freq)
        self._update_cmd_timer.timeout.connect(self._update_cmd_cb)

        # Timer for updating the joint widgets from the controller state
        self._update_act_pos_timer = QTimer(self)
        self._update_act_pos_timer.setInterval(1000.0 /
                                               self._widget_update_freq)
        self._update_act_pos_timer.timeout.connect(self._update_joint_widgets)

        # Timer for controller manager updates
        # TODO: self._list_cm = ControllerManagerLister()
        self._update_cm_list_timer = QTimer(self)
        self._update_cm_list_timer.setInterval(1000.0 /
                                               self._ctrlrs_update_freq)
        self._update_cm_list_timer.timeout.connect(self._update_cm_list)
        self._update_cm_list_timer.start()

        # Timer for running controller updates
        self._update_jtc_list_timer = QTimer(self)
        self._update_jtc_list_timer.setInterval(1000.0 /
                                                self._ctrlrs_update_freq)
        self._update_jtc_list_timer.timeout.connect(self._update_jtc_list)
        self._update_jtc_list_timer.start()

        # Signal connections
        w = self._widget
        w.enable_button.toggled.connect(self._on_jtc_enabled)
        w.jtc_combo.currentIndexChanged[str].connect(self._on_jtc_change)
        w.cm_combo.currentIndexChanged[str].connect(self._on_cm_change)

        self._cmd_pub = None    # Controller command publisher
        self._state_sub = None  # Controller state subscriber

        self._list_controllers = None

        self._traj_ns_topic_dict = None
def test_resource_overlay():
    set_ament_prefix_path(['prefix1', 'prefix2'])

    resource, prefix = get_resource('resource_type5', 'foo')
    assert resource == 'foo1', 'Expected different content'
    assert os.path.basename(prefix) == 'prefix1', 'Expected different prefix'
def test_resource_overlay():
    set_ament_prefix_path(['prefix1', 'prefix2'])

    resource = get_resource('resource_type5', 'foo')
    assert resource == 'foo1', 'Expected different content'