예제 #1
0
 def test_get_ros_hostname(self):
     roshn = host.get_ros_hostname(None)
     self.assertEqual(
         roshn, '',
         "ros hostname from `None` should be ``, got: %s, expected: %s" %
         (roshn, ''))
     roshn = host.get_ros_hostname('http://myhost:11311')
     self.assertEqual(
         roshn, 'myhost',
         "wrong ros hostname from `'http://myhost:11311'`, got: %s, expected: %s"
         % (roshn, 'myhost'))
     roshn = host.get_ros_hostname('http://192.168.11.5:11311')
     self.assertEqual(
         roshn, '',
         "wrong ros hostname from `'http://192.168.11.5:11311'`, got: %s, expected: %s"
         % (roshn, ''))
    def _prepareROSMaster(cls, masteruri):
        if masteruri is None:
            masteruri = masteruri_from_ros()
        # start roscore, if needed
        try:
            if not os.path.isdir(screen.LOG_PATH):
                os.makedirs(screen.LOG_PATH)
            socket.setdefaulttimeout(3)
            master = xmlrpcclient.ServerProxy(masteruri)
            master.getUri(rospy.get_name())
            # restart ROSCORE on different masteruri?, not now...
#      master_uri = master.getUri(rospy.get_name())
#      if masteruri != master_uri[2]:
#        # kill the local roscore...
#        raise
        except Exception:
            # run a roscore
            master_host = get_hostname(masteruri)
            if nm.is_local(master_host, True):
                master_port = get_port(masteruri)
                new_env = dict(os.environ)
                new_env['ROS_MASTER_URI'] = masteruri
                ros_hostname = nmdhost.get_ros_hostname(masteruri)
                if ros_hostname:
                    new_env['ROS_HOSTNAME'] = ros_hostname
                cmd_args = '%s roscore --port %d' % (screen.get_cmd('/roscore--%d' % master_port), master_port)
                for n in [1, 2, 3, 4]:
                    try:
                        if n == 1:
                            print("Launch ROS Master in screen  ... %s" % (cmd_args))
                            SupervisedPopen(shlex.split(cmd_args), env=new_env, object_id="ROSCORE", description="Start roscore")
                        elif n == 2:
                            print("ROS Master takes too long for start, wait for next 10 sec ...")
                        elif n == 3:
                            print("A really slow start, wait for last 10 sec ...")
                        # wait for roscore to avoid connection problems while init_node
                        result = -1
                        count = 1
                        while result == -1 and count < 11:
                            try:
                                master = xmlrpcclient.ServerProxy(masteruri)
                                result, _, _ = master.getUri(rospy.get_name())  # _:=uri, msg
                                return
                            except Exception:
                                time.sleep(1)
                                count += 1
                        if n == 4 and count >= 11:
                            raise StartException('Cannot connect to ROS-Master: %s\n--> please run "roscore" manually!' % utf8(masteruri))
                    except Exception as e:
                        raise Exception("Error while call '%s': %s" % (cmd_args, utf8(e)))
            else:
                raise Exception("ROS master '%s' is not reachable" % masteruri)
        finally:
            socket.setdefaulttimeout(None)
예제 #3
0
 def _prepareROSMaster(cls, masteruri):
     if not masteruri:
         masteruri = masteruri_from_ros()
     # start roscore, if needed
     try:
         if not os.path.isdir(screen.LOG_PATH):
             os.makedirs(screen.LOG_PATH)
         socket.setdefaulttimeout(3)
         master = xmlrpcclient.ServerProxy(masteruri)
         master.getUri(rospy.get_name())
     except Exception:
         # run a roscore
         screen.test_screen()
         master_host = get_hostname(masteruri)
         if cls.is_local(master_host, True):
             print("Start ROS-Master with %s ..." % masteruri)
             master_port = get_port(masteruri)
             new_env = dict(os.environ)
             new_env['ROS_MASTER_URI'] = masteruri
             ros_hostname = nmdhost.get_ros_hostname(masteruri)
             if ros_hostname:
                 new_env['ROS_HOSTNAME'] = ros_hostname
             cmd_args = '%s roscore --port %d' % (screen.get_cmd(
                 '/roscore--%d' % master_port), master_port)
             try:
                 subprocess.Popen(shlex.split(cmd_args), env=new_env)
                 # wait for roscore to avoid connection problems while init_node
                 result = -1
                 count = 1
                 while result == -1 and count < 11:
                     try:
                         print("  retry connect to ROS master %d/10" %
                               count)
                         master = xmlrpcclient.ServerProxy(masteruri)
                         result, _, _ = master.getUri(
                             rospy.get_name())  # _:=uri, msg
                     except Exception:
                         time.sleep(1)
                         count += 1
                 if count >= 11:
                     raise StartException(
                         'Cannot connect to the ROS-Master: ' +
                         str(masteruri))
             except Exception as e:
                 import sys
                 sys.stderr.write("%s\n" % e)
                 raise
         else:
             raise Exception("ROS master '%s' is not reachable" % masteruri)
     finally:
         socket.setdefaulttimeout(None)
