Пример #1
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description='Parse all recursively found .msg files.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('paths',
                        nargs='+',
                        help='The base paths to search for .msg files')
    args = parser.parse_args(argv)

    files = get_files(args.paths)

    for filename in files:
        pkg_name = os.path.basename(os.path.dirname(os.path.dirname(filename)))
        try:
            parse_message_file(pkg_name, filename)
            print(pkg_name, filename)
        except Exception as e:
            print(' ', pkg_name, filename, str(e))
            raise

    return 0
Пример #2
0
def test_parse_message_file():
    path = tempfile.mkdtemp(prefix='test_parse_message_file_')
    try:
        filename = os.path.join(path, 'Foo.msg')
        with open(filename, 'w') as handle:
            handle.write('bool foo')
        msg_spec = parse_message_file('pkg', filename)

        assert len(msg_spec.fields) == 1
        assert msg_spec.fields[0].type.type == 'bool'
        assert msg_spec.fields[0].name == 'foo'
        assert msg_spec.fields[0].default_value is None
        assert len(msg_spec.constants) == 0

        with open(filename, 'a') as handle:
            handle.write('\nbool foo')
        with pytest.raises(ValueError) as e:
            parse_message_file('pkg', filename)
        assert 'foo' in str(e.value)
    finally:
        shutil.rmtree(path)
Пример #3
0
def test_parse_message_file():
    path = tempfile.mkdtemp(prefix='test_parse_message_file_')
    try:
        filename = os.path.join(path, 'Foo.msg')
        with open(filename, 'w') as handle:
            handle.write('bool foo')
        msg_spec = parse_message_file('pkg', filename)

        assert len(msg_spec.fields) == 1
        assert msg_spec.fields[0].type.type == 'bool'
        assert msg_spec.fields[0].name == 'foo'
        assert msg_spec.fields[0].default_value is None
        assert len(msg_spec.constants) == 0

        with open(filename, 'a') as handle:
            handle.write('\nbool foo')
        with pytest.raises(ValueError) as e:
            parse_message_file('pkg', filename)
        assert 'foo' in str(e)
    finally:
        shutil.rmtree(path)
Пример #4
0
def main(argv=sys.argv[1:]):
    parser = argparse.ArgumentParser(
        description='Parse all recursively found .msg files.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        'paths',
        nargs='+',
        help='The base paths to search for .msg files')
    args = parser.parse_args(argv)

    files = get_files(args.paths)

    for filename in files:
        pkg_name = os.path.basename(os.path.dirname(os.path.dirname(filename)))
        try:
            parse_message_file(pkg_name, filename)
            print(pkg_name, filename)
        except Exception as e:
            print(' ', pkg_name, filename, str(e))
            raise

    return 0
Пример #5
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
Пример #6
0
def find_package_info(requested_pkg_name):
    info = PackageInfo(requested_pkg_name)

    share_dir = get_package_share_directory(requested_pkg_name)

    message_dir = '{}/msg'.format(share_dir)
    if os.path.exists(message_dir):
        for relative_msg_file in os.listdir(message_dir):
            if not relative_msg_file.endswith('.msg'):
                continue

            msg_file = '{}/{}'.format(message_dir, relative_msg_file)

            info.msg_files.append(msg_file)
            msg = parse_message_file(requested_pkg_name, msg_file)
            for field in msg.fields:
                if field.type.is_primitive_type():
                    continue

                info.dependencies.append(field.type.pkg_name)

    service_dir = '{}/srv'.format(share_dir)
    if os.path.exists(service_dir):
        for relative_srv_file in os.listdir(service_dir):
            if not relative_srv_file.endswith('.srv'):
                continue

            srv_file = '{}/{}'.format(service_dir, relative_srv_file)

            info.srv_files.append(srv_file)
            srv = parse_service_file(requested_pkg_name, srv_file)
            for component in [srv.request, srv.response]:
                for field in component.fields:
                    if field.type.is_primitive_type():
                        continue

                    info.dependencies.append(field.type.pkg_name)

    return info
Пример #7
0
def parse_interface(m):
    assert isinstance(m, str)
    pkg, tag, name = m.split('/')
    path = get_interface_path(m)
    if tag == 'msg':
        obj = parse_message_file(pkg, path)
        monkey_patch_fields(obj)
        obj.__dict__['subinterfaces'] = {'Message': obj}
    elif tag == 'srv':
        obj = parse_service_file(pkg, path)
        monkey_patch_fields(obj.request)
        monkey_patch_fields(obj.response)
        obj.__dict__['subinterfaces'] = {
            'Request': obj.request,
            'Response': obj.response
        }
    elif tag == 'action':
        obj = parse_action_file(pkg, path)
        monkey_patch_fields(obj.goal)
        monkey_patch_fields(obj.feedback)
        monkey_patch_fields(obj.result)
        obj.__dict__['subinterfaces'] = {
            'Goal': obj.goal,
            'Feedback': obj.feedback,
            'Result': obj.result
        }
    for subinterface_name, subinterface in obj.subinterfaces.items():
        subinterface.__dict__['cpp_type_normalized'] = '{}/{}'.format(
            m, subinterface_name).replace('/', '__')
        subinterface.__dict__['cpp_type'] = '::'.join(
            [pkg, tag, name, subinterface_name])
    obj.__dict__['tag'] = tag
    obj.__dict__['full_name'] = m
    obj.__dict__['cpp_include'] = '{}/{}/{}.hpp'.format(
        pkg, tag, camel_case_to_snake_case(name))
    obj.__dict__['cpp_type_normalized'] = m.replace('/', '__')
    obj.__dict__['cpp_type'] = '::'.join([pkg, tag, name])
    return obj
