def _bc_resolve_abs_paths(cls, value, host, auto_pw_request, user, pw):
        '''
        Replaces the local absolute path by remote absolute path. Only valid ROS
        package paths are resolved.

        :return: value, is absolute path, remote package found (ignore it on local host or if is not absolute path!), package name (if absolute path and remote package NOT found)
        '''
        if isstring(value) and value.startswith('/') and (os.path.isfile(value) or os.path.isdir(value)):
            if nm.is_local(host):
                return value, True, True, ''
            else:
                path = os.path.dirname(value) if os.path.isfile(value) else value
                package, package_path = package_name(path)
                if package:
                    _, stdout, _, ok = nm.ssh().ssh_exec(host, ['rospack', 'find', package], user, pw, auto_pw_request, close_stdin=True, close_stderr=True)
                    output = stdout.read()
                    stdout.close()
                    if ok:
                        if output:
                            value.replace(package_path, output)
                            return value.replace(package_path, output.strip()), True, True, package
                        else:
                            # package on remote host not found!
                            # TODO add error message
                            #      error = stderr.read()
                            pass
                return value, True, False, ''
        else:
            return value, False, False, ''
Ejemplo n.º 2
0
 def __gt__(self, item):
     '''
     Compares the path of the item.
     '''
     if isstring(item):
         return self.launchfile > item
     elif not (item is None):
         return self.launchfile > item.launchfile
     return False
Ejemplo n.º 3
0
 def __eq__(self, item):
     '''
     Compares the value of parameter.
     '''
     if isstring(item):
         return utf8(self.value) == utf8(item)
     elif not (item is None):
         return utf8(self.value) == utf8(item.value)
     return False
Ejemplo n.º 4
0
 def __gt__(self, item):
     '''
     Compares the path of the item.
     '''
     if isstring(item):
         return self.path.lower() > item.lower()
     elif not (item is None):
         return self.path.lower() > item.path.lower()
     return False
Ejemplo n.º 5
0
 def __eq__(self, item):
     '''
     Compares the name of the group.
     '''
     if isstring(item):
         return self.name.lower() == item.lower()
     elif not (item is None):
         return self.name.lower() == item.name.lower()
     return False
Ejemplo n.º 6
0
 def __gt__(self, item):
     '''
     Compares the name of parameter.
     '''
     if isstring(item):
         return self.name.lower() > item.lower()
     elif not (item is None):
         return self.name.lower() > item.name.lower()
     return False
Ejemplo n.º 7
0
def _convert_getattr(val, f, t):
    """
    Convert attribute types on the fly, if necessary.  This is mainly
    to convert uint8[] fields back to an array type.
    """
    attr = getattr(val, f)
    if isstring(attr) and 'uint8[' in t:
        return [ord(x) for x in attr]
    else:
        return attr
Ejemplo n.º 8
0
 def __gt__(self, item):
     if isstring(item):
         local = False
         try:
             local = nm.is_local(get_hostname(nm.nameres().masteruri(item)))
         except Exception:
             pass
         if self.local and not local:  # local hosts are at the top
             return False
         return self.master.name.lower() > item.lower()
     elif not (item is None):
         if self.local and not item.local:  # local hosts are at the top
             return False
         return self.master.name.lower() > item.master.name.lower()
     return False
Ejemplo n.º 9
0
 def host_color(self, host, default_color):
     if self.colorize_hosts:
         # get the color from settings file
         if host in self._host_colors:
             result = self._host_colors[host]
             if isstring(result):
                 return int(result)
             return result
         else:
             # determine a color
             hash_str = hashlib.md5(host.encode('utf-8')).hexdigest()
             hash_int = int(hash_str, 16)
             index = abs(hash_int) % len(self.DEAFULT_HOST_COLORS)
             return self.DEAFULT_HOST_COLORS[index]
     return default_color
Ejemplo n.º 10
0
 def __init__(self, name, value, parent=None):
     '''
     Initialize the item object.
     @param name: the name of the parameter
     @type name: C{str}
     @param value: the value of the parameter
     @type value: C{str}
     '''
     QStandardItem.__init__(
         self,
         utf8(value)
         if not isinstance(value, xmlrpcclient.Binary) else utf8(value))
     self._name = name
     '''@ivar: the name of parameter '''
     self._value = value
     '''@ivar: the value of the parameter '''
     if isstring(value) and value.find('\n') > -1:
         self.setSizeHint(QSize(-1, 45))
Ejemplo n.º 11
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))
 def __init__(self, name, value, parent=None):
     '''
     Initialize the item object.
     @param name: the name of the parameter
     @type name: C{str}
     @param value: the value of the parameter
     @type value: C{str}
     '''
     value_str = utf8(value) if not isinstance(value, xmlrpcclient.Binary) else utf8(value)
     self.read_only = False
     if len(value_str) > 32000:
         value_str = 'value size > 32000; use Ctrl+X to copy'
         self.read_only = True
     QStandardItem.__init__(self, value_str)
     self.setEditable(not self.read_only)
     self._name = name
     '''@ivar: the name of parameter '''
     self._value = value
     '''@ivar: the value of the parameter '''
     if isstring(value) and value.find('\n') > -1:
         self.setSizeHint(QSize(-1, 45))