예제 #4
0
def runNode(package, executable, name, args, prefix='', repawn=False, masteruri=None, loglevel=''):
    '''
    Runs a ROS node. Starts a roscore if needed.
    '''
    if not masteruri:
        masteruri = masteruri_from_ros()
    # start roscore, if needed
    nm.StartHandler._prepareROSMaster(masteruri)
    # start node
    try:
        cmd = roslib.packages.find_node(package, executable)
    except roslib.packages.ROSPkgException as e:
        # multiple nodes, invalid package
        raise nm.StartException(str(e))
    # handle different result types str or array of string (electric / fuerte)
    if isstring(cmd):
        cmd = [cmd]
    if cmd is None or len(cmd) == 0:
        raise nm.StartException(' '.join([executable, 'in package [', package, '] not found!\n\nThe package was created?\nIs the binary executable?\n']))
    # create string for node parameter. Set arguments with spaces into "'".
    node_params = ' '.join(''.join(["'", a, "'"]) if a.find(' ') > -1 else a for a in args[1:])
    cmd_args = [screen.get_cmd(name), RESPAWN_SCRIPT if repawn else '', prefix, cmd[0], node_params]
    print('run on remote host:', ' '.join(cmd_args))
    # determine the current working path
    arg_cwd = getCwdArg('__cwd', args)
    cwd = nm.get_ros_home()
    if not (arg_cwd is None):
        if arg_cwd == 'ROS_HOME':
            cwd = nm.get_ros_home()
        elif arg_cwd == 'node':
            cwd = os.path.dirname(cmd[0])
    # set the masteruri to launch with other one master
    new_env = dict(os.environ)
    new_env['ROS_MASTER_URI'] = masteruri
    ros_hostname = nmdhost.get_ros_hostname(masteruri)
    if ros_hostname:
        addr = socket.gethostbyname(ros_hostname)
        if addr in set(ip for ip in get_local_addresses()):
            new_env['ROS_HOSTNAME'] = ros_hostname
    if loglevel:
        new_env['ROSCONSOLE_CONFIG_FILE'] = rosconsole_cfg_file(package)
    subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd, env=new_env)
    if len(cmd) > 1:
        rospy.logwarn('Multiple executables are found! The first one was started! Exceutables:\n%s', str(cmd))
예제 #5
0
    def bc_run_node(cls,
                    name,
                    grpc_path='grpc://localhost:12321',
                    masteruri='',
                    reload_global_param=False,
                    loglevel='',
                    logformat='',
                    auto_pw_request=False,
                    user=None,
                    pw=None):
        '''
        Start the node with given name from the given configuration.

        :param runcfg: the configuration containing the start parameter
        :type runcfg: AdvRunCfg
        :raise StartException: if the screen is not available on host.
        :raise Exception: on errors while resolving host
        :see: :meth:`fkie_node_manager.is_local()`
        '''
        startcfg = nm.nmd().launch.get_start_cfg(
            name,
            grpc_path,
            masteruri,
            reload_global_param=reload_global_param,
            loglevel=loglevel,
            logformat=logformat)
        new_env = dict(startcfg.env)
        # set logging options
        if startcfg.namespace:
            new_env['ROS_NAMESPACE'] = startcfg.namespace
        # set logging
        if startcfg.logformat:
            new_env['ROSCONSOLE_FORMAT'] = '%s' % startcfg.logformat