Пример #8
0
def parse_packages(ros2_pkgs):
    import os
    from os.path import join as joinp
    from os.path import relpath

    from ament_index_python.packages import get_package_share_directory

    dependent_pkgs = set(ros2_pkgs)
    for ros2_pkg in ros2_pkgs:
        print(ros2_pkg)
        pkg_dir = get_package_share_directory(ros2_pkg)
        for dirpath, _, filenames in os.walk(pkg_dir):
            for filename in filenames:
                filepath = joinp(dirpath, filename)
                if filename.endswith(".msg"):
                    msgspec = parse_message_file(ros2_pkg, filepath)
                    with open(filepath) as f:
                        msgspec.raw = f.read()
                    msgspec.reldir = relpath(dirpath, pkg_dir)
                    full_type_str = get_full_type_str(msgspec.base_type)
                    __parsed_msgs[full_type_str] = msgspec
                    for field in msgspec.fields:
                        field.js_type = JsType(field.type)
                        full_type_str = get_full_type_str(field.type)
                        if full_type_str not in __parsed_msgs and field.type.pkg_name:
                            dependent_pkgs.add(field.type.pkg_name)
                elif filename.endswith(".srv"):
                    srvspec = parse_service_file(ros2_pkg, filepath)
                    srvspec.reldir = relpath(dirpath, pkg_dir)
                    full_type_str = f"{srvspec.pkg_name}/{srvspec.srv_name}"
                    __parsed_srvs[full_type_str] = srvspec
                else:
                    continue
    dependent_pkgs = dependent_pkgs.difference(ros2_pkgs)
    if dependent_pkgs:
        parse_packages(dependent_pkgs)
Пример #9
0
def generate_XML(args):
    pkg_name = args['package_name']
    #known_msg_types = extract_message_types(
    #    pkg_name, args['ros_interface_files'], args.get('ros_interface_dependencies', []))

    functions = {
        'get_header_filename_from_msg_name':
        convert_camel_case_to_lower_case_underscore,
    }

    # Set file format
    ros2_prefix = "rt/"

    # Check destination dir
    dest_dir = args['output_dir']
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    # Check source dir
    srcs_dir = os.path.join(dest_dir, "srcs")
    if not os.path.exists(srcs_dir):
        os.makedirs(srcs_dir)

    # Iterate throw all msgs/srvs
    for idl_file in args['ros_interface_files']:
        extension = os.path.splitext(idl_file)[1]
        if extension == '.msg':
            spec = parse_message_file(pkg_name, idl_file)
            #validate_field_types(spec, known_msg_types)
            subfolder = os.path.basename(os.path.dirname(idl_file))

            data = {
                'spec': spec,
                'pkg': spec.base_type.pkg_name,
                'msg': spec.msg_name,
                'type': spec.base_type.type,
                'subfolder': subfolder,
            }
            data.update(functions)

            # Generate source file path
            src_file = os.path.join(
                srcs_dir, "%s_%s_%s.xml" %
                (spec.base_type.pkg_name, subfolder, spec.msg_name))

            # Data writer
            #file_content  = "   <dds>\n"
            file_content = "       <data_writer profile_name=\"%s_%s_%s_p\">\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "           <topic profile_name=\"%s_%s_%s_t\">\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "               <kind>NO_KEY</kind>\n"
            file_content += "               <name>%s%s_%s_%s</name>\n" % (
                ros2_prefix, spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "               <dataType>%s::%s::dds_::%s_</dataType>\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "           </topic>\n"
            file_content += "       </data_writer>\n"
            #file_content += "   </dds>\n"

            # Data reader
            #file_content += "   <dds>\n"
            file_content += "       <data_reader profile_name=\"%s_%s_%s_s\">\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "           <topic profile_name=\"%s_%s_%s_t\">\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "               <kind>NO_KEY</kind>\n"
            file_content += "               <name>%s%s_%s_%s</name>\n" % (
                ros2_prefix, spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "               <dataType>%s::%s::dds_::%s_</dataType>\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "           </topic>\n"
            file_content += "       </data_reader>\n"
            #file_content += "   </dds>\n"

            # Topic
            #file_content += "   <dds>\n"
            file_content += "       <topic profile_name=\"%s_%s_%s_t\">\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "           <name>%s%s_%s_%s</name>\n" % (
                ros2_prefix, spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "           <dataType>%s::%s::dds_::%s_</dataType>\n" % (
                spec.base_type.pkg_name, subfolder, spec.msg_name)
            file_content += "       </topic>\n"
            #file_content += "   </dds>\n"

            # Write file content
            print("%s" % file_content)

        #elif extension == '.srv':

        #data = {'spec': spec}
        #data.update(functions)

        #if not os.path.exists(args['output_dir']):
        #    os.makedirs(args['output_dir'])

        #f = open(os.path.join(args['output_dir'], 'demofile.txt'), 'w+')
        #f.write("%s\n" % spec)
        #f.close()
    return 0