def __init__(self): local_uri = rosgraph.get_master_uri() foreign_uri = rospy.get_param('~foreign_master', '') if not foreign_uri: raise Exception('foreign_master URI not specified') local_pubs = rospy.get_param('~local_pubs', []) foreign_pubs = rospy.get_param('~foreign_pubs', []) self._local_services = rospy.get_param('~local_services', []) self._foreign_services = rospy.get_param('~foreign_services', []) foreign_master = rosgraph.Master(rospy.get_name(), master_uri=foreign_uri) r = rospy.Rate(1) while not _is_master_up(foreign_master) and not rospy.is_shutdown(): rospy.logdebug('Waiting for foreign master to come up...') r.sleep() self._local_manager = None self._foreign_manager = None if not rospy.is_shutdown(): self._local_manager = _RemoteManager(local_uri, self._local_publisher_update) self._foreign_manager = _RemoteManager(foreign_uri, self._foreign_publisher_update) for t in local_pubs: self._local_manager.subscribe(t) for t in foreign_pubs: self._foreign_manager.subscribe(t)
def start_node(environ, resolved_name, master_uri=None, port=None): """ Load ROS slave node, initialize from environment variables @param environ: environment variables @type environ: dict @param resolved_name: resolved node name @type resolved_name: str @param master_uri: override ROS_MASTER_URI: XMlRPC URI of central ROS server @type master_uri: str @param port: override ROS_PORT: port of slave xml-rpc node @type port: int @return: node server instance @rtype rosgraph.xmlrpc.XmlRpcNode @raise ROSInitException: if node has already been started """ init_tcpros() if not master_uri: master_uri = rosgraph.get_master_uri() if not master_uri: master_uri = DEFAULT_MASTER_URI # this will go away in future versions of API _set_caller_id(resolved_name) handler = ROSHandler(resolved_name, master_uri) node = rosgraph.xmlrpc.XmlRpcNode(port, handler, on_run_error=_node_run_error) node.start() while not node.uri and not is_shutdown(): time.sleep(0.00001) #poll for XMLRPC init logging.getLogger("rospy.init").info("ROS Slave URI: [%s]", node.uri) while not handler._is_registered() and not is_shutdown(): time.sleep(0.1) #poll for master registration logging.getLogger("rospy.init").info("registered with master") return node
def __init__(self): rospy.init_node("master_sync") self.local_service_names = rospy.get_param("~local_services", {}) self.local_pub_names = rospy.get_param("~local_pubs", []) self.foreign_service_names = rospy.get_param("~foreign_services", {}) self.foreign_pub_names = rospy.get_param("~foreign_pubs", []) # Get master URIs lm = rosgraph.get_master_uri() fm = rospy.get_param("~foreign_master", "http://localhost:11312") m = rosgraph.Master(rospy.get_name(), master_uri=fm) r = rospy.Rate(1) while not check_master(m) and not rospy.is_shutdown(): rospy.loginfo("Waiting for foreign master to come up...") r.sleep() self.local_manager = None self.foreign_manager = None if not rospy.is_shutdown(): self.local_manager = RemoteManager(lm, self.new_local_topics) self.foreign_manager = RemoteManager(fm, self.new_foreign_topics) for t in self.local_pub_names: self.local_manager.subscribe(t) for t in self.foreign_pub_names: self.foreign_manager.subscribe(t)
def testGetMasterUri(self): # test bad arity self.apiError(self.node.getMasterUri(self.caller_id, 'bad')) self.apiError(self.node.getMasterUri()) # test success uri = self.apiSuccess(self.node.getMasterUri(self.caller_id)) self._checkUri(uri) self.assertEquals(rosgraph.get_master_uri(), uri)
def _is_use_simtime(): # in order to prevent circular dependencies, this does not use the # builtin libraries for interacting with the parameter server, at least # until I reorganize the client vs. internal APIs better. master_uri = rosgraph.get_master_uri() m = rospy.core.xmlrpcapi(master_uri) code, msg, val = m.getParam(rospy.names.get_caller_id(), _USE_SIMTIME) if code == 1 and val: return True return False
def get_node_args(node_name, roslaunch_files): """ Get the node arguments for a node in roslaunch_files. @param node_name: name of node in roslaunch_files. @type node_name: str @param roslaunch_files: roslaunch file names @type roslaunch_files: [str] @return: list of command-line arguments used to launch node_name @rtype: [str] @raise RLException: if node args cannot be retrieved """ # we have to create our own XmlLoader so that we can use the same # resolution context for substitution args loader = roslaunch.xmlloader.XmlLoader(resolve_anon=False) config = load_config_default(roslaunch_files, None, loader=loader, verbose=False, assign_machines=False) (node_name) = substitution_args.resolve_args((node_name), resolve_anon=False) node_name = script_resolve_name("roslaunch", node_name) if not node_name.startswith("$") else node_name node = [n for n in config.nodes if _resolved_name(n) == node_name] + [ n for n in config.tests if _resolved_name(n) == node_name ] if not node: node_list = get_node_list(config) node_list_str = "\n".join([" * %s" % x for x in node_list]) raise RLException( "ERROR: Cannot find node named [%s] in [%s].\nNode names are:\n%s" % (node_name, ", ".join(roslaunch_files), node_list_str) ) elif len(node) > 1: raise RLException( "ERROR: multiple nodes named [%s] in [%s].\nPlease fix the launch files as duplicate names are not allowed." % (node_name, ", ".join(roslaunch_files)) ) node = node[0] master_uri = rosgraph.get_master_uri() machine = local_machine() env = setup_env(node, machine, master_uri) # remove setting identical to current environment for easier debugging to_remove = [] for k in env.iterkeys(): if env[k] == os.environ.get(k, None): to_remove.append(k) for k in to_remove: del env[k] # resolve node name for generating args args = create_local_process_args(node, machine) # join environment vars are bash prefix args return ["%s=%s" % (k, v) for k, v in env.iteritems()] + args
def _is_use_tcp_keepalive(): global _use_tcp_keepalive if _use_tcp_keepalive is not None: return _use_tcp_keepalive with _use_tcp_keepalive_lock: if _use_tcp_keepalive is not None: return _use_tcp_keepalive # in order to prevent circular dependencies, this does not use the # builtin libraries for interacting with the parameter server m = rospy.core.xmlrpcapi(rosgraph.get_master_uri()) code, msg, val = m.getParam(rospy.names.get_caller_id(), _PARAM_TCP_KEEPALIVE) _use_tcp_keepalive = val if code == 1 else True return _use_tcp_keepalive
def validate_master_launch(m, is_core, is_rostest=False): """ Validate the configuration of a master we are about to launch. Ths validation already assumes that no existing master is running at this configuration and merely checks configuration for a new launch. """ # Before starting a master, we do some sanity check on the # master configuration. There are two ways the user starts: # roscore or roslaunch. If the user types roscore, we always # will start a core if possible, but we warn about potential # misconfigurations. If the user types roslaunch, we will # auto-start a new master if it is achievable, i.e. if the # master is local. if not rosgraph.network.is_local_address(m.get_host()): # The network configuration says that the intended # hostname is not local, so... if is_core: # ...user is expecting to start a new master. Thus, we # only warn if network configuration appears # non-local. try: reverse_ips = [host[4][0] for host in socket.getaddrinfo(m.get_host(), 0, 0, 0, socket.SOL_TCP)] local_addrs = rosgraph.network.get_local_addresses() printerrlog("""WARNING: IP addresses %s for local hostname '%s' do not appear to match any local IP address (%s). Your ROS nodes may fail to communicate. Please use ROS_IP to set the correct IP address to use."""%(','.join(reverse_ips), m.get_host(), ','.join(local_addrs))) except: printerrlog("""WARNING: local hostname '%s' does not map to an IP address. Your ROS nodes may fail to communicate. Please use ROS_IP to set the correct IP address to use."""%(m.get_host())) else: # ... the remote master cannot be contacted, so we fail. #3097 raise RLException("ERROR: unable to contact ROS master at [%s]"%(m.uri)) if is_core and not is_rostest: # User wants to start a master, and our configuration does # point to the local host, and we're not running as rostest. env_uri = rosgraph.get_master_uri() env_host, env_port = rosgraph.network.parse_http_host_and_port(env_uri) if not rosgraph.network.is_local_address(env_host): # The ROS_MASTER_URI points to a different machine, warn user printerrlog("WARNING: ROS_MASTER_URI [%s] host is not set to this machine"%(env_uri)) elif env_port != m.get_port(): # The ROS_MASTER_URI points to a master on a different port, warn user printerrlog("WARNING: ROS_MASTER_URI port [%s] does not match this roscore [%s]"%(env_port, m.get_port()))
def get_master(): """ Get an XMLRPC handle to the Master. It is recommended to use the `rosgraph.masterapi` library instead, as it provides many conveniences. @return: XML-RPC proxy to ROS master @rtype: xmlrpclib.ServerProxy """ try: import xmlrpc.client as xmlrpcclient #Python 3.x except ImportError: import xmlrpclib as xmlrpcclient #Python 2.x uri = rosgraph.get_master_uri() return xmlrpcclient.ServerProxy(uri)
def get_master(env=os.environ): """ Get a remote handle to the ROS Master. This method can be called independent of running a ROS node, though the ROS_MASTER_URI must be declared in the environment. @return: ROS Master remote object @rtype: L{rospy.MasterProxy} @raise Exception: if server cannot be located or system cannot be initialized """ global _master_proxy if _master_proxy is not None: return _master_proxy _master_proxy = rospy.msproxy.MasterProxy(rosgraph.get_master_uri()) return _master_proxy
def get_ros_ip(self): o = urlparse.urlparse(rosgraph.get_master_uri()) if o.hostname == 'localhost': ros_ip = '' try: ros_ip = os.environ['ROS_IP'] except Exception: try: # often people use this one instead ros_ip = os.environ['ROS_HOSTNAME'] except Exception: # should probably check other means here - e.g. first of the system ipconfig rospy.logwarn( "Gateway : no valid ip found for this host, just setting 'localhost'" ) return 'localhost' return ros_ip else: return o.hostname
def start_node(environ, resolved_name, master_uri=None, port=0, tcpros_port=0): """ Load ROS slave node, initialize from environment variables @param environ: environment variables @type environ: dict @param resolved_name: resolved node name @type resolved_name: str @param master_uri: override ROS_MASTER_URI: XMlRPC URI of central ROS server @type master_uri: str @param port: override ROS_PORT: port of slave xml-rpc node @type port: int @param tcpros_port: override the port of the TCP server @type tcpros_port: int @return: node server instance @rtype rosgraph.xmlrpc.XmlRpcNode @raise ROSInitException: if node has already been started """ init_tcpros(tcpros_port) if not master_uri: master_uri = rosgraph.get_master_uri() if not master_uri: master_uri = DEFAULT_MASTER_URI # this will go away in future versions of API _set_caller_id(resolved_name) handler = ROSHandler(resolved_name, master_uri) node = rosgraph.xmlrpc.XmlRpcNode(port, handler, on_run_error=_node_run_error) node.start() while not node.uri and not is_shutdown(): time.sleep(0.00001) #poll for XMLRPC init logging.getLogger("rospy.init").info("ROS Slave URI: [%s]", node.uri) #changed set_node_handler(handler) set_broadcast_manager(BroadcastManager()) #get_broadcast_manager().requestParam() #changed while not handler._is_registered() and not is_shutdown(): time.sleep(0.1) #poll for master registration logging.getLogger("rospy.init").info("registered with master") return node
def configure_external(self): # Start another TCPROSServer to handle requests on the external port # - TODO: allow handlers these to be passed into TCPROSServer constructor self.external_tcpros = external_tcpros = TCPROSServer() tcpros_handler = rosproxy.tcpros.ProxyTCPROSHandler( self.topic_manager, external_tcpros) self._configure_proxy_services(external_tcpros) self._configure_proxy_topics(external_tcpros, tcpros_handler) tcpros_port = rospy.get_param('~tcpros_port', 11312) xmlrpc_port = rospy.get_param('~xmlrpc_port', 11313) rospy.loginfo("reading port configuration: TCPROS[%s] XMLRPC[%s]" % (tcpros_port, xmlrpc_port)) external_tcpros.start_server(port=tcpros_port) # TODO: this may report the address of the wrong interface rospy.loginfo("ROSRPC URI is rosrpc://%s:%s" % (rosgraph.network.get_local_address(), tcpros_port)) # Startup XMLRPC interface so we can do pub/sub master_uri = rosgraph.get_master_uri() name = 'proxy-proxy' protocol_handlers = [tcpros_handler] rpc_handler = rosproxy.handler.ProxyHandler(name, master_uri, self.topic_manager, protocol_handlers) self.external_node = external_node = XmlRpcNode( xmlrpc_port, rpc_handler) # - start the node and wait for init external_node.start() import time timeout_t = time.time() + 10. while time.time() < timeout_t and external_node.uri is None: time.sleep(0.01) rospy.loginfo("XMLRPC interface is up %s" % self.external_node.uri)
def __init__(self, foreign_master, local_service_names = [], local_pub_names = [], foreign_service_names = [], foreign_pub_names = []): self.local_service_names = local_service_names self.local_pub_names = local_pub_names self.foreign_service_names = foreign_service_names self.foreign_pub_names = foreign_pub_names self.local_manager = None self.foreign_manager = None self.stopping = False self.thread = None # Get master URIs local_master = rosgraph.get_master_uri() m = rosgraph.Master(rospy.get_name(), master_uri=foreign_master) r = rospy.Rate(1) rospy.loginfo("App Manager: waiting for foreign master [%s] to come up..."%(foreign_master)) while not check_master(m) and not rospy.is_shutdown(): r.sleep() if not rospy.is_shutdown(): rospy.loginfo("App Manager: foreign master is available") self.local_manager = RemoteManager(local_master, self.new_local_topics) self.foreign_manager = RemoteManager(foreign_master, self.new_foreign_topics) for t in self.local_pub_names: self.local_manager.subscribe(t) for t in self.foreign_pub_names: self.foreign_manager.subscribe(t) self.thread = threading.Thread(target=self.spin) self.thread.start() else: rospy.loginfo("shutdown flag raised, aborting...")
def __init__(self, foreign_master, local_service_names = [], local_pub_names = [], foreign_service_names = [], foreign_pub_names = []): self.local_service_names = local_service_names self.local_pub_names = local_pub_names self.foreign_service_names = foreign_service_names self.foreign_pub_names = foreign_pub_names self.local_manager = None self.foreign_manager = None self.stopping = False self.thread = None # Get master URIs local_master = rosgraph.get_master_uri() m = rosgraph.Master(rospy.get_name(), master_uri=foreign_master) r = rospy.Rate(1) rospy.loginfo("Waiting for foreign master [%s] to come up..."%(foreign_master)) while not check_master(m) and not rospy.is_shutdown(): r.sleep() if not rospy.is_shutdown(): rospy.loginfo("Foreign master is available") self.local_manager = RemoteManager(local_master, self.new_local_topics) self.foreign_manager = RemoteManager(foreign_master, self.new_foreign_topics) for t in self.local_pub_names: self.local_manager.subscribe(t) for t in self.foreign_pub_names: self.foreign_manager.subscribe(t) self.thread = threading.Thread(target=self.spin) self.thread.start() else: rospy.loginfo("shutdown flag raised, aborting...")
def configure_external(self): # Start another TCPROSServer to handle requests on the external port # - TODO: allow handlers these to be passed into TCPROSServer constructor self.external_tcpros = external_tcpros = TCPROSServer() tcpros_handler = rosproxy.tcpros.ProxyTCPROSHandler(self.topic_manager, external_tcpros) self._configure_proxy_services(external_tcpros) self._configure_proxy_topics(external_tcpros, tcpros_handler) tcpros_port = rospy.get_param('~tcpros_port', 11312) xmlrpc_port = rospy.get_param('~xmlrpc_port', 11313) rospy.loginfo("reading port configuration: TCPROS[%s] XMLRPC[%s]"%(tcpros_port, xmlrpc_port)) external_tcpros.start_server(port=tcpros_port) # TODO: this may report the address of the wrong interface rospy.loginfo("ROSRPC URI is rosrpc://%s:%s"%(rosgraph.network.get_local_address(), tcpros_port)) # Startup XMLRPC interface so we can do pub/sub master_uri = rosgraph.get_master_uri() name = 'proxy-proxy' protocol_handlers = [tcpros_handler] rpc_handler = rosproxy.handler.ProxyHandler(name, master_uri, self.topic_manager, protocol_handlers) self.external_node = external_node= XmlRpcNode(xmlrpc_port, rpc_handler) # - start the node and wait for init external_node.start() import time timeout_t = time.time() + 10. while time.time() < timeout_t and external_node.uri is None: time.sleep(0.01) rospy.loginfo("XMLRPC interface is up %s"%self.external_node.uri)
def test_getMasterUri(self): """ validate node.getMasterUri(caller_id) """ # test success uri = self.apiSuccess(self.node.getMasterUri(self.caller_id)) self.check_uri(uri) # check against env, canonicalize for comparison import urlparse master_env = rosgraph.get_master_uri() if not master_env.endswith('/'): master_env = master_env + '/' self.assertEquals(urlparse.urlparse(master_env), urlparse.urlparse(uri)) # test bad arity try: self.apiError(self.node.getMasterUri(self.caller_id, 'bad')) except Fault: pass try: self.apiError(self.node.getMasterUri()) except Fault: pass
def setUp(self): self.last_code = None self.last_msg = None self.last_val = None self.master = ServerProxy(rosgraph.get_master_uri())
#!/usr/bin/env python import rospy import rosgraph master_uri = rosgraph.get_master_uri() print("masteruri") print(master_uri) rospy.init_node("test") print("done init node")
#!/usr/bin/env python import roslib; roslib.load_manifest('app_manager_android') import rosgraph import rosgraph.network import pyqrnative import urlparse urlp = urlparse.urlparse(rosgraph.get_master_uri()) address = rosgraph.network.get_local_address() text = "http://%s:%s"%(address, urlp.port) print text pyqrnative.show_data(text)
def get_node_args(node_name, roslaunch_files): """ Get the node arguments for a node in roslaunch_files. @param node_name: name of node in roslaunch_files. @type node_name: str @param roslaunch_files: roslaunch file names @type roslaunch_files: [str] @return: list of command-line arguments used to launch node_name @rtype: [str] @raise RLException: if node args cannot be retrieved """ # we have to create our own XmlLoader so that we can use the same # resolution context for substitution args loader = roslaunch.xmlloader.XmlLoader(resolve_anon=False) config = load_config_default(roslaunch_files, None, loader=loader, verbose=False, assign_machines=False) (node_name) = substitution_args.resolve_args((node_name), resolve_anon=False) node_name = script_resolve_name( 'roslaunch', node_name) if not node_name.startswith('$') else node_name node = [n for n in config.nodes if _resolved_name(n) == node_name] + \ [n for n in config.tests if _resolved_name(n) == node_name] if not node: node_list = get_node_list(config) node_list_str = '\n'.join([" * %s" % x for x in node_list]) raise RLException( "ERROR: Cannot find node named [%s] in [%s].\nNode names are:\n%s" % (node_name, ', '.join(roslaunch_files), node_list_str)) elif len(node) > 1: raise RLException( "ERROR: multiple nodes named [%s] in [%s].\nPlease fix the launch files as duplicate names are not allowed." % (node_name, ', '.join(roslaunch_files))) node = node[0] master_uri = rosgraph.get_master_uri() machine = local_machine() env = setup_env(node, machine, master_uri) # remove setting identical to current environment for easier debugging to_remove = [] for k in env.keys(): if env[k] == os.environ.get(k, None): to_remove.append(k) for k in to_remove: del env[k] # resolve node name for generating args args = create_local_process_args(node, machine) if sys.platform == "win32": # set command can be used with environment variables that contain space without double quotes # https://ss64.com/nt/set.html return ["set %s=%s&&" % (k, v) for k, v in env.items()] + args else: # sys.platform.startswith('linux') # join environment vars are bash prefix args, wrap with double quotes for variables that contains space return ['%s="%s"' % (k, v) for k, v in env.items()] + args
def validate_master_launch(m, is_core, is_rostest=False): """ Validate the configuration of a master we are about to launch. Ths validation already assumes that no existing master is running at this configuration and merely checks configuration for a new launch. """ # Before starting a master, we do some sanity check on the # master configuration. There are two ways the user starts: # roscore or roslaunch. If the user types roscore, we always # will start a core if possible, but we warn about potential # misconfigurations. If the user types roslaunch, we will # auto-start a new master if it is achievable, i.e. if the # master is local. if not rosgraph.network.is_local_address(m.get_host()): # The network configuration says that the intended # hostname is not local, so... if is_core: # ...user is expecting to start a new master. Thus, we # only warn if network configuration appears # non-local. try: reverse_ips = [ host[4][0] for host in socket.getaddrinfo( m.get_host(), 0, 0, 0, socket.SOL_TCP) ] local_addrs = rosgraph.network.get_local_addresses() printerrlog( """WARNING: IP addresses %s for local hostname '%s' do not appear to match any local IP address (%s). Your ROS nodes may fail to communicate. Please use ROS_IP to set the correct IP address to use.""" % (','.join(reverse_ips), m.get_host(), ','.join(local_addrs))) except: printerrlog( """WARNING: local hostname '%s' does not map to an IP address. Your ROS nodes may fail to communicate. Please use ROS_IP to set the correct IP address to use.""" % (m.get_host())) else: # ... the remote master cannot be contacted, so we fail. #3097 raise RLException("ERROR: unable to contact ROS master at [%s]" % (m.uri)) if is_core and not is_rostest: # User wants to start a master, and our configuration does # point to the local host, and we're not running as rostest. env_uri = rosgraph.get_master_uri() env_host, env_port = rosgraph.network.parse_http_host_and_port(env_uri) if not rosgraph.network.is_local_address(env_host): # The ROS_MASTER_URI points to a different machine, warn user printerrlog( "WARNING: ROS_MASTER_URI [%s] host is not set to this machine" % (env_uri)) elif env_port != m.get_port(): # The ROS_MASTER_URI points to a master on a different port, warn user printerrlog( "WARNING: ROS_MASTER_URI port [%s] does not match this roscore [%s]" % (env_port, m.get_port()))
#!/usr/bin/env python import roslib roslib.load_manifest("app_manager_android") import rosgraph import rosgraph.network import pyqrnative import urlparse urlp = urlparse.urlparse(rosgraph.get_master_uri()) address = rosgraph.network.get_local_address() text = "http://%s:%s" % (address, urlp.port) print text pyqrnative.show_data(text)