#         if startcfg.loglevel:
#             new_env['ROSCONSOLE_CONFIG_FILE'] = launcher._rosconsole_cfg_file(startcfg.package, startcfg.loglevel)
        args = []
        # set name and namespace of the node
        if startcfg.name:
            args.append("__name:=%s" % startcfg.name)
        if startcfg.namespace:
            args.append("__ns:=%s" % startcfg.namespace)
        # add remap arguments
        for key, val in startcfg.remaps.items():
            args.append("%s:=%s" % (key, val))
        # handle respawn
        if startcfg.respawn:
            if startcfg.respawn_delay > 0:
                new_env['RESPAWN_DELAY'] = '%d' % startcfg.respawn_delay
            respawn_params = launcher._get_respawn_params(
                startcfg.fullname, startcfg.params)
            if respawn_params['max'] > 0:
                new_env['RESPAWN_MAX'] = '%d' % respawn_params['max']
            if respawn_params['min_runtime'] > 0:
                new_env['RESPAWN_MIN_RUNTIME'] = '%d' % respawn_params[
                    'min_runtime']
        if startcfg.cwd:
            cwd = get_cwd(startcfg.cwd, startcfg.binary_path)
            if cwd:
                args.append('__cwd:=%s' % cwd)
        # check for masteruri
        masteruri = startcfg.masteruri
        on_hostname = startcfg.hostname
        if masteruri is None:
            masteruri = masteruri_from_ros()
        if masteruri is not None:
            new_env['ROS_MASTER_URI'] = masteruri
            if 'ROS_HOSTNAME' in os.environ:
                # set only ROS_HOSTNAME if node manager have also one
                ros_hostname = nmdhost.get_ros_hostname(masteruri, on_hostname)
                if ros_hostname:
                    new_env['ROS_HOSTNAME'] = ros_hostname
            # load params to ROS master
            launcher._load_parameters(masteruri, startcfg.params,
                                      startcfg.clear_params)

        abs_paths = list()  # tuples of (parameter name, old value, new value)
        not_found_packages = list()  # package names
        #         # set the global parameter
        #         if runcfg.masteruri is not None and runcfg.masteruri not in runcfg.roslaunch_config.global_param_done:
        #             global_node_names = cls.getGlobalParams(runcfg.roslaunch_config.Roscfg)
        #             rospy.loginfo("Register global parameter:\n  %s", '\n  '.join("%s%s" % (utf8(v)[:80], '...' if len(utf8(v)) > 80 else'') for v in global_node_names.values()))
        #             abs_paths[len(abs_paths):], not_found_packages[len(not_found_packages):] = cls._load_parameters(runcfg.masteruri, global_node_names, [], runcfg.user, runcfg.pw, runcfg.auto_pw_request)
        #             runcfg.roslaunch_config.global_param_done.append(runcfg.masteruri)
        #
        #         # add params
        #         if runcfg.masteruri is not None:
        #             nodens = ''.join([n.namespace, n.name, rospy.names.SEP])
        #             params = dict()
        #             for param, value in runcfg.roslaunch_config.Roscfg.params.items():
        #                 if param.startswith(nodens):
        #                     params[param] = value
        #             clear_params = []
        #             for cparam in runcfg.roslaunch_config.Roscfg.clear_params:
        #                 if cparam.startswith(nodens):
        #                     clear_params.append(cparam)
        #             rospy.loginfo("Delete parameter:\n  %s", '\n  '.join(clear_params))
        #             rospy.loginfo("Register parameter:\n  %s", '\n  '.join("%s%s" % (utf8(v)[:80], '...' if len(utf8(v)) > 80 else'') for v in params.values()))
        #             abs_paths[len(abs_paths):], not_found_packages[len(not_found_packages):] = cls._load_parameters(runcfg.masteruri, params, clear_params, runcfg.user, runcfg.pw, runcfg.auto_pw_request)
        if not nm.is_local(on_hostname, wait=True):
            # start remote
            if not startcfg.package:
                raise StartException(
                    "Can't run remote without a valid package name!")
            # setup environment
            env_command = ''
            if new_env:
                try:
                    for k, v in new_env.items():
                        v_value, is_abs_path, found, package = cls._bc_resolve_abs_paths(
                            v, on_hostname, auto_pw_request, user, pw)
                        new_env[k] = v_value
                        if is_abs_path:
                            abs_paths.append(('ENV', "%s=%s" % (k, v),
                                              "%s=%s" % (k, v_value)))
                            if not found and package:
                                not_found_packages.append(package)
                    env_command = "env " + ' '.join(
                        ["%s=\'%s\'" % (k, v) for (k, v) in new_env.items()])
                except nm.AuthenticationRequest as e:
                    raise nm.InteractionNeededError(
                        e, cls.bc_run_node, {
                            'name': name,
                            'grpc_path': grpc_path,
                            'masteruri': masteruri,
                            'reload_global_param': reload_global_param,
                            'loglevel': loglevel,
                            'logformat': logformat,
                            'auto_pw_request': auto_pw_request,
                            'user': user,
                            'pw': pw
                        })
            startcmd = [
                env_command,
                nm.settings().start_remote_script, '--package',
                utf8(startcfg.package), '--node_type',
                utf8(startcfg.binary), '--node_name',
                utf8(startcfg.fullname),
                '--node_respawn true' if startcfg.respawn else ''
            ]
            if startcfg.masteruri is not None:
                startcmd.append('--masteruri')
                startcmd.append(startcfg.masteruri)
            if startcfg.prefix:
                startcmd[len(startcmd):] = ['--prefix', startcfg.prefix]
            if startcfg.loglevel:
                startcmd.append('--loglevel')
                startcmd.append(startcfg.loglevel)

            # rename the absolute paths in the args of the node
            node_args = []
            error = ''
            output = ''
            try:
                for a in startcfg.args:
                    a_value, is_abs_path, found, package = cls._bc_resolve_abs_paths(
                        a, on_hostname, auto_pw_request, user, pw)
                    node_args.append(a_value)
                    if is_abs_path:
                        abs_paths.append(('ARGS', a, a_value))
                        if not found and package:
                            not_found_packages.append(package)

                startcmd[len(startcmd):] = node_args
                startcmd[len(startcmd):] = args
                rospy.loginfo("Run remote on %s: %s", on_hostname,
                              utf8(' '.join(startcmd)))
                _, stdout, stderr, ok = nm.ssh().ssh_exec(on_hostname,
                                                          startcmd,
                                                          user,
                                                          pw,
                                                          auto_pw_request,
                                                          close_stdin=True)
                output = stdout.read()
                error = stderr.read()
                stdout.close()
                stderr.close()
            except nm.AuthenticationRequest as e:
                raise nm.InteractionNeededError(
                    e, cls.bc_run_node, {
                        'name': name,
                        'grpc_path': grpc_path,
                        'masteruri': masteruri,
                        'reload_global_param': reload_global_param,
                        'loglevel': loglevel,
                        'logformat': logformat,
                        'auto_pw_request': auto_pw_request,
                        'user': user,
                        'pw': pw
                    })
            if ok:
                if error:
                    rospy.logwarn("ERROR while start '%s': %s",
                                  startcfg.fullname, error)
                    raise StartException(
                        utf8(''.join(
                            ['The host "', on_hostname, '" reports:\n',
                             error])))
                if output:
                    rospy.logdebug("STDOUT while start '%s': %s",
                                   startcfg.fullname, output)
            # inform about absolute paths in parameter value
            if len(abs_paths) > 0:
                rospy.loginfo(
                    "Absolute paths found while start:\n%s",
                    utf8('\n'.join([
                        ''.join([p, '\n  OLD: ', ov, '\n  NEW: ', nv])
                        for p, ov, nv in abs_paths
                    ])))

            if len(not_found_packages) > 0:
                packages = '\n'.join(not_found_packages)
                raise StartException(
                    utf8('\n'.join([
                        'Some absolute paths are not renamed because following packages are not found on remote host:',
                        packages
                    ])))