Ejemplo n.º 13
0
 def __gt__(self, item):
     '''
     Compares the name of the group.
     '''
     if isstring(item):
         # put the group with SYSTEM nodes at the end
         if self.is_system_group:
             if self.name.lower() != item.lower():
                 return True
         elif item.lower() == 'system':
             return False
         return self.name.lower() > item.lower()
     elif not (item is None):
         # put the group with SYSTEM nodes at the end
         if item.is_system_group:
             if self.name.lower() != item.lower():
                 return True
         elif self.is_syste_group:
             return False
         return self.name.lower() > item.name.lower()
     return False
Ejemplo n.º 14
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
                    })
Ejemplo n.º 15
0
    def strify_message(cls, val, indent='', time_offset=None, current_time=None, field_filter=None, fixed_numeric_width=None, digits_after_in_array=None):
        """
        Convert value to string representation
        :param val: to convert to string representation. Most likely a Message.  ``Value``
        :param indent: indentation. If indent is set, then the return value will have a leading \n, ``str``
        :param time_offset: if not None, time fields will be displayed
          as deltas from  time_offset, ``Time``

        :param current_time: currently not used. Only provided for API
          compatibility. current_time passes in the current time with
          respect to the message, ``Time``
        :param field_filter: filter the fields that are strified for Messages, ``fn(Message)->iter(str)``
        :returns: string (YAML) representation of message, ``str``
        """
        type_ = type(val)
        if sys.version_info[0] <= 2:
            types = (int, long, float)
            types_wb = (int, long, float, bool)
        else:
            types = (int, float)
            types_wb = (int, float, bool)
        if type_ in types and fixed_numeric_width is not None:
            if type_ is float:
                return ('%.' + str(fixed_numeric_width) + 'f') % val
            else:
                return ('%d') % val
        elif type_ in types_wb:
            return utf8(val)
        elif isstring(val):
            # TODO: need to escape strings correctly
            if not val:
                return "''"
            return val
        elif isinstance(val, TVal):
            if time_offset is not None and isinstance(val, Time):
                val = val - time_offset
            if fixed_numeric_width is not None:
                format_str = '%d'
                sec_str = '\n%ssecs: ' % indent + (format_str % val.secs)
                nsec_str = '\n%snsecs: ' % indent + (format_str % val.nsecs)
                return sec_str + nsec_str
            else:
                return '\n%ssecs: %s\n%snsecs: %9d' % (indent, val.secs, indent, val.nsecs)

        elif type_ in (list, tuple):
            if len(val) == 0:
                return "[]"
            val0 = val[0]
            if type(val0) in (int, float) and digits_after_in_array is not None:
                list_str = '[' + ''.join(cls.strify_message(v, indent, time_offset, current_time, field_filter, digits_after_in_array) + ', ' for v in val).rstrip(', ') + ']'
                return list_str
            elif type(val0) in (int, float, str, bool):
                # TODO: escape strings properly
                return utf8(list(val))
            else:
                pref = indent + '- '
                indent = indent + '  '
                return '\n' + '\n'.join([pref + cls.strify_message(v, indent, time_offset, current_time, field_filter, digits_after_in_array) for v in val])
        elif isinstance(val, message.Message):
            # allow caller to select which fields of message are strified
            if field_filter is not None:
                fields = list(field_filter(val))
            else:
                fields = val.__slots__

            p = '%s%%s: %%s' % (indent)
            ni = '  ' + indent
            python_zip = None
            if sys.hexversion > 0x03000000:  # Python3
                python_zip = zip
            else:  # Python2
                python_zip = itertools.izip
            slots = []
            for f, t in python_zip(val.__slots__, val._slot_types):
                if f in fields:
                    cval = _convert_getattr(val, f, t)
                    slot_name = f
                    if isinstance(cval, (list, tuple)):
                        slot_name = "%s[%d]" % (f, len(cval))
                    slots.append(p % (utf8(slot_name), cls.strify_message(cval, ni, time_offset, current_time, field_filter, fixed_numeric_width)))
            vals = '\n'.join(slots)
            if indent:
                return '\n' + vals
            else:
                return vals
        else:
            return utf8(val)  # punt
Ejemplo n.º 16
0
 def value(self, value):
     self._value = value
     if isstring(value) and value.find('\n') > -1:
         self.setSizeHint(QSize(-1, 45))
Ejemplo n.º 17
0
 def __eq__(self, item):
     if isstring(item):
         return self.master.name.lower() == item.lower()
     elif not (item is None):
         return self.master.name.lower() == item.master.name.lower()
     return False