1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 """rospy internal core implementation library"""
36
37
38
39 import atexit
40 import logging
41 import os
42 import signal
43 import sys
44 import threading
45 import time
46 import traceback
47 import types
48
49 try:
50 import urllib.parse as urlparse
51 except ImportError:
52 import urlparse
53
54 try:
55 import xmlrpc.client as xmlrpcclient
56 except ImportError:
57 import xmlrpclib as xmlrpcclient
58
59 import rospkg
60
61 import rosgraph.roslogging
62
63 import rospy.exceptions
64 import rospy.rostime
65
66 from rospy.names import *
67 from rospy.impl.validators import ParameterInvalid
68
69 from rosgraph_msgs.msg import Log
70
71 _logger = logging.getLogger("rospy.core")
72
73
74
75
76 _TIMEOUT_SHUTDOWN_JOIN = 5.
77
78 import warnings
80 """This is a decorator which can be used to mark functions
81 as deprecated. It will result in a warning being emmitted
82 when the function is used."""
83 def newFunc(*args, **kwargs):
84 warnings.warn("Call to deprecated function %s." % func.__name__,
85 category=DeprecationWarning, stacklevel=2)
86 return func(*args, **kwargs)
87 newFunc.__name__ = func.__name__
88 newFunc.__doc__ = func.__doc__
89 newFunc.__dict__.update(func.__dict__)
90 return newFunc
91
92
93
94
95 ROSRPC = "rosrpc://"
98 """
99 utility function for parsing ROS-RPC URIs
100 @param uri: ROSRPC URI
101 @type uri: str
102 @return: address, port
103 @rtype: (str, int)
104 @raise ParameterInvalid: if uri is not a valid ROSRPC URI
105 """
106 if uri.startswith(ROSRPC):
107 dest_addr = uri[len(ROSRPC):]
108 else:
109 raise ParameterInvalid("Invalid protocol for ROS service URL: %s"%uri)
110 try:
111 if '/' in dest_addr:
112 dest_addr = dest_addr[:dest_addr.find('/')]
113 dest_addr, dest_port = dest_addr.split(':')
114 dest_port = int(dest_port)
115 except:
116 raise ParameterInvalid("ROS service URL is invalid: %s"%uri)
117 return dest_addr, dest_port
118
119
120
121
122 _rospy_logger = logging.getLogger("rospy.internal")
129 """Internal rospy client library debug logging"""
130 _rospy_logger.debug(msg, *args)
132 """Internal rospy client library debug logging"""
133 _rospy_logger.info(msg, *args)
135 """Internal rospy client library error logging"""
136 _rospy_logger.error(msg, *args)
138 """Internal rospy client library warn logging"""
139 _rospy_logger.warn(msg, *args)
140
141 logdebug = logging.getLogger('rosout').debug
142
143 logwarn = logging.getLogger('rosout').warning
144
145 loginfo = logging.getLogger('rosout').info
146 logout = loginfo
147
148 logerr = logging.getLogger('rosout').error
149 logerror = logerr
150
151 logfatal = logging.getLogger('rosout').critical
152
153
154
155
156 MASTER_NAME = "master"
157
158 import warnings
160 """This is a decorator which can be used to mark functions
161 as deprecated. It will result in a warning being emmitted
162 when the function is used."""
163 def newFunc(*args, **kwargs):
164 warnings.warn("Call to deprecated function %s." % func.__name__,
165 category=DeprecationWarning, stacklevel=2)
166 return func(*args, **kwargs)
167 newFunc.__name__ = func.__name__
168 newFunc.__doc__ = func.__doc__
169 newFunc.__dict__.update(func.__dict__)
170 return newFunc
171
174 """
175 Get the value of ROS_ROOT.
176 @param env: override environment dictionary
177 @type env: dict
178 @param required: if True, fails with ROSException
179 @return: Value of ROS_ROOT environment
180 @rtype: str
181 @raise ROSException: if require is True and ROS_ROOT is not set
182 """
183 if env is None:
184 env = os.environ
185 ros_root = rospkg.get_ros_root(env)
186 if required and not ros_root:
187 raise rospy.exceptions.ROSException('%s is not set'%rospkg.environment.ROS_ROOT)
188 return ros_root
189
190
191
192
193
194 _uri = None
196 """
197 Get this Node's URI.
198 @return: this Node's XMLRPC URI
199 @rtype: str
200 """
201 return _uri
202
204 """set the URI of the local node.
205 This is an internal API method, it does not actually affect the XMLRPC URI of the Node."""
206 global _uri
207 _uri = uri
208
209
210
211
212 _log_filename = None
236
238 - def emit(self, record):
240
241
242 logging.getLogger('rospy').addHandler(NullHandler())
243
244
245
246
247
248 _client_ready = False
252 """
253 Get the initialization state of the local node. If True, node has
254 been configured.
255 @return: True if local node initialized
256 @rtype: bool
257 """
258 return _client_ready
260 """
261 set the initialization state of the local node
262 @param initialized: True if node initialized
263 @type initialized: bool
264 """
265 global _client_ready
266 _client_ready = initialized
267
268 _shutdown_lock = threading.RLock()
269
270
271
272
273
274 _shutdown_flag = False
275 _in_shutdown = False
276
277
278
279
280 _shutdown_hooks = []
281 _preshutdown_hooks = []
282 _client_shutdown_hooks = []
283
284 _shutdown_threads = []
285
286 _signalChain = {}
289 """
290 @return: True if shutdown flag has been set
291 @rtype: bool
292 """
293 return _shutdown_flag
294
296 """
297 is_shutdown_requested is a state that occurs just before
298 is_shutdown. It is initiated when a shutdown requested is
299 received and continues until client shutdown handlers have been
300 called. After client shutdown handlers have been serviced, the
301 is_shutdown state becomes true.
302
303 @return: True if shutdown has been requested (but possibly not yet initiated)
304 @rtype: bool
305 """
306 return _in_shutdown
307
309 """
310 shared implementation of add_shutdown_hook and add_preshutdown_hook
311 """
312 if type(h) not in [types.FunctionType, types.MethodType]:
313 raise TypeError("shutdown hook [%s] must be a function: %s"%(h, type(h)))
314 if _shutdown_flag:
315 _logger.warn("add_shutdown_hook called after shutdown")
316 h("already shutdown")
317 return
318 with _shutdown_lock:
319 if hooks is None:
320
321 return
322 hooks.append(h)
323
342
344 """
345 Add client method to invoke when system shuts down. Unlike
346 L{add_shutdown_hook} and L{add_preshutdown_hooks}, these methods
347 will be called before any rospy internal shutdown code.
348
349 @param h: function that takes in a single string argument (shutdown reason)
350 @type h: fn(str)
351 """
352 _add_shutdown_hook(h, _client_shutdown_hooks)
353
355 """
356 Add method to invoke when system shuts down. Unlike
357 L{add_shutdown_hook}, these methods will be called before any
358 other shutdown hooks.
359
360 @param h: function that takes in a single string argument (shutdown reason)
361 @type h: fn(str)
362 """
363 _add_shutdown_hook(h, _preshutdown_hooks)
364
366 """
367 Add method to invoke when system shuts down.
368
369 Shutdown hooks are called in the order that they are
370 registered. This is an internal API method that is used to
371 cleanup. See the client X{on_shutdown()} method if you wish to
372 register client hooks.
373
374 @param h: function that takes in a single string argument (shutdown reason)
375 @type h: fn(str)
376 """
377 _add_shutdown_hook(h, _shutdown_hooks)
378
431
433 signal_shutdown("signal-"+str(sig))
434 prev_handler = _signalChain.get(sig, None)
435 if prev_handler is not None and not type(prev_handler) == int:
436 try:
437 prev_handler(sig, stackframe)
438 except KeyboardInterrupt:
439 pass
440
443 atexit.register(_ros_atexit)
447 """
448 register system signal handlers for SIGTERM and SIGINT
449 """
450 _signalChain[signal.SIGTERM] = signal.signal(signal.SIGTERM, _ros_signal)
451 _signalChain[signal.SIGINT] = signal.signal(signal.SIGINT, _ros_signal)
452
456 """
457 Validator that checks that parameter is a valid ROS topic name
458 """
459 def validator(param_value, caller_id):
460 v = valid_name_validator_resolved(param_name, param_value, caller_id)
461 if param_value == '/':
462 raise ParameterInvalid("ERROR: parameter [%s] cannot be the global namespace"%param_name)
463 return v
464 return validator
465
467 """
468 @return: instance for calling remote server or None if not a valid URI
469 @rtype: xmlrpclib.ServerProxy
470 """
471 if uri is None:
472 return None
473 uriValidate = urlparse.urlparse(uri)
474 if not uriValidate[0] or not uriValidate[1]:
475 return None
476 return xmlrpcclient.ServerProxy(uri)
477