예제 #6
0
    def runNodeWithoutConfig(cls,
                             host,
                             package,
                             binary,
                             name,
                             args=[],
                             masteruri=None,
                             use_nmd=True,
                             auto_pw_request=False,
                             user=None,
                             pw=None,
                             path=''):
        '''
        Start a node with using a launch configuration.

        :param str hosturi: the host or ip to run the node
        :param str package: the ROS package containing the binary
        :param str binary: the binary of the node to execute
        :param str name: the ROS name of the node (with name space)
        :param args: the list with arguments passed to the binary
        :type args: [str]
        :param bool use_nmd: start the node using node manager daemon
        :param bool auto_pw_request: opens question dialog directly, use True only if the method is called from the main GUI thread
        :raise Exception: on errors while resolving host
        :see: :meth:`fkie_node_manager.is_local()`
        '''
        # create the name with namespace
        args2 = list(args)
        fullname = roslib.names.ns_join(roslib.names.SEP, name)
        namespace = ''
        for a in args:
            if a.startswith('__ns:='):
                namespace = a.replace('__ns:=', '')
                fullname = roslib.names.ns_join(namespace, name)
        args2.append(''.join(['__name:=', name]))
        # run on local host
        if nm.is_local(host, wait=True):
            if not use_nmd:
                if path:
                    cmd = [path]
                else:
                    try:
                        cmd = roslib.packages.find_node(package, binary)
                    except roslib.packages.ROSPkgException as e:
                        # multiple nodes, invalid package
                        raise StartException(utf8(e))
                    # handle different result types str or array of string
                    if isstring(cmd):
                        cmd = [cmd]
                cmd_type = ''
                if cmd is None or len(cmd) == 0:
                    raise StartException('%s in package [%s] not found!' %
                                         (binary, package))
                # compatibility for python scripts installed with catkin_install_python()
                # avoid ask for select a binary
                cmd = cls._remove_src_binary(cmd)
                if len(cmd) > 1:
                    # Open selection for executables
                    err = 'Multiple executables with same name in package [%s] found' % package
                    bsel = nm.BinarySelectionRequest(cmd, err)
                    raise nm.InteractionNeededError(
                        bsel, cls.runNodeWithoutConfig, {
                            'host': host,
                            'package': package,
                            'binary': binary,
                            'name': name,
                            'args': args,
                            'masteruri': masteruri,
                            'use_nmd': use_nmd,
                            'auto_pw_request': auto_pw_request,
                            'user': user,
                            'pw': pw,
                            'path': path
                        })
                else:
                    cmd_type = cmd[0]
            new_env = {}  # dict(os.environ)
            if namespace:
                new_env['ROS_NAMESPACE'] = namespace
            if masteruri is not None:
                cls._prepareROSMaster(masteruri)
                new_env['ROS_MASTER_URI'] = masteruri
                if 'ROS_HOSTNAME' in os.environ:
                    # set ROS_HOSTNAME only if node_manager has also one
                    ros_hostname = nmdhost.get_ros_hostname(masteruri, host)
                    if ros_hostname:
                        new_env['ROS_HOSTNAME'] = ros_hostname
            if use_nmd:
                nm.nmd().launch.start_standalone_node(nmdurl.nmduri(), package,
                                                      binary, name, namespace,
                                                      args, new_env, masteruri,
                                                      host)
            else:
                local_env = dict(os.environ)
                local_env.update(new_env)
                cmd_str = utf8(' '.join([
                    screen.get_cmd(fullname, local_env), cmd_type,
                    ' '.join(args2)
                ]))
                rospy.loginfo("Run without config: %s",
                              fullname if use_nmd else cmd_str)
                SupervisedPopen(shlex.split(cmd_str),
                                env=local_env,
                                object_id="Run without config",
                                description="Run without config [%s]%s" %
                                (utf8(package), utf8(binary)))
        else:
            # run on a remote machine
            startcmd = [
                nm.settings().start_remote_script, '--package',
                utf8(package), '--node_type',
                utf8(binary), '--node_name',
                utf8(fullname)
            ]
            startcmd[len(startcmd):] = args2
            if masteruri is not None:
                startcmd.append('--masteruri')
                startcmd.append(masteruri)
            rospy.loginfo("Run remote on %s: %s", host, ' '.join(startcmd))
            try:
                _, stdout, stderr, ok = nm.ssh().ssh_exec(host,
                                                          startcmd,
                                                          user,
                                                          pw,
                                                          auto_pw_request,
                                                          close_stdin=True)
                if ok:
                    output = stdout.read()
                    error = stderr.read()
                    stdout.close()
                    stderr.close()
                    if error:
                        rospy.logwarn("ERROR while start '%s': %s", name,
                                      error)
                        raise StartException(''.join(
                            ['The host "', host, '" reports:\n', error]))
                    if output:
                        if output.find("dn't") != -1:
                            rospy.logwarn("Warning while start '%s': %s", name,
                                          output)
                        else:
                            rospy.loginfo("STDOUT while start '%s': %s", name,
                                          output)
                else:
                    if error:
                        rospy.logwarn("ERROR while start '%s': %s", name,
                                      error)
                        raise StartException(''.join(
                            ['The host "', host, '" reports:\n', error]))
            except nm.AuthenticationRequest as e:
                raise nm.InteractionNeededError(
                    e, cls.runNodeWithoutConfig, {
                        'host': host,
                        'package': package,
                        'binary': binary,
                        'name': name,
                        'args': args,
                        'masteruri': masteruri,
                        'use_nmd': use_nmd,
                        'auto_pw_request': auto_pw_request,
                        'user': user,
                        'pw': pw,
                        'path': path
                    })
예제 #7
0
def main(name):
    '''
    Start the NodeManager or EchoDialog.

    :param str name: the name propagated to the :meth:`rospy.init_node`
    '''
    try:
        from python_qt_binding.QtGui import QApplication
    except Exception:
        try:
            from python_qt_binding.QtWidgets import QApplication
        except Exception:
            sys.stderr.write("please install 'python_qt_binding' package!!")
            sys.exit(-1)
    init_settings()
    global __version__
    global __date__
    __version__, __date__ = detect_version(PKG_NAME)
    parser = init_arg_parser()
    args = rospy.myargv(argv=sys.argv)
    parsed_args = parser.parse_args(args[1:])
    if parsed_args.muri:
        masteruri = parsed_args.muri[0]
        hostname = nmdhost.get_ros_hostname(masteruri)
        os.environ['ROS_MASTER_URI'] = masteruri
        if hostname:
            os.environ['ROS_HOSTNAME'] = hostname
    masteruri = settings().masteruri()
    # Initialize Qt
    global _QAPP
    _QAPP = QApplication(sys.argv)

    # decide to show main or echo dialog
    global _MAIN_FORM
    try:
        if parsed_args.echo:
            _MAIN_FORM = init_echo_dialog(name, masteruri, parsed_args.echo[0],
                                          parsed_args.echo[1], parsed_args.hz,
                                          parsed_args.ssh)
        else:
            _MAIN_FORM = init_main_window(name, masteruri, parsed_args.file,
                                          parsed_args.port)
        thread = threading.Thread(target=rospy.spin)
        thread.daemon = True
        thread.start()
        rospy.on_shutdown(finish)
    except Exception as err:
        import traceback
        print(traceback.format_exc())
        sys.exit("%s" % err)

    exit_code = 0
    # resize and show the qt window
    if not rospy.is_shutdown():
        # change path for access to the images of descriptions
        os.chdir(settings().PACKAGE_DIR)
        #    _MAIN_FORM.resize(1024, 720)
        screen_size = QApplication.desktop().availableGeometry()
        if (_MAIN_FORM.size().width() >= screen_size.width()
                or _MAIN_FORM.size().height() >= screen_size.height() - 24):
            _MAIN_FORM.showMaximized()
        else:
            _MAIN_FORM.show()
        exit_code = -1
        try:
            exit_code = _QAPP.exec_()
            if nmd() is not None:
                nmd().stop()
        except Exception:
            if not rospy.is_shutdown():
                import traceback
                print(traceback.format_exc())
    return exit_code