repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/ros_comm/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package ros_comm ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- 1.11.10 (2014-12-22) -------------------- 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- 1.11.0 (2014-03-04) ------------------- 1.10.0 (2014-02-11) ------------------- 1.9.54 (2014-01-27) ------------------- 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- 1.9.50 (2013-10-04) ------------------- 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- 1.9.47 (2013-07-03) ------------------- 1.9.46 (2013-06-18) ------------------- * add dependency on roslisp (`#240 <https://github.com/ros/ros_comm/issues/240>`_) 1.9.45 (2013-06-06) ------------------- 1.9.44 (2013-03-21) ------------------- 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(rosparam) find_package(catkin REQUIRED) catkin_package() catkin_python_setup()
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/package.xml
<package> <name>rosparam</name> <version>1.11.21</version> <description> rosparam contains the rosparam command-line tool for getting and setting ROS Parameters on the <a href="http://www.ros.org/wiki/Parameter%20Server">Parameter Server</a> using YAML-encoded files. It also contains an experimental library for using YAML with the Parameter Server. This library is intended for internal use only. rosparam can be invoked within a <a href="http://www.ros.org/wiki/roslaunch">roslaunch</a> file. </description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>BSD</license> <url>http://ros.org/wiki/rosparam</url> <author>Ken Conley</author> <buildtool_depend>catkin</buildtool_depend> <run_depend>python-yaml</run_depend> <run_depend>rosgraph</run_depend> <export> <rosdoc config="rosdoc.yaml"/> <architecture_independent/> </export> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/example.yaml
string1: bar string2: !!str 10 preformattedtext: | This is the first line This is the second line Line breaks are preserved Indentation is stripped list1: - head - shoulders - knees - toes list2: [1, 1, 2, 3, 5, 8] dict1: { head: 1, shoulders: 2, knees: 3, toes: 4} integer1: 1 integer2: 2 float1: 3.14159 float2: 1.2345e+3 robots: childparam: a child namespace parameter child: grandchildparam: a grandchild namespace param
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/rosdoc.yaml
- builder: epydoc config: epydoc.config
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/setup.py
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosparam'], package_dir={'': 'src'}, scripts=['scripts/rosparam'] ) setup(**d)
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosparam/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-rosparam-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package rosparam ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- * add support for loading parameters from stdin as well as dumping rosparam to stdout (`#686 <https://github.com/ros/ros_comm/pull/686>`_) 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- 1.11.10 (2014-12-22) -------------------- 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- * Python 3 compatibility (`#427 <https://github.com/ros/ros_comm/issues/427>`_) 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- * add architecture_independent flag in package.xml (`#391 <https://github.com/ros/ros_comm/issues/391>`_) 1.11.0 (2014-03-04) ------------------- 1.10.0 (2014-02-11) ------------------- 1.9.54 (2014-01-27) ------------------- 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- 1.9.50 (2013-10-04) ------------------- 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- * prevent stack trace for 'rosparam get/delete' when parameter does not exist (`#265 <https://github.com/ros/ros_comm/issues/265>`_) 1.9.47 (2013-07-03) ------------------- 1.9.46 (2013-06-18) ------------------- 1.9.45 (2013-06-06) ------------------- 1.9.44 (2013-03-21) ------------------- 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/epydoc.config
[epydoc] name: rosparam modules: rosparam inheritance: included url: http://ros.org/wiki/rosparam frames: no private: no
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/scripts/rosparam
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import rosparam rosparam.yamlmain()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosparam/src/rosparam/__init__.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id: rosparam 1641 2008-07-28 21:39:33Z sfkwc $ """ Implementation of the rosparam as well as a library for modifying the state of the ROS Parameter Server using YAML files. """ from __future__ import print_function NAME = 'rosparam' ## namespace key. Use of this in a YAML document specifies the ## namespace of all the params. NOTE: phasing out most use of this ## key. It's still useful in corner cases, but most of its ## functionality can be achieved with command-line arguments. NS = '_ns' import base64 import math import os import re import sys import socket try: from xmlrpc.client import Binary except ImportError: from xmlrpclib import Binary from optparse import OptionParser import yaml import rosgraph from rosgraph.names import script_resolve_name, ns_join, get_ros_namespace, make_caller_id, make_global_ns, GLOBALNS class RosParamException(Exception): """ rosparam base exception type """ pass class RosParamIOException(RosParamException): """ Exception for communication-based (i/o) errors. """ pass # pyyaml customizations for binary and angle data def represent_xml_binary(loader, data): """ Adds a pyyaml serializer to handle xmlrpclib.Binary objects """ data = base64.b64encode(data.data) return loader.represent_scalar(u'tag:yaml.org,2002:binary', data, style='|') def represent_foo(loader, data): return loader.represent_scalar(u'#', data) def construct_yaml_binary(loader, node): """ Overrides pyaml's constructor for binary data. Wraps binary data in xmlrpclib.Binary container instead of straight string representation. """ return Binary(loader.construct_yaml_binary(node)) # register the (de)serializers with pyyaml yaml.add_representer(Binary,represent_xml_binary) yaml.add_constructor(u'tag:yaml.org,2002:binary', construct_yaml_binary) def construct_angle_radians(loader, node): """ python-yaml utility for converting rad(num) into float value """ value = loader.construct_scalar(node).strip() exprvalue = value.replace('pi', 'math.pi') if exprvalue.startswith("rad("): exprvalue = exprvalue[4:-1] try: return float(eval(exprvalue)) except SyntaxError as e: raise RosParamException("invalid radian expression: %s"%value) def construct_angle_degrees(loader, node): """ python-yaml utility for converting deg(num) into float value """ value = loader.construct_scalar(node) exprvalue = value if exprvalue.startswith("deg("): exprvalue = exprvalue.strip()[4:-1] try: return float(exprvalue) * math.pi / 180.0 except ValueError: raise RosParamException("invalid degree value: %s"%value) # utilities def _get_caller_id(): """ :returns: caller ID for rosparam ROS client calls, ``str`` """ return make_caller_id('rosparam-%s'%os.getpid()) def print_params(params, ns): """ Print contents of param dictionary to screen """ if type(params) == dict: for k, v in params.items(): if type(v) == dict: print_params(v, ns_join(ns, k)) else: print("%s=%s"%(ns_join(ns, k), v)) else: print(params) # yaml processing def load_file(filename, default_namespace=None, verbose=False): """ Load the YAML document from the specified file :param filename: name of filename, ``str`` :param default_namespace: namespace to load filename into, ``str`` :returns [(dict, str)...]: list of parameter dictionary and corresponding namespaces for each YAML document in the file :raises: :exc:`RosParamException`: if unable to load contents of filename """ if not filename or filename == '-': f = sys.stdin if verbose: print("reading parameters from stdin") return load_str(f.read(), filename, default_namespace=default_namespace, verbose=verbose) else: if not os.path.isfile(filename): raise RosParamException("file [%s] does not exist"%filename) if verbose: print("reading parameters from [%s]"%filename) with open(filename, 'r') as f: return load_str(f.read(), filename, default_namespace=default_namespace, verbose=verbose) def load_str(str, filename, default_namespace=None, verbose=False): """ Load the YAML document as a string :param filename: name of filename, only used for debugging, ``str`` :param default_namespace: namespace to load filename into, ``str`` :param str: YAML text, ``str`` :returns: list of parameter dictionary and corresponding namespaces for each YAML document in the file, ``[(dict, str)...]`` """ paramlist = [] default_namespace = default_namespace or get_ros_namespace() for doc in yaml.load_all(str): if NS in doc: ns = ns_join(default_namespace, doc.get(NS, None)) if verbose: print("reading parameters into namespace [%s]"%ns) del doc[NS] else: ns = default_namespace paramlist.append((doc, ns)) return paramlist # DUMP/GET def get_param_server(): return rosgraph.Master(_get_caller_id()) def get_param(param): """ Download a parameter from Parameter Server :param param: parameter name to retrieve from parameter server. If param is a parameter namespace, entire parameter subtree will be downloaded, ``str`` """ try: return get_param_server().getParam(param) except socket.error: raise RosParamIOException("Unable to communicate with master!") # #698 def _pretty_print(value, indent=''): """ Pretty print get value :param value: value to print :param indent: indent level, used for recursive calls, ``str`` """ keys = list(value.keys()) keys.sort() for k in keys: v = value[k] if type(v) == dict: print("%s%s:"%(indent, k)) _pretty_print(v, indent+' ') elif type(v) == str: if '\n' in v: print(indent+'%s: |'%k) for l in v.split('\n'): print(indent+' '+l) else: print("%s%s: %s"%(indent, k, v)) else: dump = yaml.dump(v) # #1617 # newer versions of python-yaml append the '...' document end # syntax. as YAML functions fine w/o it, and as it is # confusing to users who are just getting a single scalar, we # strip it if dump.endswith('\n...\n'): dump = dump[:-4] sys.stdout.write("%s%s: %s"%(indent, k, dump)) def _rosparam_cmd_get_param(param, pretty=False, verbose=False): """ Download a parameter tree and print to screen :param param: parameter name to retrieve from Parameter Server. If param is a parameter namespace, entire parameter subtree will be downloaded, ``str`` """ # yaml.dump has a \n at the end, so use stdout.write instead of print if verbose: print("getting parameter [%s]"%param) try: val = get_param(param) except rosgraph.masterapi.Error as e: raise RosParamException(str(e)) if pretty and type(val) in [dict, str]: if type(val) == dict: _pretty_print(val) else: if '\n' in val: print('|') for l in val.split('\n'): print(' '+l) else: print(val) else: dump = yaml.dump(val) # #1617 # newer versions of python-yaml append the '...' document end # syntax. as YAML functions fine w/o it, and as it is # confusing to users who are just getting a single scalar, we # strip it if dump.endswith('\n...\n'): dump = dump[:-5] # #3761 add newline in output sys.stdout.write("%s\n"%(dump)) def dump_params(filename, param, verbose=False): """ Download a parameter tree from the Parameter Server and store in a yaml file :param filename: name of file to save YAML representation, ``str`` :param param: name of parameter/namespace to dump, ``str`` :param verbose: print verbose output for debugging, ``bool`` """ tree = get_param(param) if verbose: print_params(tree, param) if not filename: f = sys.stdout yaml.dump(tree, f) else: f = open(filename, 'w') try: yaml.dump(tree, f) finally: f.close() def delete_param(param, verbose=False): """ Delete a parameter from the Parameter Server :param param: parameter name, ``str`` :param verbose: print verbose output for debugging, ``bool`` """ try: if param == GLOBALNS: # not allowed to delete the root of the tree as it must always # have a value. the equivalent command is setting the root to an # empty dictionary get_param_server().setParam(GLOBALNS, {}) if verbose: print("deleted ENTIRE parameter server") else: get_param_server().deleteParam(param) if verbose: print("deleted parameter [%s]"%param) except socket.error: raise RosParamIOException("Unable to communicate with master!") # LOAD/SET def set_param_raw(param, value, verbose=False): """ Set param on the Parameter Server. Unlike L{set_param()}, this takes in a Python value to set instead of YAML. :param param: parameter name, ``str`` :param value XmlRpcLegalValue: value to upload, ``XmlRpcLegalValue`` """ if type(value) == dict: # #1098 changing dictionary behavior to be an update, rather # than replace behavior. for k, v in value.items(): # dictionary keys must be non-unicode strings if isinstance(k, str): set_param_raw(ns_join(param, k), v, verbose=verbose) else: raise RosParamException("YAML dictionaries must have string keys. Invalid dictionary is:\n%s"%value) else: try: expected_type = long except NameError : expected_type = int if type(value) == expected_type: if value > sys.maxsize: raise RosParamException("Overflow: Parameter Server integers must be 32-bit signed integers:\n\t-%s <= value <= %s"%(maxint - 1, maxint)) try: get_param_server().setParam(param, value) except socket.error: raise RosParamIOException("Unable to communicate with master!") if verbose: print("set parameter [%s] to [%s]"%(param, value)) def set_param(param, value, verbose=False): """ Set param on the ROS parameter server using a YAML value. :param param: parameter name, ``str`` :param value: yaml-encoded value, ``str`` """ set_param_raw(param, yaml.load(value), verbose=verbose) def upload_params(ns, values, verbose=False): """ Upload params to the Parameter Server :param values: key/value dictionary, where keys are parameter names and values are parameter values, ``dict`` :param ns: namespace to load parameters into, ``str`` """ if ns == '/' and not type(values) == dict: raise RosParamException("global / can only be set to a dictionary") if verbose: print_params(values, ns) set_param_raw(ns, values) # LIST def list_params(ns): """ Get list of parameters in ns :param ns: namespace to match, ``str`` """ try: ns = make_global_ns(ns) names = get_param_server().getParamNames() names.sort() return [n for n in names if n.startswith(ns)] except socket.error: raise RosParamIOException("Unable to communicate with master!") # COMMAND-LINE PARSING def _rosparam_cmd_get_dump(cmd, argv): """ Process command line for rosparam get/dump, e.g.:: rosparam get param rosparam dump file.yaml [namespace] :param cmd: command ('get' or 'dump'), ``str`` :param argv: command-line args, ``str`` """ # get and dump are equivalent functionality, just different arguments if cmd == 'dump': parser = OptionParser(usage="usage: %prog dump [options] file [namespace]", prog=NAME) elif cmd == 'get': parser = OptionParser(usage="usage: %prog get [options] parameter", prog=NAME) parser.add_option("-p", dest="pretty", default=False, action="store_true", help="pretty print. WARNING: not YAML-safe") parser.add_option("-v", dest="verbose", default=False, action="store_true", help="turn on verbose output") options, args = parser.parse_args(argv[2:]) arg = None ns = '' if len(args) == 0: if cmd == 'get': parser.error("invalid arguments. Please specify a parameter name") elif len(args) == 1: arg = args[0] elif len(args) == 2 and cmd == 'dump': arg = args[0] ns = args[1] else: parser.error("too many arguments") if cmd == 'get': _rosparam_cmd_get_param(script_resolve_name(NAME, arg), pretty=options.pretty, verbose=options.verbose) else: if options.verbose: print("dumping namespace [%s] to file [%s]"%(ns, arg)) dump_params(arg, script_resolve_name(NAME, ns), verbose=options.verbose) def _set_optparse_neg_args(parser, argv): # we don't use optparse to parse actual arguments, just options, # due to the fact that optparse doesn't handle negative numbers as # arguments. This parsing is complicated by the fact that we still # need to respect argument-bearing options like --textfile. args = [] optparse_args = [] skip = False for s in argv[2:]: if s.startswith('-'): if s in ['-t', '--textfile', '-b', '--binfile']: skip = True optparse_args.append(s) elif skip: parser.error("-t and --textfile options require an argument") elif len(s) > 1 and ord(s[1]) >= ord('0') and ord(s[1]) <= ord('9'): args.append(s) else: optparse_args.append(s) else: if skip: skip = False optparse_args.append(s) else: args.append(s) options, _ = parser.parse_args(optparse_args) return options, args # TODO: break this into separate routines, has gotten too ugly to multiplex def _rosparam_cmd_set_load(cmd, argv): """ Process command line for rosparam set/load, e.g.:: rosparam load file.yaml [namespace] rosparam set param value :param cmd: command name, ``str`` :param argv: command-line args, ``str`` """ if cmd == 'load': parser = OptionParser(usage="usage: %prog load [options] file [namespace]", prog=NAME) elif cmd == 'set': parser = OptionParser(usage="usage: %prog set [options] parameter value", prog=NAME) parser.add_option("-t", "--textfile", dest="text_file", default=None, metavar="TEXT_FILE", help="set parameters to contents of text file") parser.add_option("-b", "--binfile", dest="bin_file", default=None, metavar="BINARY_FILE", help="set parameters to contents of binary file") parser.add_option("-v", dest="verbose", default=False, action="store_true", help="turn on verbose output") if cmd == 'set': options, args = _set_optparse_neg_args(parser, argv) if options.text_file and options.bin_file: parser.error("you may only specify one of --textfile or --binfile") else: options, args = parser.parse_args(argv[2:]) arg2 = None if len(args) == 0: if cmd == 'load': parser.error("invalid arguments. Please specify a file name or - for stdin") elif cmd == 'set': parser.error("invalid arguments. Please specify a parameter name") elif len(args) == 1: arg = args[0] if cmd == 'set' and not (options.text_file or options.bin_file): parser.error("invalid arguments. Please specify a parameter value") elif len(args) == 2: arg = args[0] arg2 = args[1] else: parser.error("too many arguments") if cmd == 'set': name = script_resolve_name(NAME, arg) # #2647 if options.text_file: if not os.path.isfile(options.text_file): parser.error("file '%s' does not exist"%(options.text_file)) with open(options.text_file) as f: arg2 = f.read() set_param_raw(name, arg2, verbose=options.verbose) elif options.bin_file: with open(options.bin_file, 'rb') as f: arg2 = Binary(f.read()) set_param_raw(name, arg2, verbose=options.verbose) else: # #2237: the empty string is really hard to specify on the # command-line due to bash quoting rules. We cheat here and # let an empty Python string be an empty YAML string (instead # of YAML null, which has no meaning to the Parameter Server # anyway). if arg2 == '': arg2 = '!!str' set_param(name, arg2, verbose=options.verbose) else: paramlist = load_file(arg, default_namespace=script_resolve_name(NAME, arg2), verbose=options.verbose) for params,ns in paramlist: upload_params(ns, params, verbose=options.verbose) def _rosparam_cmd_list(argv): """ Process command line for rosparam set/load, e.g.:: rosparam load file.yaml [namespace] rosparam set param value :param argv: command-line args, ``str`` """ parser = OptionParser(usage="usage: %prog list [namespace]", prog=NAME) options, args = parser.parse_args(argv[2:]) ns = GLOBALNS if len(args) == 1: ns = script_resolve_name(NAME, args[0]) elif len(args) == 2: parser.error("too many arguments") print('\n'.join(list_params(ns))) def _rosparam_cmd_delete(argv): """ Process command line for rosparam delete, e.g.:: rosparam delete param :param cmd: command name, ``str`` :param argv: command-line args, ``str`` """ parser = OptionParser(usage="usage: %prog delete [options] parameter", prog=NAME) parser.add_option("-v", dest="verbose", default=False, action="store_true", help="turn on verbose output") options, args = parser.parse_args(argv[2:]) arg2 = None if len(args) == 0: parser.error("invalid arguments. Please specify a parameter name") elif len(args) == 1: arg = args[0] else: parser.error("too many arguments") try: delete_param(script_resolve_name(NAME, arg), verbose=options.verbose) except rosgraph.masterapi.Error as e: raise RosParamException(str(e)) def _fullusage(): """ Prints rosparam usage """ print("""rosparam is a command-line tool for getting, setting, and deleting parameters from the ROS Parameter Server. Commands: \trosparam set\tset parameter \trosparam get\tget parameter \trosparam load\tload parameters from file \trosparam dump\tdump parameters to file \trosparam delete\tdelete parameter \trosparam list\tlist parameter names """) sys.exit(0) def yamlmain(argv=None): """ Command-line main routine. Loads in one or more input files :param argv: command-line arguments or None to use sys.argv, ``[str]`` """ if argv is None: argv = sys.argv if len(argv) == 1: _fullusage() try: command = argv[1] if command in ['get', 'dump']: _rosparam_cmd_get_dump(command, argv) elif command in ['set', 'load']: _rosparam_cmd_set_load(command, argv) elif command in ['delete']: _rosparam_cmd_delete(argv) elif command == 'list': _rosparam_cmd_list(argv) else: _fullusage() except RosParamException as e: print("ERROR: "+str(e), file=sys.stderr) sys.exit(1) # YAML configuration. Doxygen does not like these being higher up in the code yaml.add_constructor(u'!radians', construct_angle_radians) yaml.add_constructor(u'!degrees', construct_angle_degrees) # allow both !degrees 180, !radians 2*pi pattern = re.compile(r'^deg\([^\)]*\)$') yaml.add_implicit_resolver(u'!degrees', pattern, first="deg(") pattern = re.compile(r'^rad\([^\)]*\)$') yaml.add_implicit_resolver(u'!radians', pattern, first="rad(")
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(rospy) find_package(catkin REQUIRED) catkin_package() catkin_python_setup() # install legacy infrastructure needed by rosbuild install(FILES rosbuild/rospy.cmake DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/rosbuild) catkin_install_python(PROGRAMS rosbuild/scripts/genmsg_py.py rosbuild/scripts/gensrv_py.py rosbuild/scripts/genutil.py DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/rosbuild/scripts)
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/package.xml
<package> <name>rospy</name> <version>1.11.21</version> <description> rospy is a pure Python client library for ROS. The rospy client API enables Python programmers to quickly interface with ROS <a href="http://ros.org/wiki/Topics">Topics</a>, <a href="http://ros.org/wiki/Services">Services</a>, and <a href="http://ros.org/wiki/Parameter Server">Parameters</a>. The design of rospy favors implementation speed (i.e. developer time) over runtime performance so that algorithms can be quickly prototyped and tested within ROS. It is also ideal for non-critical-path code, such as configuration and initialization code. Many of the ROS tools are written in rospy to take advantage of the type introspection capabilities. Many of the ROS tools, such as <a href="http://ros.org/wiki/rostopic">rostopic</a> and <a href="http://ros.org/wiki/rosservice">rosservice</a>, are built on top of rospy. </description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>BSD</license> <url>http://ros.org/wiki/rospy</url> <author>Ken Conley</author> <buildtool_depend version_gte="0.5.78">catkin</buildtool_depend> <run_depend>genpy</run_depend> <run_depend>python-numpy</run_depend> <run_depend>python-rospkg</run_depend> <run_depend>python-yaml</run_depend> <run_depend>roscpp</run_depend> <run_depend>rosgraph</run_depend> <run_depend version_gte="1.10.3">rosgraph_msgs</run_depend> <run_depend>roslib</run_depend> <run_depend>std_msgs</run_depend> <export> <rosdoc config="rosdoc.yaml"/> <architecture_independent/> </export> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosdoc.yaml
- builder: epydoc config: epydoc.config
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/setup.py
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rospy', 'rospy.impl'], package_dir={'': 'src'}, scripts=['scripts/rosconsole'], requires=['genpy', 'numpy', 'rosgraph', 'roslib', 'rospkg'] ) setup(**d)
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rospy/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-rospy-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package rospy ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- * make get_published_topics threadsafe (`#958 <https://github.com/ros/ros_comm/issues/958>`_) * fix wrong type in docstring for rospy.Timer (`#878 <https://github.com/ros/ros_comm/pull/878>`_) * add logXXX_throttle functions (`#812 <https://github.com/ros/ros_comm/pull/812>`_) 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- * preserve identity of numpy_msg(T) (`#758 <https://github.com/ros/ros_comm/pull/758>`_) 1.11.16 (2015-11-09) -------------------- * catch ROSInterruptException from rospy timers when shutting down (`#690 <https://github.com/ros/ros_comm/pull/690>`_) 1.11.15 (2015-10-13) -------------------- * validate name after remapping (`#669 <https://github.com/ros/ros_comm/pull/669>`_) 1.11.14 (2015-09-19) -------------------- * fix memory/thread leak with QueuedConnection (`#661 <https://github.com/ros/ros_comm/pull/661>`_) * fix signaling already shutdown to client hooks with the appropriate signature (`#651 <https://github.com/ros/ros_comm/issues/651>`_) * fix bug with missing current logger levels (`#631 <https://github.com/ros/ros_comm/pull/631>`_) 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- * add rosconsole command line tool to change logger levels (`#576 <https://github.com/ros/ros_comm/pull/576>`_) * add accessor for remaining time of the Rate class (`#588 <https://github.com/ros/ros_comm/pull/588>`_) * fix high latency when using asynchronous publishing (`#547 <https://github.com/ros/ros_comm/issues/547>`_) * fix error handling when publishing on Empty topic (`#566 <https://github.com/ros/ros_comm/pull/566>`_) 1.11.10 (2014-12-22) -------------------- * add specific exception for time jumping backwards (`#485 <https://github.com/ros/ros_comm/issues/485>`_) * make param functions thread-safe (`#523 <https://github.com/ros/ros_comm/pull/523>`_) * fix infinitely retrying subscriber (`#533 <https://github.com/ros/ros_comm/issues/533>`_) * fix removal of QueuedConnection leading to wrong subscriber count (`#526 <https://github.com/ros/ros_comm/issues/526>`_) * fix TCPROS header validation when `callerid` header is not set (`#522 <https://github.com/ros/ros_comm/issues/522>`_, regression from 1.11.1) * fix memory leak when using subcriber statistics (`#520 <https://github.com/ros/ros_comm/issues/520>`_) * fix reported traffic in bytes from Python nodes (`#501 <https://github.com/ros/ros_comm/issues/501>`_) 1.11.9 (2014-08-18) ------------------- * populate delivered_msgs field of TopicStatistics message (`#486 <https://github.com/ros/ros_comm/issues/486>`_) 1.11.8 (2014-08-04) ------------------- * fix topic/connection statistics reporting code (`#482 <https://github.com/ros/ros_comm/issues/482>`_) 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- * make MasterProxy thread-safe (`#459 <https://github.com/ros/ros_comm/issues/459>`_) * check ROS_HOSTNAME for localhost / ROS_IP for 127./::1 and prevent connections from other hosts in that case (`#452 <https://github.com/ros/ros_comm/issues/452>`)_ 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- * Python 3 compatibility (`#426 <https://github.com/ros/ros_comm/issues/426>`_) 1.11.3 (2014-05-21) ------------------- * allow shutdown hooks to be any callable object (`#410 <https://github.com/ros/ros_comm/issues/410>`_) * add demux program and related scripts (`#407 <https://github.com/ros/ros_comm/issues/407>`_) * add publisher queue_size to rostopic 1.11.2 (2014-05-08) ------------------- * use publisher queue_size for statistics (`#398 <https://github.com/ros/ros_comm/issues/398>`_) 1.11.1 (2014-05-07) ------------------- * improve asynchonous publishing performance (`#373 <https://github.com/ros/ros_comm/issues/373>`_) * add warning when queue_size is omitted for rospy publisher (`#346 <https://github.com/ros/ros_comm/issues/346>`_) * add optional topic/connection statistics (`#398 <https://github.com/ros/ros_comm/issues/398>`_) * add transport information in SlaveAPI::getBusInfo() for roscpp & rospy (`#328 <https://github.com/ros/ros_comm/issues/328>`_) * allow custom error handlers for services (`#375 <https://github.com/ros/ros_comm/issues/375>`_) * add architecture_independent flag in package.xml (`#391 <https://github.com/ros/ros_comm/issues/391>`_) 1.11.0 (2014-03-04) ------------------- * fix exception handling for queued connections (`#369 <https://github.com/ros/ros_comm/issues/369>`_) * use catkin_install_python() to install Python scripts (`#361 <https://github.com/ros/ros_comm/issues/361>`_) 1.10.0 (2014-02-11) ------------------- 1.9.54 (2014-01-27) ------------------- 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- * implement optional queueing for rospy publications (`#169 <https://github.com/ros/ros_comm/issues/169>`_) * overwrite __repr__ for rospy.Duration and Time (`ros/genpy#24 <https://github.com/ros/genpy/issues/24>`_) * add missing dependency on roscpp 1.9.50 (2013-10-04) ------------------- * add support for python coverage tool to work in callbacks 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- * make rospy nodes killable while waiting for master (`#262 <https://github.com/ros/ros_comm/issues/262>`_) 1.9.47 (2013-07-03) ------------------- 1.9.46 (2013-06-18) ------------------- 1.9.45 (2013-06-06) ------------------- * add missing run_depend on python-yaml * allow configuration of ports for XML RPCs and TCP ROS * fix race condition where rospy subscribers do not connect to all publisher * fix closing and deregistering connection when connect fails (`#128 <https://github.com/ros/ros_comm/issues/128>`_) * fix log level of RosOutHandler (`#210 <https://github.com/ros/ros_comm/issues/210>`_) 1.9.44 (2013-03-21) ------------------- 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- * make dependencies on rospy optional by refactoring RosStreamHandler to rosgraph (`#179 <https://github.com/ros/ros_comm/issues/179>`_) 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- * add colorization for rospy log output (`#3691 <https://code.ros.org/trac/ros/ticket/3691>`_) * fix socket polling under Windows (`#3959 <https://code.ros.org/trac/ros/ticket/3959>`_) 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/epydoc.config
[epydoc] name: rospy modules: rospy, roslib.rostime inheritance: included url: http://ros.org/wiki/rospy frames: no private: no external-api: roslib external-api-file: roslib:doc/roslib/html/python/api-objects.txt external-api-root: roslib:http://www.ros.org/doc/api/roslib/html/python/ exclude: rospy.init, rospy.simtime, rospy.simtime, rospy.masterslave, rospy.msg, rospy.msnode, rospy.paramserver, rospy.registration, rospy.rosout, rospy.tcpros, rospy.tcpros_base, rospy.tcpros_pubsub, rospy.threadpool, rospy.udpros, rospy.validators, rospy.transport
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild/rospy.cmake
rosbuild_find_ros_package(rospy) # Message-generation support. macro(genmsg_py) rosbuild_get_msgs(_msglist) set(_inlist "") set(_autogen "") set(genmsg_py_exe ${rospy_PACKAGE_PATH}/rosbuild/scripts/genmsg_py.py) foreach(_msg ${_msglist}) # Construct the path to the .msg file set(_input ${PROJECT_SOURCE_DIR}/msg/${_msg}) # Append it to a list, which we'll pass back to gensrv below list(APPEND _inlist ${_input}) rosbuild_gendeps(${PROJECT_NAME} ${_msg}) set(_output_py ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}/msg/_${_msg}) string(REPLACE ".msg" ".py" _output_py ${_output_py}) # Add the rule to build the .py from the .msg. add_custom_command(OUTPUT ${_output_py} COMMAND ${genmsg_py_exe} --noinitpy ${_input} DEPENDS ${_input} ${genmsg_py_exe} ${gendeps_exe} ${${PROJECT_NAME}_${_msg}_GENDEPS} ${ROS_MANIFEST_LIST}) list(APPEND _autogen ${_output_py}) endforeach(_msg) if(_autogen) # Set up to create the __init__.py file that will import the .py # files created by the above loop. It can't run until those files are # generated, so it depends on them. set(_output_py ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}/msg/__init__.py) add_custom_command(OUTPUT ${_output_py} COMMAND ${genmsg_py_exe} --initpy ${_inlist} DEPENDS ${_autogen}) # A target that depends on generation of the __init__.py add_custom_target(ROSBUILD_genmsg_py DEPENDS ${_output_py}) # Make our target depend on rosbuild_premsgsrvgen, to allow any # pre-msg/srv generation steps to be done first. add_dependencies(ROSBUILD_genmsg_py rosbuild_premsgsrvgen) # Add our target to the top-level genmsg target, which will be fired if # the user calls genmsg() add_dependencies(rospack_genmsg ROSBUILD_genmsg_py) # Also set up to clean the src/<project>/msg directory get_directory_property(_old_clean_files ADDITIONAL_MAKE_CLEAN_FILES) list(APPEND _old_clean_files ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}/msg) set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_old_clean_files}") endif(_autogen) endmacro(genmsg_py) # Call the macro we just defined. genmsg_py() # Service-generation support. macro(gensrv_py) rosbuild_get_srvs(_srvlist) set(_inlist "") set(_autogen "") set(gensrv_py_exe ${rospy_PACKAGE_PATH}/rosbuild/scripts/gensrv_py.py) foreach(_srv ${_srvlist}) # Construct the path to the .srv file set(_input ${PROJECT_SOURCE_DIR}/srv/${_srv}) # Append it to a list, which we'll pass back to gensrv below list(APPEND _inlist ${_input}) rosbuild_gendeps(${PROJECT_NAME} ${_srv}) set(_output_py ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}/srv/_${_srv}) string(REPLACE ".srv" ".py" _output_py ${_output_py}) # Add the rule to build the .py from the .srv add_custom_command(OUTPUT ${_output_py} COMMAND ${gensrv_py_exe} --noinitpy ${_input} DEPENDS ${_input} ${gensrv_py_exe} ${gendeps_exe} ${${PROJECT_NAME}_${_srv}_GENDEPS} ${ROS_MANIFEST_LIST}) list(APPEND _autogen ${_output_py}) endforeach(_srv) if(_autogen) # Set up to create the __init__.py file that will import the .py # files created by the above loop. It can't run until those files are # generated, so it depends on them. set(_output_py ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}/srv/__init__.py) add_custom_command(OUTPUT ${_output_py} COMMAND ${gensrv_py_exe} --initpy ${_inlist} DEPENDS ${_autogen}) # A target that depends on generation of the __init__.py add_custom_target(ROSBUILD_gensrv_py DEPENDS ${_output_py}) # Make our target depend on rosbuild_premsgsrvgen, to allow any # pre-msg/srv generation steps to be done first. add_dependencies(ROSBUILD_gensrv_py rosbuild_premsgsrvgen) # Add our target to the top-level gensrv target, which will be fired if # the user calls gensrv() add_dependencies(rospack_gensrv ROSBUILD_gensrv_py) # Also set up to clean the src/<project>/srv directory get_directory_property(_old_clean_files ADDITIONAL_MAKE_CLEAN_FILES) list(APPEND _old_clean_files ${PROJECT_SOURCE_DIR}/src/${PROJECT_NAME}/srv) set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_old_clean_files}") endif(_autogen) endmacro(gensrv_py) # Call the macro we just defined. gensrv_py()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild/scripts/gensrv_py.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ ROS message source code generation for rospy. Converts ROS .srv files into Python source code implementations. """ import sys # genutil is a utility package the implements the package crawling # logic of genmsg_py and gensrv_py logic import genutil if __name__ == "__main__": genutil.genmain(sys.argv, 'srv')
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild/scripts/genmsg_py.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ ROS message source code generation for Python Converts ROS .msg files in a package into Python source code implementations. """ import sys # genutil is a utility package the implements the package crawling # logic of genmsg_py and gensrv_py logic import genutil if __name__ == "__main__": genutil.genmain(sys.argv, 'msg')
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/rosbuild/scripts/genutil.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## Common generation tools for Python ROS message and service generators from __future__ import print_function import os import errno # for smart handling of exceptions for os.makedirs() import sys import traceback import rospkg import genmsg import genpy import genpy.generator import genpy.generate_initpy def usage(progname): print("%(progname)s file(s)"%vars()) def get_package_and_file(argv): if not argv[1:]: usage(argv[0]) files = [a for a in argv[1:] if not a.startswith('--')] # rospy.cmake only passes in a single file arg, assert this case assert len(files) == 1, files msg_file = files[0] package = rospkg.get_package_name(msg_file) return package, msg_file def get_outdir(package, path, subdir): "compute the directory that the .py files are output to" outdir = os.path.join(path, 'src', package, subdir) if not os.path.exists(outdir): try: os.makedirs(outdir) except Exception as e: # It's not a problem if the directory already exists, # because this can happen during a parallel build if e.errno != errno.EEXIST: raise e elif not os.path.isdir(outdir): raise IOError("Cannot write to %s: file in the way"%(outdir)) return outdir def generate_messages(rospack, package, msg_file, subdir): if subdir == 'msg': gen = genpy.generator.MsgGenerator() else: gen = genpy.generator.SrvGenerator() path = rospack.get_path(package) search_path = { package: [os.path.join(path, 'msg')] } # std_msgs is implicit depend due to Header search_path['std_msgs'] = [os.path.join(rospack.get_path('std_msgs'), 'msg')] for d in rospack.get_depends(package): search_path[d] = [os.path.join(rospack.get_path(d), 'msg')] include_args = [] for d, ipaths in search_path.items(): for ipath in ipaths: include_args.append('-I%s:%s'%(d, ipath)) outdir = get_outdir(package, path, subdir) retcode = gen.generate_messages(package, [msg_file], outdir, search_path) return retcode def generate_initpy(rospack, p, subdir): path = rospack.get_path(p) outdir = get_outdir(p, path, subdir) retcode = genpy.generate_initpy.write_modules(outdir) parent_initpy = os.path.join(path, 'src', p, '__init__.py') if not os.path.exists(parent_initpy): with open(parent_initpy, 'w') as f: f.write("#autogenerated by ROS python message generators") return retcode def genmain(argv, subdir): rospack = rospkg.RosPack() try: gen_initpy = '--initpy' in argv no_gen_initpy = '--noinitpy' in argv if gen_initpy: # #1827 # new __init__py does not take explicit file args. just # convert to unique package names and compute path. files = [f for f in argv[1:] if not f.startswith('--')] packages = list(set([rospkg.get_package_name(f) for f in files])) retcodes = [generate_initpy(rospack, p, subdir) for p in packages] retcodes = [c for c in retcodes if c not in (0, None)] if retcodes: retcode = retcodes[0] else: retcode = 0 else: package, msg_file = get_package_and_file(argv) retcode = generate_messages(rospack, package, msg_file, subdir) except genmsg.InvalidMsgSpec as e: sys.stderr.write("ERROR: %s\n"%(str(e))) retcode = 1 except genmsg.MsgGenerationException as e: sys.stderr.write("ERROR: %s\n"%(str(e))) retcode = 2 except Exception as e: traceback.print_exc() sys.stderr.write("ERROR: %s\n"%(str(e))) retcode = 3 sys.exit(retcode or 0)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/test_nodes/talker.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## Simple talker demo that published std_msgs/Strings messages ## to the 'chatter' topic import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher('chatter', String, queue_size=10) rospy.init_node('talker', anonymous=True) r = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): str = "hello world %s"%rospy.get_time() rospy.loginfo(str) pub.publish(str) r.sleep() if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/test_nodes/listener.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ## Simple talker demo that listens to std_msgs/Strings published ## to the 'chatter' topic PKG = 'rosmaster' # this package name import rospy from std_msgs.msg import String def callback(data): rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.data) def listener(): # in ROS, nodes are unique named. If two nodes with the same # node are launched, the previous one is kicked off. The # anonymous=True flag means that rospy will choose a unique # name for our 'talker' node so that multiple talkers can # run simultaenously. rospy.init_node('listener', anonymous=True) rospy.Subscriber("chatter", String, callback) # spin() simply keeps python from exiting until this node is stopped rospy.spin() if __name__ == '__main__': listener()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/scripts/rosconsole
#!/usr/bin/env python from rospy import rosconsole rosconsole.main()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/service.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Base-classes and management of ROS services. See L{rospy.tcpros_service} for actual implementation.""" import logging import traceback from rospy.core import * from rospy.impl.registration import set_service_manager, Registration, get_registration_listeners from rospy.impl.transport import * logger = logging.getLogger('rospy.service') class ServiceException(Exception): """Exception class for service-related errors""" pass class _Service(object): """Internal-use superclass for storing service information""" def __init__(self, name, service_class): self.resolved_name = resolve_name(name) #services remap as well self.service_class = service_class self.request_class = service_class._request_class self.response_class = service_class._response_class self.uri = None #initialize attr class ServiceManager(object): """Keeps track of currently registered services in the ROS system""" def __init__(self, registration_listeners=None): """ ctor @param registration_listeners: override default registration listener. @type registration_listeners: RegistrationListeners """ self.map = {} # {name : Service} self.lock = threading.RLock() if registration_listeners is None: self.registration_listeners = get_registration_listeners() else: self.registration_listeners = registration_listeners def get_services(self): """ @return: List of (service_name, service_uri) for all registered services. @rtype: [(str, str)] """ with self.lock: ret_val = [] for name, service in self.map.items(): ret_val.append((name, service.uri)) services = list(self.map.values()) return ret_val def unregister_all(self): """ Unregister all registered services """ self.map.clear() def register(self, resolved_service_name, service): """ Register service with ServiceManager and ROS master @param resolved_service_name: name of service (resolved) @type resolved_service_name: str @param service: Service to register @type service: L{_Service} """ err = None with self.lock: if resolved_service_name in self.map: err = "service [%s] already registered"%resolved_service_name else: self.map[resolved_service_name] = service # NOTE: this call can potentially take a long time under lock and thus needs to be reimplmented self.registration_listeners.notify_added(resolved_service_name, service.uri, Registration.SRV) if err: raise ServiceException(err) def unregister(self, resolved_service_name, service): """ Unregister service with L{ServiceManager} and ROS Master @param resolved_service_name: name of service @type resolved_service_name: str @param service: service implementation @type service: L{_Service} """ with self.lock: curr = self.map.get(resolved_service_name, None) if curr == service: del self.map[resolved_service_name] # NOTE: this call can potentially take a long time under lock self.registration_listeners.notify_removed(resolved_service_name, service.uri, Registration.SRV) def get_service(self, resolved_service_name): """ @param resolved_service_name: name of service @type resolved_service_name: str @return: service implementation @rtype: _Service """ return self.map.get(resolved_service_name, None) set_service_manager(ServiceManager())
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/logger_level_service_caller.py
# Software License Agreement (BSD License) # # Copyright (c) 2015, Chris Mansley, Open Source Robotics Foundation, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import rosgraph import rosnode import rospy import rosservice class ROSConsoleException(Exception): """Base exception class of rosconsole-related errors.""" pass class LoggerLevelServiceCaller(object): """ Handles service calls for getting lists of nodes and loggers. Also handles sending requests to change logger levels. """ def __init__(self): pass def get_levels(self): # Declare level names lower-case, because that's how they are returned # from the service call. return ['debug', 'info', 'warn', 'error', 'fatal'] def get_loggers(self, node): self._refresh_loggers(node) return self._current_loggers def get_node_names(self): """ Get a list of available services via a ros service call. :returns: a list of all nodes that provide the set_logger_level service, ''list(str)'' """ set_logger_level_nodes = [] nodes = rosnode.get_node_names() for name in sorted(nodes): for service in rosservice.get_service_list(name): if service == name + '/set_logger_level': set_logger_level_nodes.append(name) return set_logger_level_nodes def _refresh_loggers(self, node): """ Store a list of loggers available for passed in node. :param node: name of the node to query, ''str'' :raises: :exc:`ROSTopicException` If topic type cannot be determined or loaded """ self._current_loggers = [] self._current_levels = {} # Construct the service name, taking into account our namespace servicename = rosgraph.names.ns_join( rosgraph.names.ns_join(rosgraph.names.get_ros_namespace(), node), 'get_loggers') # Construct the service name, taking into account our namespace servicename = rosgraph.names.resolve_name( servicename, rosgraph.names.get_ros_namespace()) try: service = rosservice.get_service_class_by_name(servicename) except rosservice.ROSServiceException as e: raise ROSConsoleException( "node '%s' doesn't exist or doesn't support query: %s" % (node, e)) request = service._request_class() proxy = rospy.ServiceProxy(str(servicename), service) try: response = proxy(request) except rospy.ServiceException as e: raise ROSConsoleException("node '%s' logger request failed: %s" % (node, e)) if response._slot_types[0] == 'roscpp/Logger[]': for logger in getattr(response, response.__slots__[0]): self._current_loggers.append(logger.name) self._current_levels[logger.name] = logger.level else: raise ROSConsoleException(repr(response)) def send_logger_change_message(self, node, logger, level): """ Send a logger level change request to 'node'. :param node: name of the node to chaange, ''str'' :param logger: name of the logger to change, ''str'' :param level: name of the level to change, ''str'' :returns: True if the response is valid, ''bool'' :returns: False if the request raises an exception or would not change the state, ''bool'' """ # Construct the service name, taking into account our namespace servicename = rosgraph.names.ns_join( rosgraph.names.ns_join(rosgraph.names.get_ros_namespace(), node), 'set_logger_level') # Construct the service name, taking into account our namespace servicename = rosgraph.names.resolve_name( servicename, rosgraph.names.get_ros_namespace()) if self._current_levels[logger] == level: return False service = rosservice.get_service_class_by_name(servicename) request = service._request_class() request.logger = logger request.level = level proxy = rospy.ServiceProxy(str(servicename), service) try: proxy(request) self._current_levels[logger] = level.upper() except rospy.ServiceException as e: raise ROSConsoleException("node '%s' logger request failed: %s" % (node, e)) return True
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/rostime.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ ROS time and duration representations, as well as internal routines for managing wallclock versus a simulated clock. The important data classes are L{Time} and L{Duration}, which represent the ROS 'time' and 'duration' primitives, respectively. """ import sys import threading import time import traceback import rospy.exceptions import genpy ## /time support. This hooks into the rospy Time representation and ## allows it to be overriden with data from the /time topic. _rostime_initialized = False _rostime_current = None _rostime_cond = threading.Condition() # subclass genpy to provide abstraction layer class Duration(genpy.Duration): """ Duration represents the ROS 'duration' primitive type, which consists of two integers: seconds and nanoseconds. The Duration class allows you to add and subtract Duration instances, including adding and subtracting from L{Time} instances. Usage:: five_seconds = Duration(5) five_nanoseconds = Duration(0, 5) print 'Fields are', five_seconds.secs, five_seconds.nsecs # Duration arithmetic ten_seconds = five_seconds + five_seconds five_secs_ago = rospy.Time.now() - five_seconds # Time minus Duration is a Time true_val = ten_second > five_seconds """ __slots__ = [] def __init__(self, secs=0, nsecs=0): """ Create new Duration instance. secs and nsecs are integers and correspond to the ROS 'duration' primitive type. @param secs: seconds @type secs: int @param nsecs: nanoseconds @type nsecs: int """ super(Duration, self).__init__(secs, nsecs) def __repr__(self): return 'rospy.Duration[%d]' % self.to_nsec() class Time(genpy.Time): """ Time represents the ROS 'time' primitive type, which consists of two integers: seconds since epoch and nanoseconds since seconds. Time instances are mutable. The L{Time.now()} factory method can initialize Time to the current ROS time and L{from_sec()} can be used to create a Time instance from the Python's time.time() float seconds representation. The Time class allows you to subtract Time instances to compute Durations, as well as add Durations to Time to create new Time instances. Usage:: now = rospy.Time.now() zero_time = rospy.Time() print 'Fields are', now.secs, now.nsecs # Time arithmetic five_secs_ago = now - rospy.Duration(5) # Time minus Duration is a Time five_seconds = now - five_secs_ago # Time minus Time is a Duration true_val = now > five_secs_ago # NOTE: in general, you will want to avoid using time.time() in ROS code import time py_time = rospy.Time.from_sec(time.time()) """ __slots__ = [] def __init__(self, secs=0, nsecs=0): """ Constructor: secs and nsecs are integers and correspond to the ROS 'time' primitive type. You may prefer to use the static L{from_sec()} and L{now()} factory methods instead. @param secs: seconds since epoch @type secs: int @param nsecs: nanoseconds since seconds (since epoch) @type nsecs: int """ super(Time, self).__init__(secs, nsecs) def __repr__(self): return 'rospy.Time[%d]' % self.to_nsec() @staticmethod def now(): """ Create new L{Time} instance representing current time. This can either be wall-clock time or a simulated clock. It is strongly recommended that you use the now() factory to create current time representations instead of reading wall-clock time and create Time instances from it. @return: L{Time} instance for current time @rtype: L{Time} """ return get_rostime() # have to reproduce super class implementation to return correct typing def from_seconds(float_secs): """ Use Time.from_sec() instead. Retained for backwards compatibility. @param float_secs: time value in time.time() format @type float_secs: float @return: Time instance for specified time @rtype: L{Time} """ return Time.from_sec(float_secs) from_seconds = staticmethod(from_seconds) def from_sec(float_secs): """ Create new Time instance from a float seconds representation (e.g. time.time()). @param float_secs: time value in time.time() format @type float_secs: float @return: Time instance for specified time @rtype: L{Time} """ secs = int(float_secs) nsecs = int((float_secs - secs) * 1000000000) return Time(secs, nsecs) from_sec = staticmethod(from_sec) def _set_rostime(t): """Callback to update ROS time from a ROS Topic""" if isinstance(t, genpy.Time): t = Time(t.secs, t.nsecs) elif not isinstance(t, Time): raise ValueError("must be Time instance: %s"%t.__class__) global _rostime_current _rostime_current = t try: _rostime_cond.acquire() _rostime_cond.notifyAll() finally: _rostime_cond.release() def get_rostime(): """ Get the current time as a L{Time} object @return: current time as a L{rospy.Time} object @rtype: L{Time} """ if not _rostime_initialized: raise rospy.exceptions.ROSInitException("time is not initialized. Have you called init_node()?") if _rostime_current is not None: # initialize with sim time return _rostime_current else: # initialize with wallclock float_secs = time.time() secs = int(float_secs) nsecs = int((float_secs - secs) * 1000000000) return Time(secs, nsecs) def get_time(): """ Get the current time as float secs (time.time() format) @return: time in secs (time.time() format) @rtype: float """ return Time.now().to_sec() def set_rostime_initialized(val): """ Internal use. Mark rostime as initialized. This flag enables other routines to throw exceptions if rostime is being used before the underlying system is initialized. @param val: value for initialization state @type val: bool """ global _rostime_initialized _rostime_initialized = val def is_rostime_initialized(): """ Internal use. @return: True if rostime has been initialized @rtype: bool """ return _rostime_initialized def get_rostime_cond(): """ internal API for helper routines that need to wait on time updates @return: rostime conditional var @rtype: threading.Cond """ return _rostime_cond def is_wallclock(): """ Internal use for ROS-time routines. @return: True if ROS is currently using wallclock time @rtype: bool """ return _rostime_current == None def switch_to_wallclock(): """ Internal use. Switch ROS to wallclock time. This is mainly for testing purposes. """ global _rostime_current _rostime_current = None try: _rostime_cond.acquire() _rostime_cond.notifyAll() finally: _rostime_cond.release() def wallsleep(duration): """ Internal use. Windows interrupts time.sleep with an IOError exception when a signal is caught. Even when the signal is handled by a callback, it will then proceed to throw IOError when the handling has completed. Refer to https://code.ros.org/trac/ros/ticket/3421. So we create a platform dependant wrapper to handle this here. """ if sys.platform in ['win32']: # cygwin seems to be ok try: time.sleep(duration) except IOError: pass else: time.sleep(duration)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/timer.py
# Software License Agreement (BSD License) # # Copyright (c) 2010, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id: __init__.py 12069 2010-11-09 20:31:55Z kwc $ import threading import time # for Time, Duration import genpy import rospy.core import rospy.rostime # author: tfield (Timers) # author: kwc (Rate, sleep) class Rate(object): """ Convenience class for sleeping in a loop at a specified rate """ def __init__(self, hz): """ Constructor. @param hz: hz rate to determine sleeping @type hz: int """ # #1403 self.last_time = rospy.rostime.get_rostime() self.sleep_dur = rospy.rostime.Duration(0, int(1e9/hz)) def _remaining(self, curr_time): """ Calculate the time remaining for rate to sleep. @param curr_time: current time @type curr_time: L{Time} @return: time remaining @rtype: L{Time} """ # detect time jumping backwards if self.last_time > curr_time: self.last_time = curr_time # calculate remaining time elapsed = curr_time - self.last_time return self.sleep_dur - elapsed def remaining(self): """ Return the time remaining for rate to sleep. @return: time remaining @rtype: L{Time} """ curr_time = rospy.rostime.get_rostime() return self._remaining(curr_time) def sleep(self): """ Attempt sleep at the specified rate. sleep() takes into account the time elapsed since the last successful sleep(). @raise ROSInterruptException: if ROS shutdown occurs before sleep completes @raise ROSTimeMovedBackwardsException: if ROS time is set backwards """ curr_time = rospy.rostime.get_rostime() sleep(self._remaining(curr_time)) self.last_time = self.last_time + self.sleep_dur # detect time jumping forwards, as well as loops that are # inherently too slow if curr_time - self.last_time > self.sleep_dur * 2: self.last_time = curr_time def sleep(duration): """ sleep for the specified duration in ROS time. If duration is negative, sleep immediately returns. @param duration: seconds (or rospy.Duration) to sleep @type duration: float or Duration @raise ROSInterruptException: if ROS shutdown occurs before sleep completes @raise ROSTimeMovedBackwardsException: if ROS time is set backwards """ if rospy.rostime.is_wallclock(): if isinstance(duration, genpy.Duration): duration = duration.to_sec() if duration < 0: return else: rospy.rostime.wallsleep(duration) else: initial_rostime = rospy.rostime.get_rostime() if not isinstance(duration, genpy.Duration): duration = genpy.Duration.from_sec(duration) rostime_cond = rospy.rostime.get_rostime_cond() # #3123 if initial_rostime == genpy.Time(0): # break loop if time is initialized or node is shutdown while initial_rostime == genpy.Time(0) and \ not rospy.core.is_shutdown(): with rostime_cond: rostime_cond.wait(0.3) initial_rostime = rospy.rostime.get_rostime() sleep_t = initial_rostime + duration # break loop if sleep_t is reached, time moves backwards, or # node is shutdown while rospy.rostime.get_rostime() < sleep_t and \ rospy.rostime.get_rostime() >= initial_rostime and \ not rospy.core.is_shutdown(): with rostime_cond: rostime_cond.wait(0.5) if rospy.rostime.get_rostime() < initial_rostime: time_jump = (initial_rostime - rospy.rostime.get_rostime()).to_sec() rospy.core.logerr("ROS time moved backwards: %ss", time_jump) raise rospy.exceptions.ROSTimeMovedBackwardsException(time_jump) if rospy.core.is_shutdown(): raise rospy.exceptions.ROSInterruptException("ROS shutdown request") class TimerEvent(object): """ Constructor. @param last_expected: in a perfect world, this is when the previous callback should have happened @type last_expected: rospy.Time @param last_real: when the callback actually happened @type last_real: rospy.Time @param current_expected: in a perfect world, this is when the current callback should have been called @type current_expected: rospy.Time @param last_duration: contains the duration of the last callback (end time minus start time) in seconds. Note that this is always in wall-clock time. @type last_duration: float """ def __init__(self, last_expected, last_real, current_expected, current_real, last_duration): self.last_expected = last_expected self.last_real = last_real self.current_expected = current_expected self.current_real = current_real self.last_duration = last_duration class Timer(threading.Thread): """ Convenience class for calling a callback at a specified rate """ def __init__(self, period, callback, oneshot=False): """ Constructor. @param period: desired period between callbacks @type period: rospy.Duration @param callback: callback to be called @type callback: function taking rospy.TimerEvent @param oneshot: if True, fire only once, otherwise fire continuously until shutdown is called [default: False] @type oneshot: bool """ super(Timer, self).__init__() self._period = period self._callback = callback self._oneshot = oneshot self._shutdown = False self.setDaemon(True) self.start() def shutdown(self): """ Stop firing callbacks. """ self._shutdown = True def run(self): r = Rate(1.0 / self._period.to_sec()) current_expected = rospy.rostime.get_rostime() + self._period last_expected, last_real, last_duration = None, None, None while not rospy.core.is_shutdown() and not self._shutdown: try: r.sleep() except rospy.exceptions.ROSInterruptException as e: if rospy.core.is_shutdown(): break raise if self._shutdown: break current_real = rospy.rostime.get_rostime() start = time.time() self._callback(TimerEvent(last_expected, last_real, current_expected, current_real, last_duration)) if self._oneshot: break last_duration = time.time() - start last_expected, last_real = current_expected, current_real current_expected += self._period
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/client.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Additional ROS client API methods. """ import logging import os import socket import struct import sys from threading import Lock import time import random import yaml import rosgraph import rosgraph.names import roslib import rospy.core from rospy.core import logwarn, loginfo, logerr, logdebug import rospy.exceptions import rospy.names import rospy.rostime import rospy.impl.init import rospy.impl.rosout import rospy.impl.simtime TIMEOUT_READY = 15.0 #seconds # log level constants from rosgraph_msgs.msg import Log from roscpp.srv import GetLoggers, GetLoggersResponse, SetLoggerLevel, SetLoggerLevelResponse from roscpp.msg import Logger from rospy.impl.tcpros_service import Service DEBUG = Log.DEBUG INFO = Log.INFO WARN = Log.WARN ERROR = Log.ERROR FATAL = Log.FATAL def myargv(argv=None): """ Remove ROS remapping arguments from sys.argv arguments. @return: copy of sys.argv with ROS remapping arguments removed @rtype: [str] """ if argv is None: argv = sys.argv return [a for a in argv if not rosgraph.names.REMAP in a] def load_command_line_node_params(argv): """ Load node param mappings (aka private parameters) encoded in command-line arguments, e.g. _foo:=bar. See also rosgraph.names.load_mappings. @param argv: command-line arguments @param argv: [str] @return: param->value remappings. @rtype: {str: val} @raises: ROSInitException """ try: mappings = {} for arg in argv: if rosgraph.names.REMAP in arg: src, dst = [x.strip() for x in arg.split(rosgraph.names.REMAP)] if src and dst: if len(src) > 1 and src[0] == '_' and src[1] != '_': mappings[src[1:]] = yaml.load(dst) return mappings except Exception as e: raise rospy.exceptions.ROSInitException("invalid command-line parameters: %s"%(str(e))) def on_shutdown(h): """ Register function to be called on shutdown. This function will be called before Node begins teardown. @param h: Function with zero args to be called on shutdown. @type h: fn() """ rospy.core.add_client_shutdown_hook(h) def spin(): """ Blocks until ROS node is shutdown. Yields activity to other threads. @raise ROSInitException: if node is not in a properly initialized state """ if not rospy.core.is_initialized(): raise rospy.exceptions.ROSInitException("client code must call rospy.init_node() first") logdebug("node[%s, %s] entering spin(), pid[%s]", rospy.core.get_caller_id(), rospy.core.get_node_uri(), os.getpid()) try: while not rospy.core.is_shutdown(): rospy.rostime.wallsleep(0.5) except KeyboardInterrupt: logdebug("keyboard interrupt, shutting down") rospy.core.signal_shutdown('keyboard interrupt') _logging_level_names = { logging.DEBUG: 'DEBUG', logging.INFO: 'INFO', logging.WARNING: 'WARN', logging.ERROR: 'ERROR', logging.CRITICAL: 'FATAL', } def _get_loggers(request): """ ROS service handler to get the levels of all active loggers. """ ret = GetLoggersResponse() for n in logging.Logger.manager.loggerDict.keys(): level = logging.getLogger(n).getEffectiveLevel() level = _logging_level_names[level] ret.loggers.append(Logger(n, level)) return ret _names_to_logging_levels = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARN': logging.WARNING, 'ERROR': logging.ERROR, 'FATAL': logging.CRITICAL, } def _set_logger_level(request): """ ROS service handler to set the logging level for a particular logger """ level = request.level.upper() if level in _names_to_logging_levels: logger = logging.getLogger(request.logger) logger.setLevel(_names_to_logging_levels[level]) else: logging.getLogger('rospy').error("Bad logging level: %s"%level) ret = SetLoggerLevelResponse() return ret def _init_node_params(argv, node_name): """ Uploads private params to the parameter server. Private params are specified via command-line remappings. @raises: ROSInitException """ # #1027: load in param name mappings params = load_command_line_node_params(argv) for param_name, param_value in params.items(): logdebug("setting param %s to %s"%(param_name, param_value)) set_param(rosgraph.names.PRIV_NAME + param_name, param_value) _init_node_args = None def init_node(name, argv=None, anonymous=False, log_level=None, disable_rostime=False, disable_rosout=False, disable_signals=False, xmlrpc_port=0, tcpros_port=0): """ Register client node with the master under the specified name. This MUST be called from the main Python thread unless disable_signals is set to True. Duplicate calls to init_node are only allowed if the arguments are identical as the side-effects of this method are not reversible. @param name: Node's name. This parameter must be a base name, meaning that it cannot contain namespaces (i.e. '/') @type name: str @param argv: Command line arguments to this program, including remapping arguments (default: sys.argv). If you provide argv to init_node(), any previously created rospy data structure (Publisher, Subscriber, Service) will have invalid mappings. It is important that you call init_node() first if you wish to provide your own argv. @type argv: [str] @param anonymous: if True, a name will be auto-generated for the node using name as the base. This is useful when you wish to have multiple instances of the same node and don't care about their actual names (e.g. tools, guis). name will be used as the stem of the auto-generated name. NOTE: you cannot remap the name of an anonymous node. @type anonymous: bool @param log_level: log level for sending message to /rosout and log file, which is INFO by default. For convenience, you may use rospy.DEBUG, rospy.INFO, rospy.ERROR, rospy.WARN, rospy.FATAL @type log_level: int @param disable_signals: If True, rospy will not register its own signal handlers. You must set this flag if (a) you are unable to call init_node from the main thread and/or you are using rospy in an environment where you need to control your own signal handling (e.g. WX). If you set this to True, you should call rospy.signal_shutdown(reason) to initiate clean shutdown. NOTE: disable_signals is overridden to True if roslib.is_interactive() is True. @type disable_signals: bool @param disable_rostime: for internal testing only: suppresses automatic subscription to rostime @type disable_rostime: bool @param disable_rosout: for internal testing only: suppress auto-publication of rosout @type disable_rostime: bool @param xmlrpc_port: If provided, it will use this port number for the client XMLRPC node. @type xmlrpc_port: int @param tcpros_port: If provided, the TCPROS server will listen for connections on this port @type tcpros_port: int @raise ROSInitException: if initialization/registration fails @raise ValueError: if parameters are invalid (e.g. name contains a namespace or is otherwise illegal) """ if argv is None: argv = sys.argv else: # reload the mapping table. Any previously created rospy data # structure does *not* reinitialize based on the new mappings. rospy.names.reload_mappings(argv) # this test can be eliminated once we change from warning to error in the next check if rosgraph.names.SEP in name: raise ValueError("namespaces are not allowed in node names") global _init_node_args # #972: allow duplicate init_node args if calls are identical # NOTE: we don't bother checking for node name aliases (e.g. 'foo' == '/foo'). if _init_node_args: if _init_node_args != (name, argv, anonymous, log_level, disable_rostime, disable_signals): raise rospy.exceptions.ROSException("rospy.init_node() has already been called with different arguments: "+str(_init_node_args)) else: return #already initialized # for scripting environments, we don't want to use the ROS signal # handlers disable_signals = disable_signals or roslib.is_interactive() _init_node_args = (name, argv, anonymous, log_level, disable_rostime, disable_signals) if not disable_signals: # NOTE: register_signals must be called from main thread rospy.core.register_signals() # add handlers for SIGINT/etc... else: logdebug("signal handlers for rospy disabled") # check for name override mappings = rospy.names.get_mappings() if '__name' in mappings: name = mappings['__name'] if anonymous: logdebug("[%s] WARNING: due to __name setting, anonymous setting is being changed to false"%name) anonymous = False if anonymous: # not as good as a uuid/guid, but more readable. can't include # hostname as that is not guaranteed to be a legal ROS name name = "%s_%s_%s"%(name, os.getpid(), int(time.time()*1000)) # check for legal base name once all changes have been made to the name if not rosgraph.names.is_legal_base_name(name): import warnings warnings.warn("'%s' is not a legal ROS base name. This may cause problems with other ROS tools."%name, stacklevel=2) # use rosgraph version of resolve_name to avoid remapping resolved_node_name = rosgraph.names.resolve_name(name, rospy.core.get_caller_id()) rospy.core.configure_logging(resolved_node_name) # #1810 rospy.names.initialize_mappings(resolved_node_name) logger = logging.getLogger("rospy.client") logger.info("init_node, name[%s], pid[%s]", resolved_node_name, os.getpid()) # node initialization blocks until registration with master node = rospy.impl.init.start_node(os.environ, resolved_node_name, port=xmlrpc_port, tcpros_port=tcpros_port) rospy.core.set_node_uri(node.uri) rospy.core.add_shutdown_hook(node.shutdown) if rospy.core.is_shutdown(): logger.warn("aborting node initialization as shutdown has been triggered") raise rospy.exceptions.ROSInitException("init_node interrupted before it could complete") # upload private params (set via command-line) to parameter server _init_node_params(argv, name) rospy.core.set_initialized(True) if not disable_rosout: rospy.impl.rosout.init_rosout() rospy.impl.rosout.load_rosout_handlers(log_level) if not disable_rostime: if not rospy.impl.simtime.init_simtime(): raise rospy.exceptions.ROSInitException("Failed to initialize time. Please check logs for additional details") else: rospy.rostime.set_rostime_initialized(True) logdebug("init_node, name[%s], pid[%s]", resolved_node_name, os.getpid()) # advertise logging level services Service('~get_loggers', GetLoggers, _get_loggers) Service('~set_logger_level', SetLoggerLevel, _set_logger_level) #_master_proxy is a MasterProxy wrapper _master_proxy = None _master_proxy_lock = Lock() 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, _master_proxy_lock if _master_proxy is None: with _master_proxy_lock: if _master_proxy is None: _master_proxy = rospy.msproxy.MasterProxy( rosgraph.get_master_uri()) return _master_proxy ######################################################### # Topic helpers def get_published_topics(namespace='/'): """ Retrieve list of topics that the master is reporting as being published. @return: List of topic names and types: [[topic1, type1]...[topicN, typeN]] @rtype: [[str, str]] """ code, msg, val = get_master().getPublishedTopics(namespace) if code != 1: raise rospy.exceptions.ROSException("unable to get published topics: %s"%msg) return val class _WFM(object): def __init__(self): self.msg = None def cb(self, msg): if self.msg is None: self.msg = msg def wait_for_message(topic, topic_type, timeout=None): """ Receive one message from topic. This will create a new subscription to the topic, receive one message, then unsubscribe. @param topic: name of topic @type topic: str @param topic_type: topic type @type topic_type: L{rospy.Message} class @param timeout: timeout time in seconds @type timeout: double @return: Message @rtype: L{rospy.Message} @raise ROSException: if specified timeout is exceeded @raise ROSInterruptException: if shutdown interrupts wait """ wfm = _WFM() s = None try: s = rospy.topics.Subscriber(topic, topic_type, wfm.cb) if timeout is not None: timeout_t = time.time() + timeout while not rospy.core.is_shutdown() and wfm.msg is None: rospy.rostime.wallsleep(0.01) if time.time() >= timeout_t: raise rospy.exceptions.ROSException("timeout exceeded while waiting for message on topic %s"%topic) else: while not rospy.core.is_shutdown() and wfm.msg is None: rospy.rostime.wallsleep(0.01) finally: if s is not None: s.unregister() if rospy.core.is_shutdown(): raise rospy.exceptions.ROSInterruptException("rospy shutdown") return wfm.msg ######################################################### # Param Server Access _param_server = None _param_server_lock = Lock() def _init_param_server(): """ Initialize parameter server singleton """ global _param_server, _param_server_lock if _param_server is None: with _param_server_lock: if _param_server is None: _param_server = get_master() return _param_server_lock # class and singleton to distinguish whether or not user has passed us a default value class _Unspecified(object): pass _unspecified = _Unspecified() def get_param(param_name, default=_unspecified): """ Retrieve a parameter from the param server NOTE: this method is thread-safe. @param default: (optional) default value to return if key is not set @type default: any @return: parameter value @rtype: XmlRpcLegalValue @raise ROSException: if parameter server reports an error @raise KeyError: if value not set and default is not given """ try: _init_param_server() return _param_server[param_name] #MasterProxy does all the magic for us except KeyError: if default != _unspecified: return default else: raise #except socket.error: # if default != _unspecified: # return default # else: # raise rospy.exceptions.ROSException("Unable to get parameter : %s" % param_name) def get_param_names(): """ Retrieve list of parameter names. NOTE: this method is thread-safe. @return: parameter names @rtype: [str] @raise ROSException: if parameter server reports an error """ _init_param_server() code, msg, val = _param_server.getParamNames() #MasterProxy does all the magic for us if code != 1: raise rospy.exceptions.ROSException("Unable to retrieve parameter names: %s"%msg) else: return val def set_param(param_name, param_value): """ Set a parameter on the param server NOTE: this method is thread-safe. @param param_name: parameter name @type param_name: str @param param_value: parameter value @type param_value: XmlRpcLegalValue @raise ROSException: if parameter server reports an error """ # #2202 if not rosgraph.names.is_legal_name(param_name): import warnings warnings.warn("'%s' is not a legal ROS graph resource name. This may cause problems with other ROS tools"%param_name, stacklevel=2) _init_param_server() _param_server[param_name] = param_value #MasterProxy does all the magic for us def search_param(param_name): """ Search for a parameter on the param server NOTE: this method is thread-safe. @param param_name: parameter name @type param_name: str @return: key of matching parameter or None if no matching parameter. @rtype: str @raise ROSException: if parameter server reports an error """ _init_param_server() return _param_server.search_param(param_name) def delete_param(param_name): """ Delete a parameter on the param server NOTE: this method is thread-safe. @param param_name: parameter name @type param_name: str @raise KeyError: if parameter is not set @raise ROSException: if parameter server reports an error """ _init_param_server() del _param_server[param_name] #MasterProxy does all the magic for us def has_param(param_name): """ Test if parameter exists on the param server NOTE: this method is thread-safe. @param param_name: parameter name @type param_name: str @raise ROSException: if parameter server reports an error """ _init_param_server() return param_name in _param_server #MasterProxy does all the magic for us
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/__init__.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Copyright (c) 2008, Willow Garage, Inc. # Revision $Id$ """ ROS client library for Python. See U{http://ros.org/wiki/rospy} @author: Ken Conley (kwc) """ # import symbols into rospy namespace # NOTE: there are much better ways to configure python module # dictionaries, but the rospy codebase isn't quite in shape for that # yet from std_msgs.msg import Header from .client import spin, myargv, init_node, \ get_published_topics, \ wait_for_message, \ get_master, \ on_shutdown, \ get_param, get_param_names, set_param, delete_param, has_param, search_param,\ DEBUG, INFO, WARN, ERROR, FATAL from .timer import sleep, Rate, Timer from .core import is_shutdown, signal_shutdown, \ get_node_uri, get_ros_root, \ logdebug, logwarn, loginfo, logout, logerr, logfatal, \ logdebug_throttle, logwarn_throttle, loginfo_throttle, logerr_throttle, logfatal_throttle, \ parse_rosrpc_uri from .exceptions import * from .msg import AnyMsg from .msproxy import MasterProxy from .names import get_name, get_caller_id, get_namespace, resolve_name, remap_name from .rostime import Time, Duration, get_rostime, get_time from .service import ServiceException # - use tcp ros implementation of services from .impl.tcpros_service import Service, ServiceProxy, wait_for_service from .topics import Message, SubscribeListener, Publisher, Subscriber ## \defgroup validators Validators ## \defgroup clientapi Client API __all__ = [ 'Header', 'spin', 'myargv', 'init_node', 'get_master', 'get_published_topics', 'wait_for_service', 'on_shutdown', 'get_param', 'get_param_names', 'set_param', 'delete_param', 'has_param', 'search_param', 'sleep', 'Rate', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL' 'is_shutdown', 'signal_shutdown', 'get_node_uri', 'get_ros_root', 'logdebug', 'logwarn', 'loginfo', 'logout', 'logerr', 'logfatal', 'logdebug_throttle', 'logwarn_throttle', 'loginfo_throttle', 'logerr_throttle', 'logfatal_throttle', 'parse_rosrpc_uri', 'MasterProxy', 'NodeProxy', 'ROSException', 'ROSSerializationException', 'ROSInitException', 'ROSInterruptException', 'ROSInternalException', 'TransportException', 'TransportTerminated', 'TransportInitError', 'AnyMsg', 'Message', 'get_name', 'get_caller_id', 'get_namespace', 'resolve_name', 'remap_name', 'Time', 'Duration', 'get_rostime', 'get_time', 'ServiceException', 'Service', 'ServiceProxy', 'SubscribeListener', 'Publisher', 'Subscriber', ]
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/core.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """rospy internal core implementation library""" import atexit try: import cPickle as pickle except ImportError: import pickle import inspect import logging import os import signal import sys import threading import time import traceback import types try: import urllib.parse as urlparse #Python 3.x except ImportError: import urlparse try: import xmlrpc.client as xmlrpcclient #Python 3.x except ImportError: import xmlrpclib as xmlrpcclient #Python 2.x import rospkg import rosgraph.roslogging import rospy.exceptions import rospy.rostime from rospy.names import * from rospy.impl.validators import ParameterInvalid from rosgraph_msgs.msg import Log _logger = logging.getLogger("rospy.core") # number of seconds to wait to join on threads. network issue can # cause joins to be not terminate gracefully, and it's better to # teardown dirty than to hang _TIMEOUT_SHUTDOWN_JOIN = 5. import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def newFunc(*args, **kwargs): warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning, stacklevel=2) return func(*args, **kwargs) newFunc.__name__ = func.__name__ newFunc.__doc__ = func.__doc__ newFunc.__dict__.update(func.__dict__) return newFunc ######################################################### # ROSRPC ROSRPC = "rosrpc://" def parse_rosrpc_uri(uri): """ utility function for parsing ROS-RPC URIs @param uri: ROSRPC URI @type uri: str @return: address, port @rtype: (str, int) @raise ParameterInvalid: if uri is not a valid ROSRPC URI """ if uri.startswith(ROSRPC): dest_addr = uri[len(ROSRPC):] else: raise ParameterInvalid("Invalid protocol for ROS service URL: %s"%uri) try: if '/' in dest_addr: dest_addr = dest_addr[:dest_addr.find('/')] dest_addr, dest_port = dest_addr.split(':') dest_port = int(dest_port) except: raise ParameterInvalid("ROS service URL is invalid: %s"%uri) return dest_addr, dest_port ######################################################### # rospy logger _rospy_logger = logging.getLogger("rospy.internal") # we keep a separate, non-rosout log file to contain stack traces and # other sorts of information that scare users but are essential for # debugging def rospydebug(msg, *args): """Internal rospy client library debug logging""" _rospy_logger.debug(msg, *args) def rospyinfo(msg, *args): """Internal rospy client library debug logging""" _rospy_logger.info(msg, *args) def rospyerr(msg, *args): """Internal rospy client library error logging""" _rospy_logger.error(msg, *args) def rospywarn(msg, *args): """Internal rospy client library warn logging""" _rospy_logger.warn(msg, *args) logdebug = logging.getLogger('rosout').debug logwarn = logging.getLogger('rosout').warning loginfo = logging.getLogger('rosout').info logout = loginfo # alias deprecated name logerr = logging.getLogger('rosout').error logerror = logerr # alias logerr logfatal = logging.getLogger('rosout').critical class LoggingThrottle(object): last_logging_time_table = {} def __call__(self, caller_id, logging_func, period, msg): """Do logging specified message periodically. - caller_id (str): Id to identify the caller - logging_func (function): Function to do logging. - period (float): Period to do logging in second unit. - msg (object): Message to do logging. """ now = rospy.Time.now() last_logging_time = self.last_logging_time_table.get(caller_id) if (last_logging_time is None or (now - last_logging_time) > rospy.Duration(period)): logging_func(msg) self.last_logging_time_table[caller_id] = now _logging_throttle = LoggingThrottle() def _frame_record_to_caller_id(frame_record): frame, _, lineno, _, code, _ = frame_record caller_id = ( inspect.getabsfile(frame), lineno, frame.f_lasti, ) return pickle.dumps(caller_id) def logdebug_throttle(period, msg): caller_id = _frame_record_to_caller_id(inspect.stack()[1]) _logging_throttle(caller_id, logdebug, period, msg) def loginfo_throttle(period, msg): caller_id = _frame_record_to_caller_id(inspect.stack()[1]) _logging_throttle(caller_id, loginfo, period, msg) def logwarn_throttle(period, msg): caller_id = _frame_record_to_caller_id(inspect.stack()[1]) _logging_throttle(caller_id, logwarn, period, msg) def logerr_throttle(period, msg): caller_id = _frame_record_to_caller_id(inspect.stack()[1]) _logging_throttle(caller_id, logerr, period, msg) def logfatal_throttle(period, msg): caller_id = _frame_record_to_caller_id(inspect.stack()[1]) _logging_throttle(caller_id, logfatal, period, msg) ######################################################### # CONSTANTS MASTER_NAME = "master" #master is a reserved node name for the central master import warnings import functools def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" @functools.wraps(func) def newFunc(*args, **kwargs): warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning, stacklevel=2) return func(*args, **kwargs) return newFunc @deprecated def get_ros_root(required=False, env=None): """ Get the value of ROS_ROOT. @param env: override environment dictionary @type env: dict @param required: if True, fails with ROSException @return: Value of ROS_ROOT environment @rtype: str @raise ROSException: if require is True and ROS_ROOT is not set """ if env is None: env = os.environ ros_root = rospkg.get_ros_root(env) if required and not ros_root: raise rospy.exceptions.ROSException('%s is not set'%rospkg.environment.ROS_ROOT) return ros_root ######################################################### # API _uri = None def get_node_uri(): """ Get this Node's URI. @return: this Node's XMLRPC URI @rtype: str """ return _uri def set_node_uri(uri): """set the URI of the local node. This is an internal API method, it does not actually affect the XMLRPC URI of the Node.""" global _uri _uri = uri ######################################################### # Logging _log_filename = None def configure_logging(node_name, level=logging.INFO): """ Setup filesystem logging for this node @param node_name: Node's name @type node_name str @param level: (optional) Python logging level (INFO, DEBUG, etc...). (Default: logging.INFO) @type level: int """ global _log_filename # #988 __log command-line remapping argument mappings = get_mappings() if '__log' in get_mappings(): logfilename_remap = mappings['__log'] filename = os.path.abspath(logfilename_remap) else: # fix filesystem-unsafe chars filename = node_name.replace('/', '_') + '.log' if filename[0] == '_': filename = filename[1:] if not filename: raise rospy.exceptions.ROSException('invalid configure_logging parameter: %s'%node_name) _log_filename = rosgraph.roslogging.configure_logging('rospy', level, filename=filename) class NullHandler(logging.Handler): def emit(self, record): pass # keep logging happy until we have the node name to configure with logging.getLogger('rospy').addHandler(NullHandler()) ######################################################### # Init/Shutdown/Exit API and Handlers _client_ready = False def is_initialized(): """ Get the initialization state of the local node. If True, node has been configured. @return: True if local node initialized @rtype: bool """ return _client_ready def set_initialized(initialized): """ set the initialization state of the local node @param initialized: True if node initialized @type initialized: bool """ global _client_ready _client_ready = initialized _shutdown_lock = threading.RLock() # _shutdown_flag flags that rospy is in shutdown mode, in_shutdown # flags that the shutdown routine has started. These are separate # because 'pre-shutdown' hooks require rospy to be in a non-shutdown # mode. These hooks are executed during the shutdown routine. _shutdown_flag = False _in_shutdown = False # various hooks to call on shutdown. shutdown hooks are called in the # shutdown state, preshutdown are called just before entering shutdown # state, and client shutdown is called before both of these. _shutdown_hooks = [] _preshutdown_hooks = [] _client_shutdown_hooks = [] # threads that must be joined on shutdown _shutdown_threads = [] _signalChain = {} def is_shutdown(): """ @return: True if shutdown flag has been set @rtype: bool """ return _shutdown_flag def is_shutdown_requested(): """ is_shutdown_requested is a state that occurs just before is_shutdown. It is initiated when a shutdown requested is received and continues until client shutdown handlers have been called. After client shutdown handlers have been serviced, the is_shutdown state becomes true. @return: True if shutdown has been requested (but possibly not yet initiated) @rtype: bool """ return _in_shutdown def _add_shutdown_hook(h, hooks, pass_reason_argument=True): """ shared implementation of add_shutdown_hook and add_preshutdown_hook """ if not callable(h): raise TypeError("shutdown hook [%s] must be a function or callable object: %s"%(h, type(h))) if _shutdown_flag: _logger.warn("add_shutdown_hook called after shutdown") if pass_reason_argument: h("already shutdown") else: h() return with _shutdown_lock: if hooks is None: # race condition check, don't log as we are deep into shutdown return hooks.append(h) def _add_shutdown_thread(t): """ Register thread that must be joined() on shutdown """ if _shutdown_flag: #TODO return with _shutdown_lock: if _shutdown_threads is None: # race condition check, don't log as we are deep into shutdown return # in order to prevent memory leaks, reap dead threads. The # last thread may not get reaped until shutdown, but this is # relatively minor for other in _shutdown_threads[:]: if not other.isAlive(): _shutdown_threads.remove(other) _shutdown_threads.append(t) def add_client_shutdown_hook(h): """ Add client method to invoke when system shuts down. Unlike L{add_shutdown_hook} and L{add_preshutdown_hooks}, these methods will be called before any rospy internal shutdown code. @param h: function with zero args @type h: fn() """ _add_shutdown_hook(h, _client_shutdown_hooks, pass_reason_argument=False) def add_preshutdown_hook(h): """ Add method to invoke when system shuts down. Unlike L{add_shutdown_hook}, these methods will be called before any other shutdown hooks. @param h: function that takes in a single string argument (shutdown reason) @type h: fn(str) """ _add_shutdown_hook(h, _preshutdown_hooks) def add_shutdown_hook(h): """ Add method to invoke when system shuts down. Shutdown hooks are called in the order that they are registered. This is an internal API method that is used to cleanup. See the client X{on_shutdown()} method if you wish to register client hooks. @param h: function that takes in a single string argument (shutdown reason) @type h: fn(str) """ _add_shutdown_hook(h, _shutdown_hooks) def signal_shutdown(reason): """ Initiates shutdown process by signaling objects waiting on _shutdown_lock. Shutdown and pre-shutdown hooks are invoked. @param reason: human-readable shutdown reason, if applicable @type reason: str """ global _shutdown_flag, _in_shutdown, _shutdown_lock, _shutdown_hooks _logger.info("signal_shutdown [%s]"%reason) if _shutdown_flag or _in_shutdown: return with _shutdown_lock: if _shutdown_flag or _in_shutdown: return _in_shutdown = True # make copy just in case client re-invokes shutdown for h in _client_shutdown_hooks: try: # client shutdown hooks do not accept a reason arg h() except: traceback.print_exc() del _client_shutdown_hooks[:] for h in _preshutdown_hooks: try: h(reason) except: traceback.print_exc() del _preshutdown_hooks[:] # now that pre-shutdown hooks have been called, raise shutdown # flag. This allows preshutdown hooks to still publish and use # service calls properly _shutdown_flag = True for h in _shutdown_hooks: try: h(reason) except Exception as e: sys.stderr.write("signal_shutdown hook error[%s]\n"%e) del _shutdown_hooks[:] threads = _shutdown_threads[:] for t in threads: if t.isAlive(): t.join(_TIMEOUT_SHUTDOWN_JOIN) del _shutdown_threads[:] try: rospy.rostime.wallsleep(0.1) #hack for now until we get rid of all the extra threads except KeyboardInterrupt: pass def _ros_signal(sig, stackframe): signal_shutdown("signal-"+str(sig)) prev_handler = _signalChain.get(sig, None) if prev_handler is not None and not type(prev_handler) == int: try: prev_handler(sig, stackframe) except KeyboardInterrupt: pass #filter out generic keyboard interrupt handler def _ros_atexit(): signal_shutdown('atexit') atexit.register(_ros_atexit) # #687 def register_signals(): """ register system signal handlers for SIGTERM and SIGINT """ _signalChain[signal.SIGTERM] = signal.signal(signal.SIGTERM, _ros_signal) _signalChain[signal.SIGINT] = signal.signal(signal.SIGINT, _ros_signal) # Validators ###################################### def is_topic(param_name): """ Validator that checks that parameter is a valid ROS topic name """ def validator(param_value, caller_id): v = valid_name_validator_resolved(param_name, param_value, caller_id) if param_value == '/': raise ParameterInvalid("ERROR: parameter [%s] cannot be the global namespace"%param_name) return v return validator def xmlrpcapi(uri): """ @return: instance for calling remote server or None if not a valid URI @rtype: xmlrpclib.ServerProxy """ if uri is None: return None uriValidate = urlparse.urlparse(uri) if not uriValidate[0] or not uriValidate[1]: return None return xmlrpcclient.ServerProxy(uri)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/rosconsole.py
# Software License Agreement (BSD License) # # Copyright (c) 2015, Chris Mansley, Open Source Robotics Foundation, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from __future__ import print_function import os import socket import sys import rosgraph import rospy from .logger_level_service_caller import LoggerLevelServiceCaller from .logger_level_service_caller import ROSConsoleException NAME = 'rosconsole' def error(status, msg): print("%s: error: %s" % (NAME, msg), file=sys.stderr) sys.exit(status) def _get_cmd_list_optparse(): from optparse import OptionParser usage = "usage: %prog list <node>" parser = OptionParser(usage=usage, prog=NAME) return parser def _rosconsole_cmd_list(argv): args = argv[2:] parser = _get_cmd_list_optparse() (options, args) = parser.parse_args(args) if not args: parser.error("you must specify a node to list loggers") elif len(args) > 1: parser.error("you may only specify one node to list") logger_level = LoggerLevelServiceCaller() loggers = logger_level.get_loggers(args[0]) output = '\n'.join(loggers) print(output) def _get_cmd_set_optparse(): from optparse import OptionParser usage = "usage: %prog set <node> <logger> <level>" levels = ', '.join(LoggerLevelServiceCaller().get_levels()) usage += "\n\n <level> must be one of [" + levels + "]" parser = OptionParser(usage=usage, prog=NAME) return parser def _rosconsole_cmd_set(argv): args = argv[2:] parser = _get_cmd_set_optparse() (options, args) = parser.parse_args(args) if len(args) < 3: parser.error("you must specify a node, a logger and a level") logger_level = LoggerLevelServiceCaller() logger_level.get_loggers(args[0]) if args[1] not in logger_level._current_levels: error(2, "node " + args[0] + " does not contain logger " + args[1]) level = args[2].lower() if level not in logger_level.get_levels(): parser.error("invalid level") logger_level.send_logger_change_message(args[0], args[1], args[2]) def _get_cmd_get_optparse(): from optparse import OptionParser usage = "usage: %prog get <node> <logger>" parser = OptionParser(usage=usage, prog=NAME) return parser def _rosconsole_cmd_get(argv): args = argv[2:] parser = _get_cmd_get_optparse() (options, args) = parser.parse_args(args) if len(args) < 2: parser.error("you must specify a node and a logger") logger_level = LoggerLevelServiceCaller() logger_level.get_loggers(args[0]) if args[1] not in logger_level._current_levels: error(2, "node " + args[0] + " does not contain logger " + args[1]) print(logger_level._current_levels[args[1]]) def _fullusage(): print("""rosconsole is a command-line tool for configuring the logger level of ROS nodes. Commands: \trosconsole get\tdisplay level for a logger \trosconsole list\tlist loggers for a node \trosconsole set\tset level for a logger Type rosconsole <command> -h for more detailed usage, e.g. 'rosconsole list -h' """) sys.exit(getattr(os, 'EX_USAGE', 1)) def main(argv=None): if argv is None: argv = sys.argv # Initialize ourselves as a node, to ensure handling of namespace and # remapping arguments rospy.init_node('rosconsole', anonymous=True) argv = rospy.myargv(argv) # process argv if len(argv) == 1: _fullusage() try: command = argv[1] if command == 'get': _rosconsole_cmd_get(argv) elif command == 'list': _rosconsole_cmd_list(argv) elif command == 'set': _rosconsole_cmd_set(argv) else: _fullusage() except socket.error as e: error(1, "Network communication failed; most likely failed to communicate with master: %s" % e) except rosgraph.MasterException as e: # mainly for invalid master URI/rosgraph.masterapi error(1, str(e)) except ROSConsoleException as e: error(1, str(e)) except KeyboardInterrupt: pass except rospy.ROSInterruptException: pass
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/names.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Support for ROS Names See: U{http://www.ros.org/wiki/Names} """ import sys import os from rosgraph.names import namespace, get_ros_namespace, ns_join, make_global_ns, load_mappings, \ SEP, GLOBALNS, REMAP, ANYTYPE, \ is_global, is_private import rosgraph.names from rospy.exceptions import ROSException from rospy.impl.validators import ParameterInvalid TOPIC_ANYTYPE = ANYTYPE #indicates that a subscriber will connect any datatype given to it SERVICE_ANYTYPE = ANYTYPE #indicates that a service client does not have a fixed type import struct if sys.hexversion > 0x03000000: #Python3 def isstring(s): return isinstance(s, str) #Python 3.x else: def isstring(s): return isinstance(s, basestring) #Python 2.x def canonicalize_name(name): """ Put name in canonical form. Double slashes '//' are removed and name is returned without any trailing slash, e.g. /foo/bar @param name: ROS name @type name: str """ if not name or name == SEP: return name elif name[0] == SEP: return '/' + '/'.join([x for x in name.split(SEP) if x]) else: return '/'.join([x for x in name.split(SEP) if x]) ##if len(name) > 1 and name[-1] == SEP: ## return name[:-1] ##return name # Mappings override name resolution by substituting fully-qualified # names in for local name references. They override any name # reference, with exception of '.local' names. We load remapping args # as soon as client API is referenced so that they are initialized # before Topic constructors are invoked. _mappings = load_mappings(sys.argv) _resolved_mappings = {} def reload_mappings(argv): """ Re-initialize the name remapping table. @param argv: Command line arguments to this program. ROS reads these arguments to find renaming params. @type argv: [str] """ global _mappings _mappings = load_mappings(argv) # #1810 def initialize_mappings(node_name): """ Initialize the remapping table based on provide node name. @param node_name: name of node (caller ID) @type node_name: str """ global _resolved_mappings _resolved_mappings = {} for m,v in _mappings.items(): # resolve both parts of the mappings. use the rosgraph.names # version of resolve_name to avoid circular mapping. if m.startswith('__'): # __name, __log, etc... _resolved_mappings[m] = v else: _resolved_mappings[rosgraph.names.resolve_name(m, node_name)] = rosgraph.names.resolve_name(v, node_name) def resolve_name_without_node_name(name): """ The need for this function is complicated -- Topics and Services can be created before init_node is called. In general, this is okay, unless the name is a ~name, in which case we have to raise an ValueError @param name: ROS name to resolve @type name: str @raise ValueError: if name is a ~name @raise ROSInitException: if name is remapped to a ~name """ if is_private(name): raise ValueError("~name topics cannot be created before init_node() has been called") # we use the underlying rosgraph.names.resolve_name to avoid dependencies on nodename/remappings fake_caller_id = ns_join(get_namespace(), 'node') fake_resolved = rosgraph.names.resolve_name(name, fake_caller_id) for m, v in _mappings.items(): if rosgraph.names.resolve_name(m, fake_caller_id) == fake_resolved: if is_private(name): raise ROSInitException("due to the way this node is written, %s cannot be remapped to a ~name. \nThe declaration of topics/services must be moved after the call to init_node()"%name) else: return rosgraph.names.resolve_name(v, fake_caller_id) return fake_resolved def get_mappings(): """ Get mapping table with unresolved names @return: command-line remappings {name: name} @rtype: {str: str} """ return _mappings def get_resolved_mappings(): """ Get mapping table with resolved names @return: command-line remappings {name: name} @rtype: {str: str} """ return _resolved_mappings #TODO: port to a wrapped call to rosgraph.names.resolve_name def resolve_name(name, caller_id=None): """ Resolve a ROS name to its global, canonical form. Private ~names are resolved relative to the node name. @param name: name to resolve. @type name: str @param caller_id: node name to resolve relative to. To resolve to local namespace, omit this parameter (or use None) @type caller_id: str @return: Resolved name. If name is empty/None, resolve_name returns parent namespace. If namespace is empty/None, @rtype: str """ if not caller_id: caller_id = get_name() if not name: #empty string resolves to namespace return namespace(caller_id) name = str(name) # enforce string conversion else struct.pack might raise UnicodeDecodeError (see #3998) name = canonicalize_name(name) if name[0] == SEP: #global name resolved_name = name elif is_private(name): #~name resolved_name = ns_join(caller_id, name[1:]) else: #relative resolved_name = namespace(caller_id) + name #Mappings override general namespace-based resolution # - do this before canonicalization as remappings are meant to # match the name as specified in the code if resolved_name in _resolved_mappings: return _resolved_mappings[resolved_name] else: return resolved_name def remap_name(name, caller_id=None, resolved=True): """ Remap a ROS name. This API should be used to instead of resolve_name for APIs in which you don't wish to resolve the name unless it is remapped. @param name: name to remap @type name: str @param resolved: if True (default), use resolved names in remappings, which is the standard for ROS. @type resolved: bool @return: Remapped name @rtype: str """ if not caller_id: caller_id = get_caller_id() if name in _mappings: return rosgraph.names.resolve_name(_mappings[name], caller_id) return name def scoped_name(caller_id, name): """ Convert the global caller_id to a relative name within the namespace. For example, for namespace '/foo' and name '/foo/bar/name', the return value will be 'bar/name' WARNING: scoped_name does not validate that name is actually within the supplied namespace. @param caller_id: caller ID, in canonical form @type caller_id: str @param name: name to scope @type name: str @return: name scoped to the caller_id's namespace. @rtype: str """ if not is_global(caller_id): raise ROSException("caller_id must be global") return canonicalize_name(name)[len(namespace(caller_id)):] ################################################### # Name validators ############################ #Technically XMLRPC will never send a None, but I don't want to code masterslave.py to be #XML-RPC specific in this way. def valid_name_validator_resolved(param_name, param_value, caller_id): if not param_value or not isstring(param_value): raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name) #TODO: actual validation of chars # I added the colon check as the common error will be to send an URI instead of name if ':' in param_value or ' ' in param_value: raise ParameterInvalid("ERROR: parameter [%s] contains illegal chars"%param_name) #don't use our own resolve_name because we do not want to remap return rosgraph.names.resolve_name(param_value, caller_id, remappings=None) def valid_name_validator_unresolved(param_name, param_value, caller_id): if not param_value or not isstring(param_value): raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name) #TODO: actual validation of chars # I added the colon check as the common error will be to send an URI instead of name if ':' in param_value or ' ' in param_value: raise ParameterInvalid("ERROR: parameter [%s] contains illegal chars"%param_name) return param_value def valid_name(param_name, resolve=True): """ Validator that resolves names and also ensures that they are not empty @param param_name: name @type param_name: str @param resolve: if True/omitted, the name will be resolved to a global form. Otherwise, no resolution occurs. @type resolve: bool @return: resolved parameter value @rtype: str """ def validator(param_value, caller_id): if resolve: return valid_name_validator_resolved(param_name, param_value, caller_id) return valid_name_validator_unresolved(param_name, param_value, caller_id) return validator def global_name(param_name): """ Validator that checks for valid, global graph resource name. @return: parameter value @rtype: str """ def validator(param_value, caller_id): if not param_value or not isstring(param_value): raise ParameterInvalid("ERROR: parameter [%s] must be a non-empty string"%param_name) #TODO: actual validation of chars if not is_global(param_value): raise ParameterInvalid("ERROR: parameter [%s] must be a globally referenced name"%param_name) return param_value return validator ######################################################### #Global Namespace Routines # - Global state, e.g. singletons and namespace _caller_namespace = get_ros_namespace() _caller_id = _caller_namespace+'unnamed' #default for non-node. def get_namespace(): """ Get namespace of local node. @return: fully-qualified name of local node or '' if not applicable @rtype: str """ return _caller_namespace def get_name(): """ Get fully resolved name of local node. If this is not a node, use empty string @return: fully-qualified name of local node or '' if not applicable @rtype: str """ return _caller_id # backwards compatibility get_caller_id = get_name def _set_caller_id(caller_id): """ Internal API. Set the global name (i.e. caller_id) and namespace. Methods can check what the name of the current node is by calling get_caller_id. The caller_id is important as it is the first parameter to any API call on a remote node. Invoked by ROSNode constructor @param caller_id: new caller ID @type caller_id: str """ global _caller_id, _caller_namespace _caller_id = caller_id _caller_namespace = namespace(caller_id)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/numpy_msg.py
# Software License Agreement (BSD License) # # Copyright (c) 2009, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Support for using numpy with rospy messages. For tutorials, see U{http://www.ros.org/wiki/rospy_tutorials/Tutorials/numpy} Listener example:: from rospy.numpy_msg import numpy_msg rospy.init_node('mynode') rospy.Subscriber("mytopic", numpy_msg(TopicType) Publisher example:: from rospy.numpy_msg import numpy_msg import numpy pub = rospy.Publisher('mytopic', numpy_msg(TopicType), queue_size=10) rospy.init_node('mynode') a = numpy.array([1.0, 2.1, 3.2, 4.3, 5.4, 6.5], dtype=numpy.float32) pub.publish(a) """ import numpy # TODO: we will need to generate a new type structure with # little-endian specified and then pass that type structure into the # *_numpy calls. def _serialize_numpy(self, buff): """ wrapper for factory-generated class that passes numpy module into serialize """ # pass in numpy module reference to prevent import in auto-generated code return self.serialize_numpy(buff, numpy) def _deserialize_numpy(self, str): """ wrapper for factory-generated class that passes numpy module into deserialize """ # pass in numpy module reference to prevent import in auto-generated code return self.deserialize_numpy(str, numpy) _numpy_msg_types = {} ## Use this function to generate message instances using numpy array ## types for numerical arrays. ## @msg_type Message class: call this functioning on the message type that you pass ## into a Publisher or Subscriber call. ## @returns Message class def numpy_msg(msg_type): if msg_type in _numpy_msg_types: return _numpy_msg_types[msg_type] classdict = { '__slots__': msg_type.__slots__, '_slot_types': msg_type._slot_types, '_md5sum': msg_type._md5sum, '_type': msg_type._type, '_has_header': msg_type._has_header, '_full_text': msg_type._full_text, 'serialize': _serialize_numpy, 'deserialize': _deserialize_numpy, 'serialize_numpy': msg_type.serialize_numpy, 'deserialize_numpy': msg_type.deserialize_numpy } # create the numpy message type msg_type_name = "Numpy_%s"%msg_type._type.replace('/', '__') numpy_type = type(msg_type_name,(msg_type,),classdict) _numpy_msg_types[msg_type] = numpy_type return numpy_type
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/topics.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ rospy implementation of topics. Client API ========== L{Publisher} and L{Subscriber} are the client API for topics. Internal Implementation ======================= Internally, L{_TopicImpl} instances (_PublisherImpl/_SubscriberImpl) are used to manage actual transport connections. The L{_TopicManager} is responsible for tracking the system-wide state of publications and subscriptions as well as the L{_TopicImpl} instances. More info is below. L{_TopicManager} ================ The L{_TopicManager} does the backend topic bookkeeping for the local node. Use L{get_topic_manager()} to access singleton. Actual topic implementations are done through the L{_TopicImpl}/L{_PublisherImpl}/L{_SubscriberImpl} hierarchy. Client code generates instances of type L{Publisher}/L{Subscriber}, which enable to client to create multiple publishers/subscribers of that topic that get controlled access to the underlying share connections. Common parent classes for all rospy topics. The rospy topic autogenerators create classes that are children of these implementations. """ from rospy.impl.registration import get_service_manager, get_broadcast_manager import struct import select import ctypes try: from cStringIO import StringIO #Python 2.x python3 = 0 def isstring(s): return isinstance(s, basestring) #Python 2.x except ImportError: python3 = 1 from io import StringIO, BytesIO #Python 3.x def isstring(s): return isinstance(s, str) #Python 3.x import threading import logging import time from itertools import chain import traceback import rosgraph.names from rospy.core import * from rospy.exceptions import ROSSerializationException, TransportTerminated from rospy.msg import serialize_message, args_kwds_to_message from rospy.impl.statistics import SubscriberStatisticsLogger from rospy.impl.registration import get_topic_manager, set_topic_manager, Registration, get_registration_listeners from rospy.impl.tcpros import get_tcpros_handler, DEFAULT_BUFF_SIZE from rospy.impl.tcpros_pubsub import QueuedConnection _logger = logging.getLogger('rospy.topics') # wrap genpy implementation and map it to rospy namespace import genpy Message = genpy.Message import roslib.message import google.protobuf # socket_base = "/socket_topic" ####################################################################### # Base classes for all client-API instantiated pub/sub # # There are two trees: Topic and _TopicImpl. Topic is the client API # for interfacing with topics, while _TopicImpl implements the # underlying connection details. class Topic(object): """Base class of L{Publisher} and L{Subscriber}""" def __init__(self, name, data_class, reg_type): """ @param name: graph resource name of topic, e.g. 'laser'. @type name: str @param data_class: message class for serialization @type data_class: L{Message} @param reg_type Registration.PUB or Registration.SUB @type reg_type: str @raise ValueError: if parameters are invalid """ if not name or not isstring(name): raise ValueError("topic name is not a non-empty string") try: if python3 == 1: name.encode("utf-8") else: name = name.encode("utf-8") except UnicodeError: raise ValueError("topic name must be ascii/utf-8 compatible") if data_class is None: raise ValueError("topic parameter 'data_class' is not initialized") if not type(data_class) == type and not issubclass(data_class, google.protobuf.message.Message): raise ValueError("data_class [%s] is not a class"%data_class) if not issubclass(data_class, genpy.Message) and not issubclass(data_class, google.protobuf.message.Message): raise ValueError("data_class [%s] is not a message data class"%data_class.__class__.__name__) # #2202 if not rosgraph.names.is_legal_name(name): import warnings warnings.warn("'%s' is not a legal ROS graph resource name. This may cause problems with other ROS tools"%name, stacklevel=2) # this is a bit ugly, but necessary due to the fact that we allow # topics and services to be initialized before the node if not rospy.core.is_initialized(): self.resolved_name = rospy.names.resolve_name_without_node_name(name) else: # init_node() has been called, so we can do normal resolution self.resolved_name = resolve_name(name) self.name = self.resolved_name # #1810 for backwards compatibility roslib.message.add_rosmsg_interface_for_protobuf(data_class) self.data_class = data_class self.type = data_class._type self.md5sum = data_class._md5sum self.reg_type = reg_type self.impl = get_topic_manager().acquire_impl(reg_type, self.resolved_name, data_class) def get_num_connections(self): """ get the number of connections to other ROS nodes for this topic. For a Publisher, this corresponds to the number of nodes subscribing. For a Subscriber, the number of publishers. @return: number of connections @rtype: int """ return self.impl.get_num_connections() def unregister(self): """ unpublish/unsubscribe from topic. Topic instance is no longer valid after this call. Additional calls to unregister() have no effect. """ # as we don't guard unregister, have to protect value of # resolved_name for release_impl call resolved_name = self.resolved_name if resolved_name and self.impl: get_topic_manager().release_impl(self.reg_type, resolved_name) self.impl = self.resolved_name = self.type = self.md5sum = self.data_class = None # #3808 class Poller(object): """ select.poll/kqueue abstraction to handle socket failure detection on multiple platforms. NOT thread-safe. """ def __init__(self): try: self.poller = select.poll() self.add_fd = self.add_poll self.remove_fd = self.remove_poll self.error_iter = self.error_poll_iter except: try: # poll() not available, try kqueue self.poller = select.kqueue() self.add_fd = self.add_kqueue self.remove_fd = self.remove_kqueue self.error_iter = self.error_kqueue_iter self.kevents = [] except: #TODO: non-Noop impl for Windows self.poller = self.noop self.add_fd = self.noop self.remove_fd = self.noop self.error_iter = self.noop_iter def noop(self, *args): pass def noop_iter(self): empty_generator = (x for x in list()) for x in empty_generator: yield x def add_poll(self, fd): self.poller.register(fd) def remove_poll(self, fd): self.poller.unregister(fd) def error_poll_iter(self): events = self.poller.poll(0) for fd, event in events: if event & (select.POLLHUP | select.POLLERR): yield fd def add_kqueue(self, fd): self.kevents.append(select.kevent(fd)) def error_kqueue_iter(self): events = self.poller.control(self.kevents, 0) for event in events: if event & (select.KQ_EV_ERROR | select.KQ_EV_EOF): yield event.ident def remove_kqueue(self, fd): e = [x for x in self.kevents if x.ident == fd] for x in e: self.kevents.remove(x) class _TopicImpl(object): """ Base class of internal topic implementations. Each topic has a singleton _TopicImpl implementation for managing the underlying connections. """ def __init__(self, name, data_class): """ Base constructor @param name: graph resource name of topic, e.g. 'laser'. @type name: str @param data_class: message data class @type data_class: L{Message} """ # #1810 made resolved/unresolved more explicit so we don't accidentally double-resolve self.resolved_name = resolve_name(name) #NOTE: remapping occurs here! self.name = self.resolved_name # for backwards compatibility self.data_class = data_class self.type = data_class._type self.handler = None self.seq = 0 # lock is used for to serialize call order that methods that # modify self.connections. Because add/removing connections is # a rare event, we go through the extra hassle of making a # copy of the connections/callbacks lists # when modifying, then setting the reference to the new copy. # With this pattern, other code can use these lists without # having to acquire c_lock self.c_lock = threading.RLock() self.connections = [] self.closed = False # number of Topic instances using this self.ref_count = 0 self.connection_poll = Poller() self._libshm_manager_file = os.path.join( os.environ['ROS_ROOT'], "../../lib/", "libshm_manager.so") self._pdll = ctypes.CDLL(self._libshm_manager_file) def __del__(self): # very similar to close(), but have to be more careful in a __del__ what we call if self.closed: return if self.connections is not None: for c in self.connections: try: c.close() except: pass del self.connections[:] self.c_lock = self.connections = self.handler = self.data_class = self.type = None def close(self): """close I/O""" if self.closed: return self.closed = True if self.c_lock is not None: with self.c_lock: for c in self.connections: try: if c is not None: c.close() except: # seems more logger.error internal than external logerr _logger.error(traceback.format_exc()) del self.connections[:] self.handler = None def get_num_connections(self): with self.c_lock: return len(self.connections) def has_connection(self, endpoint_id): """ Query whether or not a connection with the associated \a endpoint has been added to this object. @param endpoint_id: endpoint ID associated with connection. @type endpoint_id: str """ # save reference to avoid lock conn = self.connections for c in conn: if c.endpoint_id == endpoint_id: return True return False def has_connections(self): """ Check to see if this topic is connected to other publishers/subscribers @return: True if topic is connected @rtype: bool """ if self.connections: return True return False def _remove_connection(self, connections, c): # Check and remove segment try: # Get node info pubs = get_broadcast_manager().get_pubs()[self.resolved_name] subs = get_broadcast_manager().get_subs()[self.resolved_name] # Count total nums count = len(pubs) + len(subs) # Remove segment if count < 1: self._pdll.remove_segment(self.resolved_name) except: pass # Remove from poll instance as well as connections try: self.connection_poll.remove_fd(c.fileno()) except: pass try: # not necessarily correct from an abstraction point of # view, but will prevent accident connection leaks c.close() except: pass # while c might be a rospy.impl.tcpros_base.TCPROSTransport instance # connections might only contain the rospy.impl.tcpros_pubsub.QueuedConnection proxy # finding the "right" connection is more difficult then if c in connections: connections.remove(c) # therefore additionally check for fileno equality if available elif c.fileno(): matching_connections = [ conn for conn in connections if conn.fileno() == c.fileno()] if len(matching_connections) == 1: connections.remove(matching_connections[0]) def add_connection(self, c): """ Add a connection to this topic. If any previous connections to same endpoint exist, drop them. @param c: connection instance @type c: Transport @return: True if connection was added, ``bool`` """ rospyinfo("topic[%s] adding connection to [%s], count %s"%(self.resolved_name, c.endpoint_id, len(self.connections))) with self.c_lock: # protect against race condition adding connection to closed sub if self.closed: rospyerr( "ERROR: Race condition failure adding connection to closed subscriber\n" "If you run into this please comment on " "https://github.com/ros/ros_comm/issues/544" ) return False # c_lock is to make add_connection thread-safe, but we # still make a copy of self.connections so that the rest of the # code can use self.connections in an unlocked manner new_connections = self.connections[:] # if we have a connection to the same endpoint_id, drop # the old one. for oldc in self.connections: if oldc.endpoint_id == c.endpoint_id: self._remove_connection(new_connections, oldc) # #3808: "garbage collect" bad sockets whenever we add new # connections. This allows at most one stale connection # per topic. Otherwise, we only detect bad connections on # write. An alternative (given the current # implementation) would be to start a thread that # regularly polls all fds, but that would create a lot of # synchronization events and also have a separate thread # to manage. It would be desireable to move to this, but # this change is less impactful and keeps the codebase # more stable as we move towards an entirely different # event loop for rospy -- the heart of the problem is that # rospy's i/o is blocking-based, which has the obvious # issues. for fd in self.connection_poll.error_iter(): to_remove = [x for x in new_connections if x.fileno() == fd] for x in to_remove: rospydebug("removing connection to %s, connection error detected"%(x.endpoint_id)) self._remove_connection(new_connections, x) # Add new connection to poller, register for all events, # though we only care about POLLHUP/ERR new_fd = c.fileno() if new_fd is not None: self.connection_poll.add_fd(new_fd) # add in new connection new_connections.append(c) self.connections = new_connections # connections make a callback when closed # don't clobber an existing callback if not c.cleanup_cb: c.set_cleanup_callback(self.remove_connection) else: previous_callback = c.cleanup_cb new_callback = self.remove_connection def cleanup_cb_wrapper(s): new_callback(s) previous_callback(s) c.set_cleanup_callback(cleanup_cb_wrapper) return True def remove_connection(self, c): """ Remove connection from topic. @param c: connection instance to remove @type c: Transport """ rospyinfo("topic[%s] removing connection to %s"%(self.resolved_name, c.endpoint_id)) with self.c_lock: # c_lock is to make remove_connection thread-safe, but we # still make a copy of self.connections so that the rest of the # code can use self.connections in an unlocked manner new_connections = self.connections[:] self._remove_connection(new_connections, c) self.connections = new_connections def get_stats_info(self): # STATS """ Get the stats for this topic @return: stats for topic in getBusInfo() format:: Publisher: ((connection_id, destination_caller_id, direction, transport, topic_name, connected, connection_info_string)*) Subscriber: ((connection_id, publisher_xmlrpc_uri, direction, transport, topic_name, connected, connection_info_string)*) @rtype: list """ # save referenceto avoid locking connections = self.connections return [(c.id, c.endpoint_id, c.direction, c.transport_type, self.resolved_name, True, c.get_transport_info()) for c in connections] def get_stats(self): # STATS """Get the stats for this topic (API stub)""" raise Exception("subclasses must override") # Implementation note: Subscriber attaches to a _SubscriberImpl # singleton for that topic. The underlying impl manages the # connections for that publication and enables thread-safe access class Subscriber(Topic): """ Class for registering as a subscriber to a specified topic, where the messages are of a given type. """ def __init__(self, name, data_class, callback=None, callback_args=None, queue_size=None, buff_size=DEFAULT_BUFF_SIZE, tcp_nodelay=False): """ Constructor. NOTE: for the queue_size and buff_size parameters, rospy does not attempt to do intelligent merging between multiple Subscriber instances for the same topic. As they share the same underlying transport, multiple Subscribers to the same topic can conflict with one another if they set these parameters differently. @param name: graph resource name of topic, e.g. 'laser'. @type name: str @param data_class: data type class to use for messages, e.g. std_msgs.msg.String @type data_class: L{Message} class @param callback: function to call ( fn(data)) when data is received. If callback_args is set, the function must accept the callback_args as a second argument, i.e. fn(data, callback_args). NOTE: Additional callbacks can be added using add_callback(). @type callback: fn(msg, cb_args) @param callback_args: additional arguments to pass to the callback. This is useful when you wish to reuse the same callback for multiple subscriptions. @type callback_args: any @param queue_size: maximum number of messages to receive at a time. This will generally be 1 or None (infinite, default). buff_size should be increased if this parameter is set as incoming data still needs to sit in the incoming buffer before being discarded. Setting queue_size buff_size to a non-default value affects all subscribers to this topic in this process. @type queue_size: int @param buff_size: incoming message buffer size in bytes. If queue_size is set, this should be set to a number greater than the queue_size times the average message size. Setting buff_size to a non-default value affects all subscribers to this topic in this process. @type buff_size: int @param tcp_nodelay: if True, request TCP_NODELAY from publisher. Use of this option is not generally recommended in most cases as it is better to rely on timestamps in message data. Setting tcp_nodelay to True enables TCP_NODELAY for all subscribers in the same python process. @type tcp_nodelay: bool @raise ROSException: if parameters are invalid """ super(Subscriber, self).__init__(name, data_class, Registration.SUB) #add in args that factory cannot pass in # last person to set these to non-defaults wins, not much way # around this if queue_size is not None: self.impl.set_queue_size(queue_size) if buff_size != DEFAULT_BUFF_SIZE: self.impl.set_buff_size(buff_size) if callback is not None: # #1852 # it's important that we call add_callback so that the # callback can be invoked with any latched messages self.impl.add_callback(callback, callback_args) # save arguments for unregister self.callback = callback self.callback_args = callback_args else: # initialize fields self.callback = self.callback_args = None if tcp_nodelay: self.impl.set_tcp_nodelay(tcp_nodelay) def unregister(self): """ unpublish/unsubscribe from topic. Topic instance is no longer valid after this call. Additional calls to unregister() have no effect. """ if self.impl: # It's possible to have a Subscriber instance with no # associated callback if self.callback is not None: self.impl.remove_callback(self.callback, self.callback_args) self.callback = self.callback_args = None super(Subscriber, self).unregister() class _SubscriberImpl(_TopicImpl): """ Underyling L{_TopicImpl} implementation for subscriptions. """ def __init__(self, name, data_class): """ ctor. @param name: graph resource name of topic, e.g. 'laser'. @type name: str @param data_class: Message data class @type data_class: L{Message} class """ super(_SubscriberImpl, self).__init__(name, data_class) # client-methods to invoke on new messages. should only modify # under lock. This is a list of 2-tuples (fn, args), where # args are additional arguments for the callback, or None self.callbacks = [] self.queue_size = None self.buff_size = DEFAULT_BUFF_SIZE self.tcp_nodelay = False self.statistics_logger = SubscriberStatisticsLogger(self) \ if SubscriberStatisticsLogger.is_enabled() \ else None def close(self): """close I/O and release resources""" _TopicImpl.close(self) if self.callbacks: del self.callbacks[:] self.callbacks = None if self.statistics_logger: self.statistics_logger.shutdown() self.statistics_logger = None def set_tcp_nodelay(self, tcp_nodelay): """ Set the value of TCP_NODELAY, which causes the Nagle algorithm to be disabled for future topic connections, if the publisher supports it. """ self.tcp_nodelay = tcp_nodelay def set_queue_size(self, queue_size): """ Set the receive queue size. If more than queue_size messages are waiting to be deserialized, they are discarded. @param queue_size int: incoming queue size. Must be positive integer or None. @type queue_size: int """ if queue_size == -1: self.queue_size = None elif queue_size == 0: raise ROSException("queue size may not be set to zero") elif queue_size is not None and type(queue_size) != int: raise ROSException("queue size must be an integer") else: self.queue_size = queue_size def set_buff_size(self, buff_size): """ Set the receive buffer size. The exact meaning of this is transport dependent. @param buff_size: receive buffer size @type buff_size: int """ if type(buff_size) != int: raise ROSException("buffer size must be an integer") elif buff_size <= 0: raise ROSException("buffer size must be a positive integer") self.buff_size = buff_size def get_stats(self): # STATS """ Get the stats for this topic subscriber @return: stats for topic in getBusStats() publisher format:: (topicName, connStats) where connStats is:: [connectionId, bytesReceived, numSent, dropEstimate, connected]* @rtype: list """ # save reference to avoid locking conn = self.connections #for now drop estimate is -1 stats = (self.resolved_name, [(c.id, c.stat_bytes, c.stat_num_msg, -1, not c.done) for c in conn] ) return stats def add_callback(self, cb, cb_args): """ Register a callback to be invoked whenever a new message is received @param cb: callback function to invoke with message data instance, i.e. fn(data). If callback args is set, they will be passed in as the second argument. @type cb: fn(msg, cb_args) @param cb_cargs: additional arguments to pass to callback @type cb_cargs: Any """ if self.closed: raise ROSException("subscriber [%s] has been closed"%(self.resolved_name)) with self.c_lock: # we lock in order to serialize calls to add_callback, but # we copy self.callbacks so we can it new_callbacks = self.callbacks[:] new_callbacks.append((cb, cb_args)) self.callbacks = new_callbacks # #1852: invoke callback with any latched messages for c in self.connections: if c.latch is not None: self._invoke_callback(c.latch, cb, cb_args) def remove_callback(self, cb, cb_args): """ Unregister a message callback. @param cb: callback function @type cb: fn(msg, cb_args) @param cb_cargs: additional arguments associated with callback @type cb_cargs: Any @raise KeyError: if no matching callback """ if self.closed: return with self.c_lock: # we lock in order to serialize calls to add_callback, but # we copy self.callbacks so we can it matches = [x for x in self.callbacks if x[0] == cb and x[1] == cb_args] if matches: new_callbacks = self.callbacks[:] # remove the first match new_callbacks.remove(matches[0]) self.callbacks = new_callbacks if not matches: raise KeyError("no matching cb") def _invoke_callback(self, msg, cb, cb_args): """ Invoke callback on msg. Traps and logs any exceptions raise by callback @param msg: message data @type msg: L{Message} @param cb: callback @type cb: fn(msg, cb_args) @param cb_args: callback args or None @type cb_args: Any """ try: if cb_args is not None: cb(msg, cb_args) else: cb(msg) except Exception as e: if not is_shutdown(): logerr("bad callback: %s\n%s"%(cb, traceback.format_exc())) else: _logger.warn("during shutdown, bad callback: %s\n%s"%(cb, traceback.format_exc())) def receive_callback(self, msgs, connection): """ Called by underlying connection transport for each new message received @param msgs: message data @type msgs: [L{Message}] """ # save reference to avoid lock callbacks = self.callbacks for msg in msgs: if self.statistics_logger: self.statistics_logger.callback(msg, connection.callerid_pub, connection.stat_bytes) for cb, cb_args in callbacks: self._invoke_callback(msg, cb, cb_args) class SubscribeListener(object): """ Callback API to receive notifications when new subscribers connect and disconnect. """ def peer_subscribe(self, topic_name, topic_publish, peer_publish): """ callback when a peer has subscribed from a topic @param topic_name: topic name. NOTE: topic name will be resolved/remapped @type topic_name: str @param topic_publish: method to publish message data to all subscribers @type topic_publish: fn(data) @param peer_publish: method to publish message data to new subscriber. NOTE: behavior for the latter is transport-dependent as some transports may be broadcast only. @type peer_publish: fn(data) """ pass def peer_unsubscribe(self, topic_name, num_peers): """ callback when a peer has unsubscribed from a topic @param topic_name: topic name. NOTE: topic name will be resolved/remapped @type topic_name: str @param num_peers: number of remaining peers subscribed to topic @type num_peers: int """ pass # Implementation note: Publisher attaches to a # _PublisherImpl singleton for that topic. The underlying impl # manages the connections for that publication and enables # thread-safe access class Publisher(Topic): """ Class for registering as a publisher of a ROS topic. """ def __init__(self, name, data_class, subscriber_listener=None, tcp_nodelay=False, latch=False, headers=None, queue_size=None): """ Constructor @param name: resource name of topic, e.g. 'laser'. @type name: str @param data_class: message class for serialization @type data_class: L{Message} class @param subscriber_listener: listener for subscription events. May be None. @type subscriber_listener: L{SubscribeListener} @param tcp_nodelay: If True, sets TCP_NODELAY on publisher's socket (disables Nagle algorithm). This results in lower latency publishing at the cost of efficiency. @type tcp_nodelay: bool @param latch: If True, the last message published is 'latched', meaning that any future subscribers will be sent that message immediately upon connection. @type latch: bool @param headers: If not None, a dictionary with additional header key-values being used for future connections. @type headers: dict @param queue_size: The queue size used for asynchronously publishing messages from different threads. A size of zero means an infinite queue, which can be dangerous. When the keyword is not being used or when None is passed all publishing will happen synchronously and a warning message will be printed. @type queue_size: int @raise ROSException: if parameters are invalid """ super(Publisher, self).__init__(name, data_class, Registration.PUB) if subscriber_listener: self.impl.add_subscriber_listener(subscriber_listener) if tcp_nodelay: get_tcpros_handler().set_tcp_nodelay(self.resolved_name, tcp_nodelay) if latch: self.impl.enable_latch() if headers: self.impl.add_headers(headers) if queue_size is not None: self.impl.set_queue_size(queue_size) else: import warnings warnings.warn("The publisher should be created with an explicit keyword argument 'queue_size'. " "Please see http://wiki.ros.org/rospy/Overview/Publishers%20and%20Subscribers for more information.", SyntaxWarning, stacklevel=2) def publish(self, *args, **kwds): """ Publish message data object to this topic. Publish can either be called with the message instance to publish or with the constructor args for a new Message instance, i.e.:: pub.publish(message_instance) pub.publish(message_field_1, message_field_2...) pub.publish(message_field_1='foo', message_field_2='bar') @param args : L{Message} instance, message arguments, or no args if keyword arguments are used @param kwds : Message keyword arguments. If kwds are used, args must be unset @raise ROSException: If rospy node has not been initialized @raise ROSSerializationException: If unable to serialize message. This is usually a type error with one of the fields. """ if self.impl is None: raise ROSException("publish() to an unregistered() handle") if not is_initialized(): raise ROSException("ROS node has not been initialized yet. Please call init_node() first") data = args_kwds_to_message(self.data_class, args, kwds) try: self.impl.acquire() self.impl.publish(data) except genpy.SerializationError as e: # can't go to rospy.logerr(), b/c this could potentially recurse _logger.error(traceback.format_exc()) raise ROSSerializationException(str(e)) finally: self.impl.release() class _PublisherImpl(_TopicImpl): """ Underyling L{_TopicImpl} implementation for publishers. """ def __init__(self, name, data_class): """ @param name: name of topic, e.g. 'laser'. @type name: str @param data_class: Message data class @type data_class: L{Message} class """ super(_PublisherImpl, self).__init__(name, data_class) if python3 == 0: self.buff = StringIO() else: self.buff = BytesIO() self.publock = threading.RLock() #for acquire()/release self.subscriber_listeners = [] # additional client connection headers self.headers = {} # publish latch, starts disabled self.is_latch = False self.latch = None # maximum queue size for publishing messages self.queue_size = None #STATS self.message_data_sent = 0 def close(self): """close I/O and release resources""" _TopicImpl.close(self) # release resources if self.subscriber_listeners: del self.subscriber_listeners[:] if self.headers: self.headers.clear() if self.buff is not None: self.buff.close() self.publock = self.headers = self.buff = self.subscriber_listeners = None def add_headers(self, headers): """ Add connection headers to this Topic for future connections. @param headers: key/values will be added to current connection header set, overriding any existing keys if they conflict. @type headers: dict """ self.headers.update(headers) def enable_latch(self): """ Enable publish() latch. The latch contains the last published message and is sent to any new subscribers. """ self.is_latch = True def set_queue_size(self, queue_size): self.queue_size = queue_size def get_stats(self): # STATS """ Get the stats for this topic publisher @return: stats for topic in getBusStats() publisher format:: [topicName, messageDataBytes, connStats], where connStats is:: [id, bytes, numMessages, connected]* @rtype: list """ # save reference to avoid lock conn = self.connections return (self.resolved_name, self.message_data_sent, [(c.id, c.stat_bytes, c.stat_num_msg, not c.done) for c in conn] ) def add_subscriber_listener(self, l): """ Add a L{SubscribeListener} for subscribe events. @param l: listener instance @type l: L{SubscribeListener} """ self.subscriber_listeners.append(l) def acquire(self): """lock for thread-safe publishing to this transport""" if self.publock is not None: self.publock.acquire() def release(self): """lock for thread-safe publishing to this transport""" if self.publock is not None: self.publock.release() def add_connection(self, c): """ Add a connection to this topic. This must be a PubTransport. If the latch is enabled, c will be sent a the value of the latch. @param c: connection instance @type c: L{Transport} @return: True if connection was added @rtype: bool """ if self.queue_size is not None: c = QueuedConnection(c, self.queue_size) super(_PublisherImpl, self).add_connection(c) def publish_single(data): self.publish(data, connection_override=c) for l in self.subscriber_listeners: l.peer_subscribe(self.resolved_name, self.publish, publish_single) if self.is_latch and self.latch is not None: with self.publock: self.publish(self.latch, connection_override=c) return True def remove_connection(self, c): """ Remove existing connection from this topic. @param c: connection instance to remove @type c: L{Transport} """ super(_PublisherImpl, self).remove_connection(c) num = len(self.connections) for l in self.subscriber_listeners: l.peer_unsubscribe(self.resolved_name, num) def publish(self, message, connection_override=None): """ Publish the data to the topic. If the topic has no subscribers, the method will return without any affect. Access to publish() should be locked using acquire() and release() in order to ensure proper message publish ordering. @param message: message data instance to publish @type message: L{Message} @param connection_override: publish to this connection instead of all @type connection_override: L{Transport} @return: True if the data was published, False otherwise. @rtype: bool @raise genpy.SerializationError: if L{Message} instance is unable to serialize itself @raise rospy.ROSException: if topic has been closed or was closed during publish() """ #TODO: should really just use IOError instead of rospy.ROSException if self.closed: # during shutdown, the topic can get closed, which creates # a race condition with user code testing is_shutdown if not is_shutdown(): raise ROSException("publish() to a closed topic") else: return if self.is_latch: self.latch = message if not self.has_connections(): #publish() falls through return False if connection_override is None: #copy connections so we can iterate safely conns = self.connections else: conns = [connection_override] # #2128 test our buffer. I don't now how this got closed in # that case, but we can at least diagnose the problem. b = self.buff try: b.tell() # serialize the message self.seq += 1 #count messages published to the topic serialize_message(b, self.seq, message) # send the buffer to all connections err_con = [] data = b.getvalue() for c in conns: try: if not is_shutdown(): c.write_data(data) except TransportTerminated as e: logdebug("publisher connection to [%s] terminated, see errorlog for details:\n%s"%(c.endpoint_id, traceback.format_exc())) err_con.append(c) except Exception as e: # greater severity level logdebug("publisher connection to [%s] terminated, see errorlog for details:\n%s"%(c.endpoint_id, traceback.format_exc())) err_con.append(c) # reset the buffer and update stats self.message_data_sent += b.tell() #STATS b.seek(0) b.truncate(0) except ValueError: # operations on self.buff can fail if topic is closed # during publish, which often happens during Ctrl-C. # diagnose the error and report accordingly. if self.closed: if is_shutdown(): # we offer no guarantees on publishes that occur # during shutdown, so this is not exceptional. return else: # this indicates that user-level code most likely # closed the topic, which is exceptional. raise ROSException("topic was closed during publish()") else: # unexpected, so re-raise original error raise # remove any bad connections for c in err_con: try: # connection will callback into remove_connection when # we close it c.close() except: pass ################################################################################# # TOPIC MANAGER/LISTENER class _TopicManager(object): """ Tracks Topic objects See L{get_topic_manager()} for singleton access """ def __init__(self): """ctor.""" super(_TopicManager, self).__init__() self.pubs = {} #: { topic: _PublisherImpl } self.subs = {} #: { topic: _SubscriberImpl } self.topics = set() # [str] list of topic names self.lock = threading.Condition() self.closed = False _logger.info("topicmanager initialized") def get_pub_sub_info(self): """ get topic publisher and subscriber connection info for getBusInfo() api @return: [bus info stats] See getBusInfo() API for more data structure details. @rtype: list """ with self.lock: info = [] for s in chain(iter(self.pubs.values()), iter(self.subs.values())): info.extend(s.get_stats_info()) return info def get_pub_sub_stats(self): """ get topic publisher and subscriber stats for getBusStats() api @return: [publisherStats, subscriberStats]. See getBusStats() API for more data structure details. @rtype: list """ with self.lock: return [s.get_stats() for s in self.pubs.values()],\ [s.get_stats() for s in self.subs.values()] def close_all(self): """ Close all registered publication and subscriptions. Manager is no longer usable after close. """ self.closed = True with self.lock: for t in chain(iter(self.pubs.values()), iter(self.subs.values())): t.close() self.pubs.clear() self.subs.clear() def _add(self, ps, rmap, reg_type): """ Add L{_TopicImpl} instance to rmap @param ps: a pub/sub impl instance @type ps: L{_TopicImpl} @param rmap: { topic: _TopicImpl} rmap to record instance in @type rmap: dict @param reg_type: L{rospy.registration.Registration.PUB} or L{rospy.registration.Registration.SUB} @type reg_type: str """ resolved_name = ps.resolved_name _logger.debug("tm._add: %s, %s, %s", resolved_name, ps.type, reg_type) with self.lock: rmap[resolved_name] = ps self.topics.add(resolved_name) # NOTE: this call can take a lengthy amount of time (at # least until its reimplemented to use queues) get_registration_listeners().notify_added(resolved_name, ps.type, reg_type) def _recalculate_topics(self): """recalculate self.topics. expensive""" self.topics = set([x.resolved_name for x in self.pubs.values()] + [x.resolved_name for x in self.subs.values()]) def _remove(self, ps, rmap, reg_type): """ Remove L{_TopicImpl} instance from rmap @param ps: a pub/sub impl instance @type ps: L{_TopicImpl} @param rmap: topic->_TopicImpl rmap to remove instance in @type rmap: dict @param reg_type: L{rospy.registration.Registration.PUB} or L{rospy.registration.Registration.SUB} @type reg_type: str """ resolved_name = ps.resolved_name _logger.debug("tm._remove: %s, %s, %s", resolved_name, ps.type, reg_type) with self.lock: del rmap[resolved_name] self. _recalculate_topics() # NOTE: this call can take a lengthy amount of time (at # least until its reimplemented to use queues) get_registration_listeners().notify_removed(resolved_name, ps.type, reg_type) def get_impl(self, reg_type, resolved_name): """ Get the L{_TopicImpl} for the specified topic. This is mainly for testing purposes. Unlike acquire_impl, it does not alter the ref count. @param resolved_name: resolved topic name @type resolved_name: str @param reg_type: L{rospy.registration.Registration.PUB} or L{rospy.registration.Registration.SUB} @type reg_type: str """ if reg_type == Registration.PUB: rmap = self.pubs elif reg_type == Registration.SUB: rmap = self.subs else: raise TypeError("invalid reg_type: %s"%s) return rmap.get(resolved_name, None) def acquire_impl(self, reg_type, resolved_name, data_class): """ Acquire a L{_TopicImpl} for the specified topic (create one if it doesn't exist). Every L{Topic} instance has a _TopicImpl that actually controls the topic resources so that multiple Topic instances use the same underlying connections. 'Acquiring' a topic implementation marks that another Topic instance is using the TopicImpl. @param resolved_name: resolved topic name @type resolved_name: str @param reg_type: L{rospy.registration.Registration.PUB} or L{rospy.registration.Registration.SUB} @type reg_type: str @param data_class: message class for topic @type data_class: L{Message} class """ if reg_type == Registration.PUB: rmap = self.pubs impl_class = _PublisherImpl elif reg_type == Registration.SUB: rmap = self.subs impl_class = _SubscriberImpl else: raise TypeError("invalid reg_type: %s"%s) with self.lock: impl = rmap.get(resolved_name, None) if not impl: impl = impl_class(resolved_name, data_class) self._add(impl, rmap, reg_type) impl.ref_count += 1 return impl def release_impl(self, reg_type, resolved_name): """ Release a L_{TopicImpl} for the specified topic. Every L{Topic} instance has a _TopicImpl that actually controls the topic resources so that multiple Topic instances use the same underlying connections. 'Acquiring' a topic implementation marks that another Topic instance is using the TopicImpl. @param resolved_name: resolved topic name @type resolved_name: str @param reg_type: L{rospy.registration.Registration.PUB} or L{rospy.registration.Registration.SUB} @type reg_type: str """ if reg_type == Registration.PUB: rmap = self.pubs else: rmap = self.subs with self.lock: # check for race condition where multiple things are cleaning up at once if self.closed: return impl = rmap.get(resolved_name, None) assert impl is not None, "cannot release topic impl as impl [%s] does not exist"%resolved_name impl.ref_count -= 1 assert impl.ref_count >= 0, "topic impl's reference count has gone below zero" if impl.ref_count == 0: rospyinfo("topic impl's ref count is zero, deleting topic %s...", resolved_name) impl.close() self._remove(impl, rmap, reg_type) del impl _logger.debug("... done deleting topic %s", resolved_name) def get_publisher_impl(self, resolved_name): """ @param resolved_name: resolved topic name @type resolved_name: str @return: list of L{_PublisherImpl}s @rtype: [L{_PublisherImpl}] """ return self.pubs.get(resolved_name, None) def get_subscriber_impl(self, resolved_name): """ @param resolved_name: topic name @type resolved_name: str @return: subscriber for the specified topic. @rtype: L{_SubscriberImpl} """ return self.subs.get(resolved_name, None) def has_subscription(self, resolved_name): """ @param resolved_name: resolved topic name @type resolved_name: str @return: True if manager has subscription for specified topic @rtype: bool """ return resolved_name in self.subs def has_publication(self, resolved_name): """ @param resolved_name: resolved topic name @type resolved_name: str @return: True if manager has publication for specified topic @rtype: bool """ return resolved_name in self.pubs def get_topics(self): """ @return: list of topic names this node subscribes to/publishes @rtype: [str] """ return self.topics def _get_list(self, rmap): return [[k, v.type] for k, v in rmap.items()] ## @return [[str,str],]: list of topics subscribed to by this node, [ [topic1, topicType1]...[topicN, topicTypeN]] def get_subscriptions(self): return self._get_list(self.subs) ## @return [[str,str],]: list of topics published by this node, [ [topic1, topicType1]...[topicN, topicTypeN]] def get_publications(self): return self._get_list(self.pubs) set_topic_manager(_TopicManager())
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/exceptions.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """rospy exception types""" class ROSException(Exception): """ Base exception class for ROS clients """ pass class ROSSerializationException(ROSException): """ Exception for message serialization errors """ pass class ROSInitException(ROSException): """ Exception for errors initializing ROS state """ pass class ROSInterruptException(ROSException, KeyboardInterrupt): """ Exception for operations that interrupted, e.g. due to shutdown. This is a subclass of both L{ROSException} and KeyboardInterrupt so that it can be used in logic tht expects either. """ pass class ROSTimeMovedBackwardsException(ROSInterruptException): """ Exception if time moved backwards """ def __init__(self, time): self.time = time """The amount of time in seconds.""" super(ROSTimeMovedBackwardsException, self).__init__("ROS time moved backwards") class ROSInternalException(Exception): """ Base class for exceptions that are internal to the ROS system """ pass class TransportException(ROSInternalException): """ Base class for transport-related exceptions """ pass class TransportTerminated(TransportException): """ Internal class for representing broken connections """ pass class TransportInitError(TransportException): """ Internal exception for representing exceptions that occur establishing transports """ pass
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/msproxy.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Master/Slave XML-RPC Wrappers. The L{MasterProxy} simplifies usage of master/slave APIs by automatically inserting the caller ID and also adding python dictionary accessors on the parameter server. """ from threading import Lock import rospy.core import rospy.exceptions import rospy.names import rospy.impl.paramserver import rospy.impl.masterslave from rospy.impl.broadcast_manager import BroadcastManager from rospy.impl.registration import get_broadcast_manager, set_broadcast_manager _master_arg_remap = { 'deleteParam': [0], # remap key 'setParam': [0], # remap key 'getParam': [0], # remap key 'searchParam': [0], # remap key 'subscribeParam': [0], # remap key 'unsubscribeParam': [0], # remap key 'hasParam': [0], # remap key 'registerService': [0], # remap service 'lookupService': [0], # remap service 'unregisterService': [0], # remap service 'registerSubscriber': [0], # remap topic 'unregisterSubscriber': [0], # remap topic 'registerPublisher': [0], # remap topic 'unregisterPublisher': [0], # remap topic 'lookupNode': [0], # remap node 'getPublishedTopics': [0], # remap subgraph } class MasterProxy(object): """ Convenience wrapper for ROS master API and XML-RPC implementation. The Master API methods can be invoked on this object and will be forwarded appropriately. Names in arguments will be remapped according to current node settings. Provides dictionary-like access to parameter server, e.g.:: master[key] = value All methods are thread-safe. """ def __init__(self, uri): """ Constructor for wrapping a remote master instance. @param uri: XML-RPC URI of master @type uri: str """ self.target = rospy.core.xmlrpcapi(uri) if get_broadcast_manager() is None: set_broadcast_manager(BroadcastManager()) self.bm = get_broadcast_manager() self._lock = Lock() def __getattr__(self, key): #forward api calls to target if key in _master_arg_remap: remappings = _master_arg_remap[key] else: remappings = rospy.impl.masterslave.ROSHandler.remappings(key) def wrappedF(*args, **kwds): args = [rospy.names.get_caller_id(),]+list(args) #print "Remap indicies", remappings for i in remappings: i = i + 1 #callerId does not count #print "Remap %s => %s"%(args[i], rospy.names.resolve_name(args[i])) args[i] = rospy.names.resolve_name(args[i]) with self._lock: f = getattr(self.target, key) return f(*args, **kwds) return wrappedF def __getitem__(self, key): """ Fetch item from parameter server and subscribe to future updates so that values can be cached. @param key: parameter key @type key: str @raise KeyError: if key is not set """ #NOTE: remapping occurs here! resolved_key = rospy.names.resolve_name(key) if 1: # disable param cache with self._lock: code, msg, value = self.target.getParam(rospy.names.get_caller_id(), resolved_key) if code != 1: #unwrap value with Python semantics raise KeyError(key) return value try: # check for value in the parameter server cache return rospy.impl.paramserver.get_param_server_cache().get(resolved_key) except KeyError: # first access, make call to parameter server with self._lock: code, msg, value = self.target.subscribeParam(rospy.names.get_caller_id(), rospy.core.get_node_uri(), resolved_key) if code != 1: #unwrap value with Python semantics raise KeyError(key) # set the value in the cache so that it's marked as subscribed rospy.impl.paramserver.get_param_server_cache().set(resolved_key, value) return value def __setitem__(self, key, val): """ Set parameter value on Parameter Server @param key: parameter key @type key: str @param val: parameter value @type val: XMLRPC legal value """ with self._lock: self.target.setParam(rospy.names.get_caller_id(), rospy.names.resolve_name(key), val) def search_param(self, key): """ Search for a parameter matching key on the parameter server @return: found key or None if search did not succeed @rtype: str @raise ROSException: if parameter server reports an error """ # #1810 searchParam has to use unresolved form of mappings mappings = rospy.names.get_mappings() if key in mappings: key = mappings[key] with self._lock: code, msg, val = self.target.searchParam(rospy.names.get_caller_id(), key) if code == 1: return val elif code == -1: return None else: raise rospy.exceptions.ROSException("cannot search for parameter: %s"%msg) def __delitem__(self, key): """ Delete parameter key from the parameter server. @raise KeyError: if key is not set @raise ROSException: if parameter server reports an error """ resolved_key = rospy.names.resolve_name(key) with self._lock: code, msg, _ = self.target.deleteParam(rospy.names.get_caller_id(), resolved_key) if code == -1: raise KeyError(key) elif code != 1: raise rospy.exceptions.ROSException("cannot delete parameter: %s"%msg) elif 0: #disable parameter cache # set the value in the cache so that it's marked as subscribed rospy.impl.paramserver.get_param_server_cache().delete(resolved_key) def __contains__(self, key): """ Check if parameter is set on Parameter Server @param key: parameter key @type key: str @raise ROSException: if parameter server reports an error """ with self._lock: code, msg, value = self.target.hasParam(rospy.names.get_caller_id(), rospy.names.resolve_name(key)) if code != 1: raise rospy.exceptions.ROSException("cannot check parameter on server: %s"%msg) return value def __iter__(self): """ @raise ROSException: if parameter server reports an error """ with self._lock: code, msg, value = self.target.getParamNames(rospy.names.get_caller_id()) if code == 1: return value.__iter__() else: raise rospy.exceptions.ROSException("cannot retrieve parameter names: %s"%msg)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/msg.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal use: Support for ROS messages, including network serialization routines""" import types import time import struct import logging import traceback import genpy import rospy.exceptions import rospy.names import google.protobuf.message class AnyMsg(genpy.Message): """ Message class to use for subscribing to any topic regardless of type. Incoming messages are not deserialized. Instead, the raw serialized data can be accssed via the buff property. This class is meant to be used by advanced users only. """ _md5sum = rospy.names.TOPIC_ANYTYPE _type = rospy.names.TOPIC_ANYTYPE _has_header = False _full_text = '' __slots__ = ['_buff'] def __init__(self, *args): """ Constructor. Does not accept any arguments. """ if len(args) != 0: raise rospy.exceptions.ROSException("AnyMsg does not accept arguments") self._buff = None def serialize(self, buff): """AnyMsg provides an implementation so that a node can forward messages w/o (de)serialization""" if self._buff is None: raise rospy.exceptions("AnyMsg is not initialized") else: buff.write(self._buff) def deserialize(self, str): """Copies raw buffer into self._buff""" self._buff = str return self def args_kwds_to_message(data_class, args, kwds): """ Given a data class, take in the args and kwds of a function call and return the appropriate data_class instance. If kwds are specified, a new data_class instance will be created with keyword-style init. If there is only a single arg and it is of the correct type, it will be returned. AnyMsg is considered to match all data_class types. Otherwise, args will be used as args for a new message instance. @param data_class: Message class that will be used to instantiate new instances, if necessary. @type data_class: Message class @param args: function args @type args: sequence @param kwds: function kwds @type kwds: dict @raise TypeError: if args and kwds are both specified """ if args and kwds: raise TypeError("publish() can be called with arguments or keywords, but not both.") elif kwds: return data_class(**kwds) else: if len(args) == 1: arg = args[0] if isinstance(arg, google.protobuf.message.Message): return arg # #2584: have to compare on md5sum as isinstance check can fail in dyngen case if hasattr(arg, '_md5sum') and (arg._md5sum == data_class._md5sum or isinstance(arg, AnyMsg)): return arg # If the argument is a message, make sure that it matches # the type of the first field. This means that the # data_class has fields and that the type matches. This # branch isn't necessary but provides more useful # information to users elif isinstance(arg, genpy.Message): if len(data_class._slot_types) == 0: raise TypeError("expected [] but got [%s]"%arg._type) elif arg._type != data_class._slot_types[0]: raise TypeError("expected [%s] but got [%s]"%(data_class._slot_types[0], arg._type)) return data_class(*args) else: return data_class(*args) def serialize_message(b, seq, msg): """ Serialize the message to the buffer @param b: buffer to write to. WARNING: buffer will be reset after call @type b: StringIO @param msg: message to write @type msg: Message @param seq: current sequence number (for headers) @type seq: int: current sequence number (for headers) @raise ROSSerializationException: if unable to serialize message. This is usually due to a type error with one of the fields. """ start = b.tell() b.seek(start+4) #reserve 4-bytes for length #update Header object in top-level message if getattr(msg.__class__, "_has_header", False): header = msg.header header.seq = seq # default value for frame_id is '0' if header.frame_id is None: header.frame_id = "0" #serialize the message data try: msg.serialize(b) except struct.error as e: raise rospy.exceptions.ROSSerializationException(e) #write 4-byte packet length # -4 don't include size of length header end = b.tell() size = end - 4 - start b.seek(start) b.write(struct.pack('<I', size)) b.seek(end) def deserialize_messages(b, msg_queue, data_class, queue_size=None, max_msgs=None, start=0): """ Read all messages off the buffer @param b: buffer to read data from @type b: StringIO @param msg_queue: queue to append deserialized data to @type msg_queue: list @param data_class: message deserialization class @type data_class: Message class @param queue_size: message queue size. all but the last queue_size messages are discarded if this parameter is specified. @type queue_size: int @param start: starting position to read in b @type start: int @param max_msgs int: maximum number of messages to deserialize or None @type max_msgs: int @raise genpy.DeserializationError: if an error/exception occurs during deserialization """ try: pos = start btell = b.tell() left = btell - pos # check to see if we even have a message if left < 4: return # read in each message from the buffer as a string. each # message is preceded by a 4-byte integer length. the # serialized messages are appended to buff. b.seek(pos) buffs = [] # size of message size = -1 while (size < 0 and left >= 4) or (size > -1 and left >= size): # - read in the packet length # NOTE: size is not inclusive of itself. if size < 0 and left >= 4: (size,) = struct.unpack('<I', b.read(4)) left -= 4 # - deserialize the complete buffer if size > -1 and left >= size: buffs.append(b.read(size)) pos += size + 4 left = btell - pos size = -1 if max_msgs and len(buffs) >= max_msgs: break #Before we deserialize, prune our buffers baed on the #queue_size rules. if queue_size is not None: buffs = buffs[-queue_size:] # Deserialize the messages into msg_queue, then trim the # msg_queue as specified. for q in buffs: data = data_class() msg_queue.append(data.deserialize(q)) if queue_size is not None: del msg_queue[:-queue_size] #update buffer b to its correct write position. if btell == pos: #common case: no leftover data, reset the buffer b.seek(start) b.truncate(start) else: if pos != start: #next packet is stuck in our buffer, copy it to the #beginning of our buffer to keep things simple b.seek(pos) leftovers = b.read(btell-pos) b.truncate(start + len(leftovers)) b.seek(start) b.write(leftovers) else: b.seek(btell) except Exception as e: logging.getLogger('rospy.msg').error("cannot deserialize message: EXCEPTION %s", traceback.format_exc()) raise genpy.DeserializationError("cannot deserialize: %s"%str(e))
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/registration.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal use: handles maintaining registrations with master via internal listener APIs""" import socket import sys import logging import threading import time import traceback try: import xmlrpc.client as xmlrpcclient except ImportError: import xmlrpclib as xmlrpcclient from rospy.core import is_shutdown, is_shutdown_requested, xmlrpcapi, \ logfatal, logwarn, loginfo, logerr, logdebug, \ signal_shutdown, add_preshutdown_hook from rospy.names import get_caller_id, get_namespace # topic manager and service manager singletons _topic_manager = None def set_topic_manager(tm): global _topic_manager _topic_manager = tm def get_topic_manager(): return _topic_manager _service_manager = None def set_service_manager(sm): global _service_manager _service_manager = sm def get_service_manager(): return _service_manager broadcast_manager_handler = None def set_broadcast_manager(bm): global broadcast_manager_handler broadcast_manager_handler = bm def get_broadcast_manager(): global broadcast_manager_handler return broadcast_manager_handler node_handler = None def set_node_handler(handler): global node_handler node_handler = handler def get_node_handler(): global node_handler return node_handler class Registration(object): """Registration types""" PUB = 'pub' SUB = 'sub' SRV = 'srv' class RegistrationListener(object): """Listener API for subscribing to changes in Publisher/Subscriber/Service declarations""" def reg_added(self, resolved_name, data_type_or_uri, reg_type): """ New pub/sub/service declared. @param resolved_name: resolved topic/service name @param data_type_or_uri: topic type or service uri @type data_type_or_uri: str @param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV} @type reg_type: str """ pass def reg_removed(self, resolved_name, data_type_or_uri, reg_type): """ New pub/sub/service removed. @param resolved_name: topic/service name @type resolved_name: str @param data_type_or_uri: topic type or service uri @type data_type_or_uri: str @param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV} @type reg_type: str """ pass class RegistrationListeners(object): def __init__(self): """ ctor. """ self.listeners = [] self.lock = threading.Lock() def add_listener(self, l): """ Subscribe to notifications of pub/sub/service registration changes. This is an internal API used to notify higher level routines when to communicate with the master. @param l: listener to subscribe @type l: TopicListener """ assert isinstance(l, RegistrationListener) with self.lock: self.listeners.append(l) def notify_removed(self, resolved_name, data_type_or_uri, reg_type): """ @param resolved_name: resolved_topic/service name @type resolved_name: str @param data_type_or_uri: topic type or service uri @type data_type_or_uri: str @param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV} @type reg_type: str """ with self.lock: for l in self.listeners: try: l.reg_removed(resolved_name, data_type_or_uri, reg_type) except Exception as e: logerr("error notifying listener of removal: %s"%traceback.format_exc()) def notify_added(self, resolved_name, data_type, reg_type): """ @param resolved_name: topic/service name @type resolved_name: str @param data_type: topic/service type @type data_type: str @param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV} @type reg_type: str """ with self.lock: for l in self.listeners: try: l.reg_added(resolved_name, data_type, reg_type) except Exception as e: logerr(traceback.format_exc()) def clear(self): """ Remove all registration listeners """ if not is_shutdown_requested(): with self.lock: del self.listeners[:] else: # when being in shutdown phase the lock might not be lockable # if a notify_added/removed is currently ongoing locked = self.lock.acquire(False) # remove all listeners anyway del self.listeners[:] if locked: self.lock.release() _registration_listeners = RegistrationListeners() def get_registration_listeners(): return _registration_listeners # RegManager's main purpose is to collect all client->master communication in one place class RegManager(RegistrationListener): """ Registration manager used by Node implemenation. Communicates with ROS Master to maintain topic registration information. Also responds to publisher updates to create topic connections """ def __init__(self, handler): """ ctor. @param handler: node API handler """ self.logger = logging.getLogger("rospy.registration") self.handler = handler self.uri = None self.master_uri = None self.updates = [] self.cond = threading.Condition() #for locking/notifying updates self.registered = False # cleanup has to occur before official shutdown add_preshutdown_hook(self.cleanup) def start(self, uri, master_uri): """ Start the RegManager. This should be passed in as an argument to a thread starter as the RegManager is designed to spin in its own thread @param uri: URI of local node @type uri: str @param master_uri: Master URI @type master_uri: str """ self.registered = False self.master_uri = master_uri self.uri = uri first = True tm = get_topic_manager() sm = get_service_manager() ns = get_namespace() caller_id = get_caller_id() registered = False while get_broadcast_manager() is None: time.sleep(0.01) bm = get_broadcast_manager() while not registered and not is_shutdown(): try: try: # prevent TopicManager and ServiceManager from accepting registrations until we are done tm.lock.acquire() sm.lock.acquire() pub, sub, srv = tm.get_publications(), tm.get_subscriptions(), sm.get_services() for resolved_name, data_type in pub: self.logger.info("Registering publisher topic [%s] type [%s]", resolved_name, data_type) self.logger.info("registerPublisher(%s, %s, %s, %s)"% (caller_id, resolved_name, data_type, uri)) code, msg, val = bm.registerPublisher(caller_id, resolved_name, data_type, uri) if code != 1: logfatal("cannot register publication topic [%s]: %s"%(resolved_name, msg)) signal_shutdown("node incompatibility with register publisher") for resolved_name, data_type in sub: self.logger.info("registering subscriber topic [%s] type [%s]", resolved_name, data_type) self.logger.info("registerSubscriber(%s, %s, %s, %s)"% (caller_id, resolved_name, data_type, uri)) code, msg, val = bm.registerSubscriber(caller_id, resolved_name, data_type, uri) if code != 1: logfatal("cannot register subscription topic [%s]: %s"%(resolved_name, msg)) signal_shutdown("node incompatibility with register subscriber") else: self.publisher_update(resolved_name, val) for resolved_name, service_uri in srv: self.logger.info("registering service [%s] uri [%s]", resolved_name, service_uri) self.logger.info("registerService(%s, %s, %s, %s)"% (caller_id, resolved_name, data_type, uri)) code, msg, val = bm.registerService(caller_id, resolved_name, service_uri, uri) if code != 1: logfatal("cannot register service [%s]: %s"%(resolved_name, msg)) signal_shutdown("node incompatibility with register service") registered = True # Subscribe to updates to our state get_registration_listeners().add_listener(self) finally: sm.lock.release() tm.lock.release() if pub or sub: logdebug("Registered [%s]", caller_id) else: logdebug("No topics to register") except Exception as e: if first: # this use to print to console always, arguable whether or not this should be subjected to same configuration options as logging logerr(e) logerr("Unable to immediately register.") first = False time.sleep(0.2) self.registered = True self.run() def is_registered(self): """ Check if Node has been registered yet. @return: True if registration has occurred with master @rtype: bool """ return self.registered def run(self): """ Main RegManager thread loop. Periodically checks the update queue and generates topic connections """ #Connect the topics while not self.handler.done and not is_shutdown(): cond = self.cond try: cond.acquire() if not self.updates: cond.wait(0.5) if self.updates: #work from the end as these are the most up-to-date topic, uris = self.updates.pop() #print "update", topic, uris #filter out older updates for same topic #self.updates = [x for x in self.updates if x[0] != topic] self.updates = [x for x in self.updates if x[0] != topic or x[1] != uris] else: topic = uris = None finally: if cond is not None: cond.release() #call _connect_topic on all URIs as it can check to see whether #or not a connection exists. if uris and not self.handler.done: for uri in uris: self.logger.debug("pub update:(%s,%s)" % (topic, uri)) # #1141: have to multithread this to prevent a bad publisher from hanging us #print topic, uri t = threading.Thread(target=self._connect_topic_thread, args=(topic, uri)) t.setDaemon(True) t.start() def _connect_topic_thread(self, topic, uri): try: code, msg, _ = self.handler._connect_topic(topic, uri) if code != 1: logerr("Unable to connect subscriber to publisher [%s] for topic [%s]: %s", uri, topic, msg) except Exception as e: if not is_shutdown(): logerr("Unable to connect to publisher [%s] for topic [%s]: %s"%(uri, topic, traceback.format_exc())) def cleanup(self, reason): """ Cleans up registrations with master and releases topic and service resources @param reason: human-reasonable debug string @type reason: str """ self.logger.debug("registration cleanup starting") try: self.cond.acquire() self.cond.notifyAll() finally: self.cond.release() caller_id = get_caller_id() # clear the registration listeners as we are going to do a quick unregister here rl = get_registration_listeners() if rl is not None: rl.clear() tm = get_topic_manager() sm = get_service_manager() try: bm = get_broadcast_manager() if tm is not None: for resolved_name, _ in tm.get_subscriptions(): self.logger.debug("unregisterSubscriber [%s]"%resolved_name) bm.unregisterSubscriber(caller_id, resolved_name, self.uri) for resolved_name, _ in tm.get_publications(): self.logger.debug("unregisterPublisher [%s]"%resolved_name) bm.unregisterPublisher(caller_id, resolved_name, self.uri) if sm is not None: for resolved_name, service_uri in sm.get_services(): self.logger.debug("unregisterService [%s]"%resolved_name) bm.unregisterService(caller_id, resolved_name, service_uri) except socket.error as se: (errno, msg) = se.args if errno == 111 or errno == 61: #can't talk to master, nothing we can do about it self.logger.warn("cannot unregister with master due to network issues") else: self.logger.warn("unclean shutdown\n%s"%traceback.format_exc()) except: self.logger.warn("unclean shutdown\n%s"%traceback.format_exc()) self.logger.debug("registration cleanup: complete") #TODO: cleanup() should actually be orchestrated by a separate #cleanup routine that calls the reg manager/sm/tm if tm is not None: tm.close_all() if sm is not None: sm.unregister_all() def reg_removed(self, resolved_name, data_type_or_uri, reg_type): """ RegistrationListener callback @param resolved_name: resolved name of topic or service @type resolved_name: str @param data_type_or_uri: either the data type (for topic regs) or the service URI (for service regs). @type data_type_or_uri: str @param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV} @type reg_type: str """ try: bm = get_broadcast_manager() if reg_type == Registration.PUB: self.logger.debug("unregisterPublisher(%s, %s)", resolved_name, self.uri) self.logger.info("unregisterPublisher(%s, %s)" % (resolved_name, self.uri)) bm.unregisterPublisher(get_caller_id(), resolved_name, self.uri) elif reg_type == Registration.SUB: self.logger.debug("unregisterSubscriber(%s, %s)", resolved_name, data_type_or_uri) self.logger.info("unregisterSubscriber(%s, %s)" % (resolved_name, data_type_or_uri)) bm.unregisterSubscriber(get_caller_id(), resolved_name, self.uri) elif reg_type == Registration.SRV: self.logger.debug("unregisterService(%s, %s)", resolved_name, data_type_or_uri) self.logger.info("unregisterService(%s, %s)" % (resolved_name, data_type_or_uri)) bm.unregisterService(get_caller_id(), resolved_name, data_type_or_uri) except: logwarn("unable to unregister, registrations are now out of sync") self.logger.error(traceback.format_exc()) def reg_added(self, resolved_name, data_type_or_uri, reg_type): """ RegistrationListener callback @param resolved_name: resolved name of topic or service @type resolved_name: str @param data_type_or_uri: either the data type (for topic regs) or the service URI (for service regs). @type data_type_or_uri: str @param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV} @type reg_type: str """ #TODO: this needs to be made robust to master outages args = (get_caller_id(), resolved_name, data_type_or_uri, self.uri) registered = False first = True while not registered and not is_shutdown(): try: bm = get_broadcast_manager() if reg_type == Registration.PUB: self.logger.debug("registerPublisher(%s, %s, %s, %s)"%args) self.logger.info("registerPublisher(%s, %s, %s, %s)" % args) code, msg, val = bm.registerPublisher(*args) if code != 1: logfatal("unable to register publication [%s]: %s"%(resolved_name, msg)) elif reg_type == Registration.SUB: self.logger.debug("registerSubscriber(%s, %s, %s, %s)"%args) self.logger.info("registerSubscriber(%s, %s, %s, %s)" % args) code, msg, val = bm.registerSubscriber(*args) if code == 1: #pass self.publisher_update(resolved_name, val) else: # this is potentially worth exiting over. in the future may want to add a retry # timer logfatal("unable to register subscription [%s]: %s"%(resolved_name, msg)) elif reg_type == Registration.SRV: self.logger.debug("registerService(%s, %s, %s, %s)"%args) self.logger.info("registerService(%s, %s, %s, %s)" % args) code, msg, val = bm.registerService(*args) if code != 1: logfatal("unable to register service [%s]: %s"%(resolved_name, msg)) registered = True except Exception as e: if first: msg = "Unable to register." self.logger.error(str(e)+"\n"+msg) first = False time.sleep(0.2) def publisher_update(self, resolved_name, uris): """ Inform psmanager of latest publisher list for a topic. This will cause L{RegManager} to create a topic connection for all new publishers (in a separate thread). @param resolved_name: resolved topic name @type resolved_name: str @param uris: list of all publishers uris for topic @type uris: [str] """ try: self.cond.acquire() self.updates.append((resolved_name, uris)) self.cond.notifyAll() finally: self.cond.release()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/transport.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Base classes for rospy transports These are the base underlying transport implementations, i.e. TCP/IP connections, etc... For topic implementations, see L{topics} """ import threading # we need ids for the transports so we can send the IDs instead of # full connection details _transport_id = 0 _id_lock = threading.Lock() def _nextId(): global _transport_id try: _id_lock.acquire() _transport_id += 1 return _transport_id finally: _id_lock.release() INBOUND = 'i' OUTBOUND = 'o' BIDIRECTIONAL = 'b' ## Base API of Transport implementations class Transport(object): transport_type = 'UNKNOWN' ## @param self ## @param direction str: INBOUND | OUTBOUND | BIDIRECTIONAL ## @param name str def __init__(self, direction, name='unnamed'): self.name = name self.direction = direction self.done = False self.cleanup_cb = None self.endpoint_id = '' #STATS self.id = _nextId() self.stat_bytes = 0 # Number of messages that have passed through this transport self.stat_num_msg = 0 # Endpoint Details (IP, Port) self.local_endpoint = (0, 0) self.remote_endpoint = (0, 0) def fileno(self): """ Get a file descriptor for select() if available """ return None ## callback function to invoke when this connection is ## closed. Function will be passed this transport as an argument. ## @param self ## @param cleanup_callback fn(Transport): callback for when connection is closed def set_cleanup_callback(self, cleanup_callback): self.cleanup_cb = cleanup_callback ## terminate i/o. Leaf subclasses should override and call this implementation ## @param self def close(self): self.done = True if self.cleanup_cb: self.cleanup_cb(self) ## Write raw data to transport ## @throws TransportInitialiationError could not be initialized ## @throws TransportTerminated no longer open for publishing def write_data(self, data): raise Exception("not implemented") ## Implements the getTransportInfo() from roscpp ## Similar to getTransportInfo() in 'libros/transport/transport_tcp.cpp' def get_transport_info(self): raise NotImplementedError ## Shell class to hold stats about transport that is being killed off. ## This allows the information to stick around but the original Tranport to be gc'd class DeadTransport(Transport): ## @param self ## @param transport str: transport name def __init__(self, transport): super(DeadTransport, self).__init__( transport.direction, transport.name) self.transport_type = transport.transport_type #class property self.id = transport.id self.stat_bytes = transport.stat_bytes self.stat_num_msg = transport.stat_num_msg self.done = True self.endpoint_id = transport.endpoint_id self.local_endpoint = transport.local_endpoint self.remote_endpoint = transport.remote_endpoint ## @param self def get_transport_info(self): return "Closed %s connection on port %s to [%s:%s]" % (self.transport_type, self.local_endpoint[1], self.remote_endpoint[0], self.remote_endpoint[1]) ## ProtocolHandler interface: implements topic communication for a ## particular protocol(s). In order to understand the methods of this ## API, it is important to understand how topic communication is ## established: ## ## When a subscriber is notified of a new topic publisher, it contacts ## the publisher to establish a connection. The subscriber gathers a ## list of supported protocols (e.g. [['TCPROS'], ['MEMMAP']]) from ## its protocol handlers (L{get_supported}) and then passes these to ## the publisher. Each of these protocols is actual a list, ## e.g. ['MPI', LaneWidth, BusSpeed], since a protocol may have ## associated parameters. This is considered the start of the ## 'negotiation phase'. ## ## subscriber -> pub.requestTopic(protocols) ## ## The Publisher selects a protocol from the lists and tells the ## appropriate protocol handler to prepare the outbound connection: ## ## pub.requestTopic() -> pub.protocol_handler.init_publisher(selected_protocol) ## ## The protocol handler will return a new set of parameters ## representing connection parameters, e.g. [TCPROS, address, ## port]. These new parameters are passed back to the subscriber, ## which tells its protocol handler to establish the connection. ## ## subscriber -> subscriber.protocol_handler.create_transport(protocolParams) class ProtocolHandler(object): #interface ## shutdown any resources associated with handling this protocol ## @param self def shutdown(self): pass ## Create a new Transport using the specified \a protocol_params ## returned from the Publisher \a pub_uri. ## @param self ## @param protocol_params [[str, val*]]: parameter list from Publisher. Actual ## contents are protocol-specified. ## @param pub_uri str: publisher API URI ## @param topic str: topic name ## @return int, str, int: code, message, debug def create_transport(self, topic, pub_uri, protocol_params): raise Exception("interface impl") ## @param self ## @param protocol str: protocol name. Must match string identifier used in ## negotiation. ## @return bool: True if this handler supports the specified protocol""" def supports(self, protocol): return False ## This method is called on subscribers and returns the protocol list ## @param self ## @return [[str, val*]]: list of supported protocol params. Each set of protocol params is a ## list where the first element is the string identifier for the protocol. def get_supported(self): return [] ## Prepare a transport based on one of the supported protocols ## declared by a Subscriber. Subscribers supply a list of ## supported protocols, of which one is selected by the Publisher ## and passed to init_publisher(). init_publisher is responsible ## for initializing the publisher based on the selection. ## @param self ## @param topic str: name of topic ## @param protocol: selected protocol parameters from the Subscriber. ## @return (int, str, list): (code, statusMessage, params). params ## is protocol specific. These params will be sent to the Subscriber ## so that it can create_transport(). def init_publisher(self, topic, protocol): raise Exception("interface impl")
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/udpros.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ from __future__ import print_function """ UDPROS connection protocol. """ ## UDPROS connection protocol. # http://ros.org/wiki/ROS/UDPROS # import rosgraph.network import rospy.impl.registration import rospy.impl.transport def get_max_datagram_size(): #TODO return 1024 class UDPROSHandler(rospy.transport.ProtocolHandler): """ rospy protocol handler for UDPROS. Stores the datagram server if necessary. """ def __init__(self, port=0): """ ctor """ self.port = port self.buff_size = get_max_datagram_size() def init_server(self): """ Initialize and start the server thread, if not already initialized. """ if self.server is not None: return if rosgraph.network.use_ipv6(): s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) else: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((rosgraph.network.get_bind_address(), self.port)) if self.port == 0: self.port = s.getsockname()[1] self.server = s threading.start_new_thread(self.run, ()) def run(self): buff_size = self.buff_size try: while not rospy.core.is_shutdown(): data = self.server.recvfrom(self.buff_size) print("received packet") #TODO except: #TODO: log pass def shutdown(self): if self.sock is not None: self.sock.close() def create_transport(self, topic_name, pub_uri, protocol_params): """ Connect to topic resolved_name on Publisher pub_uri using UDPROS. @param resolved_name str: resolved topic name @type resolved_name: str @param pub_uri: XML-RPC URI of publisher @type pub_uri: str @param protocol_params: protocol parameters to use for connecting @type protocol_params: [XmlRpcLegal] @return: code, message, debug @rtype: (int, str, int) """ #Validate protocol params = [UDPROS, address, port, headers] if type(protocol_params) != list or len(protocol_params) != 4: return 0, "ERROR: invalid UDPROS parameters", 0 if protocol_params[0] != UDPROS: return 0, "INTERNAL ERROR: protocol id is not UDPROS: %s"%id, 0 #TODO: get connection_id and buffer size from params id, dest_addr, dest_port, headers = protocol_params self.init_server() #TODO: parse/validate headers sub = rospy.registration.get_topic_manager().get_subscriber_impl(topic_name) # Create Transport # TODO: create just a single 'connection' instance to represent # all UDP connections. 'connection' can take care of unifying # publication if addresses are the same transport = UDPTransport(protocol, topic_name, sub.receive_callback) # Attach connection to _SubscriberImpl if sub.add_connection(transport): #pass udp connection to handler return 1, "Connected topic[%s]. Transport impl[%s]"%(topic_name, transport.__class__.__name__), dest_port else: transport.close() return 0, "ERROR: Race condition failure: duplicate topic subscriber [%s] was created"%(topic_name), 0 def supports(self, protocol): """ @param protocol: name of protocol @type protocol: str @return: True if protocol is supported @rtype: bool """ return protocol == UDPROS def get_supported(self): """ Get supported protocols """ return [[UDPROS]] def init_publisher(self, topic_name, protocol_params): """ Initialize this node to start publishing to a new UDP location. @param resolved_name: topic name @type resolved__name: str @param protocol_params: requested protocol parameters. protocol[0] must be the string 'UDPROS' @type protocol_params: [str, value*] @return: (code, msg, [UDPROS, addr, port]) @rtype: (int, str, list) """ if protocol_params[0] != UDPROS: return 0, "Internal error: protocol does not match UDPROS: %s"%protocol, [] #TODO _, header, host, port, max_datagram_size = protocol_params #TODO: connection_id, max_datagraph_size return 1, "ready", [UDPROS] def topic_connection_handler(self, sock, client_addr, header): """ Process incoming topic connection. Reads in topic name from handshake and creates the appropriate L{TCPROSPub} handler for the connection. @param sock: socket connection @type sock: socket.socket @param client_addr: client address @type client_addr: (str, int) @param header: key/value pairs from handshake header @type header: dict @return: error string or None @rtype: str """ for required in ['topic', 'md5sum', 'callerid']: if not required in header: return "Missing required '%s' field"%required else: resolved_topic_name = header['topic'] md5sum = header['md5sum'] tm = rospy.registration.get_topic_manager() topic = tm.get_publisher_impl(resolved_topic_name) if not topic: return "[%s] is not a publisher of [%s]. Topics are %s"%(rospy.names.get_caller_id(), resolved_topic_name, tm.get_publications()) elif md5sum != rospy.names.TOPIC_ANYTYPE and md5sum != topic.data_class._md5sum: actual_type = topic.data_class._type # check to see if subscriber sent 'type' header. If they did, check that # types are same first as this provides a better debugging message if 'type' in header: requested_type = header['type'] if requested_type != actual_type: return "topic types do not match: [%s] vs. [%s]"%(requested_type, actual_type) else: # defaults to actual type requested_type = actual_type return "Client [%s] wants topic [%s] to have datatype/md5sum [%s/%s], but our version has [%s/%s] Dropping connection."%(header['callerid'], resolved_topic_name, requested_type, md5sum, actual_type, topic.data_class._md5sum) else: #TODO:POLLING if polling header is present, have to spin up receive loop as well # #1334: tcp_nodelay support from subscriber option if 'tcp_nodelay' in header: tcp_nodelay = True if header['tcp_nodelay'].strip() == '1' else False else: tcp_nodelay = self.tcp_nodelay_map.get(resolved_topic_name, False) _configure_pub_socket(sock, tcp_nodelay) protocol = TCPROSPub(resolved_topic_name, topic.data_class, is_latch=topic.is_latch, headers=topic.headers) transport = TCPROSTransport(protocol, resolved_topic_name) transport.set_socket(sock, header['callerid']) transport.write_header() topic.add_connection(transport) ## UDPROS communication routines class UDPROSTransport(rospy.transport.Transport): transport_type = 'UDPROS' def __init__(self, protocol, name, header): """ ctor @param name: topic name @type name: str: @param protocol: protocol implementation @param protocol: UDPROSTransportProtocol @param header: handshake header if transport handshake header was already read off of transport. @type header: dict @throws TransportInitError: if transport cannot be initialized according to arguments """ super(UDPROSTransport, self).__init__(protocol.direction, name=name) if not name: raise TransportInitError("Unable to initialize transport: name is not set") self.done = False self.header = header def send_message(self, msg, seq): """ Convenience routine for services to send a message across a particular connection. NOTE: write_data is much more efficient if same message is being sent to multiple connections. Not threadsafe. @param msg: message to send @type msg: Msg @param seq: sequence number for message @type seq: int @raise TransportException: if error occurred sending message """ # this will call write_data(), so no need to keep track of stats serialize_message(self.write_buff, seq, msg) self.write_data(self.write_buff.getvalue()) self.write_buff.truncate(0) def write_data(self, data): """ Write raw data to transport @raise TransportInitialiationError: could not be initialized @raise TransportTerminated: no longer open for publishing """ # TODO # - cut into packets # write to address pass def receive_once(self): """ block until messages are read off of socket @return: list of newly received messages @rtype: [Msg] @raise TransportException: if unable to receive message due to error """ pass ## Receive messages until shutdown ## @param self ## @param msgs_callback fn([msg]): callback to invoke for new messages received def receive_loop(self, msgs_callback): pass ## close i/o and release resources def close(super): self(UDPROSTransport, self).close() #TODO self.done = True _handler = UDPROSHandler() def get_handler(): return _handler
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/validators.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal-use Python decorators for parameter validation""" class ParameterInvalid(Exception): """Exception that is raised when a parameter fails validation checks""" def __init__(self, message): self._message = message def __str__(self): return str(self._message) def non_empty(param_name): """Validator that checks that parameter is not empty""" def validator(param, context): if not param: raise ParameterInvalid("ERROR: parameter [%s] must be specified and non-empty"%param_name) return param return validator
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/tcpros_pubsub.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal use: Topic-specific extensions for TCPROS support""" import socket import threading import time try: from xmlrpc.client import ServerProxy # Python 3.x except ImportError: from xmlrpclib import ServerProxy # Python 2.x from rospy.core import logwarn, logerr, logdebug, rospyerr import rospy.exceptions import rospy.names import rospy.impl.registration import rospy.impl.transport from rospy.impl.tcpros_base import TCPROSTransport, TCPROSTransportProtocol, \ get_tcpros_server_address, start_tcpros_server,\ DEFAULT_BUFF_SIZE, TCPROS class TCPROSSub(TCPROSTransportProtocol): """ Subscription transport implementation for receiving topic data via peer-to-peer TCP/IP sockets """ def __init__(self, resolved_name, recv_data_class, queue_size=None, \ buff_size=DEFAULT_BUFF_SIZE, tcp_nodelay=False): """ ctor. @param resolved_name: resolved subscription name @type resolved_name: str @param recv_data_class: class to instantiate to receive messages @type recv_data_class: L{rospy.Message} @param queue_size: maximum number of messages to deserialize from newly read data off socket @type queue_size: int @param buff_size: recv buffer size @type buff_size: int @param tcp_nodelay: If True, request TCP_NODELAY from publisher @type tcp_nodelay: bool """ super(TCPROSSub, self).__init__(resolved_name, recv_data_class, queue_size, buff_size) self.direction = rospy.impl.transport.INBOUND self.tcp_nodelay = tcp_nodelay def get_header_fields(self): """ @return: dictionary of subscriber fields @rtype: dict """ return {'topic': self.resolved_name, 'message_definition': self.recv_data_class._full_text, 'tcp_nodelay': '1' if self.tcp_nodelay else '0', 'md5sum': self.recv_data_class._md5sum, 'type': self.recv_data_class._type, 'callerid': rospy.names.get_caller_id(), 'node_type': "rospy"} # Separate method for easier testing def _configure_pub_socket(sock, is_tcp_nodelay): """ Configure socket options on a new publisher socket. @param sock: socket.socket @type sock: socket.socket @param is_tcp_nodelay: if True, TCP_NODELAY will be set on outgoing socket if available @param is_tcp_nodelay: bool """ # #956: low latency, TCP_NODELAY support if is_tcp_nodelay: if hasattr(socket, 'TCP_NODELAY'): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) else: logwarn("WARNING: cannot enable TCP_NODELAY as its not supported on this platform") #TODO:POLLING: TCPROSPub currently doesn't actually do anything -- not until polling is implemented class TCPROSPub(TCPROSTransportProtocol): """ Publisher transport implementation for publishing topic data via peer-to-peer TCP/IP sockets. """ def __init__(self, resolved_name, pub_data_class, is_latch=False, headers=None): """ ctor. @param resolved_name: resolved topic name @type resolved_name: str @param pub_data_class: class to instance to receive messages @type pub_data_class: L{rospy.Message} class @param is_latch: If True, Publisher is latching @type is_latch: bool """ # very small buffer size for publishers as the messages they receive are very small super(TCPROSPub, self).__init__(resolved_name, None, queue_size=None, buff_size=128) self.pub_data_class = pub_data_class self.direction = rospy.impl.transport.OUTBOUND self.is_latch = is_latch self.headers = headers if headers else {} def get_header_fields(self): base = {'topic': self.resolved_name, 'type': self.pub_data_class._type, 'latching': '1' if self.is_latch else '0', 'message_definition': self.pub_data_class._full_text, 'md5sum': self.pub_data_class._md5sum, 'callerid': rospy.names.get_caller_id(), 'node_type': "rospy"} # this implementation allows the user to override builtin # fields. this could potentially enable some interesting # features... or it could be really bad. if self.headers: base.update(self.headers) return base def robust_connect_subscriber(conn, dest_addr, dest_port, pub_uri, receive_cb, resolved_topic_name): """ Keeps trying to create connection for subscriber. Then passes off to receive_loop once connected. """ # kwc: this logic is not very elegant. I am waiting to rewrite # the I/O loop with async i/o to clean this up. # timeout is really generous. for now just choosing one that is large but not infinite interval = 0.5 while conn.socket is None and not conn.done and not rospy.is_shutdown(): try: conn.connect(dest_addr, dest_port, pub_uri, timeout=60.) except rospy.exceptions.TransportInitError as e: # if the connection was closed intentionally # because of an unknown error, stop trying if conn.protocol is None: conn.done = True break rospyerr("unable to create subscriber transport: %s. Will try again in %ss", e, interval) interval = interval * 2 time.sleep(interval) # check to see if publisher state has changed conn.done = not check_if_still_publisher(resolved_topic_name, pub_uri) if not conn.done: conn.receive_loop(receive_cb) def check_if_still_publisher(resolved_topic_name, pub_uri): try: s = ServerProxy(pub_uri) code, msg, val = s.getPublications(rospy.names.get_name()) if code == 1: return len([t for t in val if t[0] == resolved_topic_name]) > 0 else: return False except: return False class TCPROSHandler(rospy.impl.transport.ProtocolHandler): """ ROS Protocol handler for TCPROS. Accepts both TCPROS topic connections as well as ROS service connections over TCP. TCP server socket is run once start_server() is called -- this is implicitly called during init_publisher(). """ def __init__(self): """ctor""" self.tcp_nodelay_map = {} # { topic : tcp_nodelay} def set_tcp_nodelay(self, resolved_name, tcp_nodelay): """ @param resolved_name: resolved topic name @type resolved_name: str @param tcp_nodelay: If True, sets TCP_NODELAY on publisher's socket (disables Nagle algorithm). This results in lower latency publishing at the cost of efficiency. @type tcp_nodelay: bool """ self.tcp_nodelay_map[resolved_name] = tcp_nodelay def shutdown(self): """ stops the TCP/IP server responsible for receiving inbound connections """ pass def create_transport(self, resolved_name, pub_uri, protocol_params): """ Connect to topic resolved_name on Publisher pub_uri using TCPROS. @param resolved_name str: resolved topic name @type resolved_name: str @param pub_uri: XML-RPC URI of publisher @type pub_uri: str @param protocol_params: protocol parameters to use for connecting @type protocol_params: [XmlRpcLegal] @return: code, message, debug @rtype: (int, str, int) """ #Validate protocol params = [TCPROS, address, port] if type(protocol_params) != list or len(protocol_params) != 3: return 0, "ERROR: invalid TCPROS parameters", 0 if protocol_params[0] != TCPROS: return 0, "INTERNAL ERROR: protocol id is not TCPROS: %s"%id, 0 id, dest_addr, dest_port = protocol_params sub = rospy.impl.registration.get_topic_manager().get_subscriber_impl(resolved_name) #Create connection protocol = TCPROSSub(resolved_name, sub.data_class, \ queue_size=sub.queue_size, buff_size=sub.buff_size, tcp_nodelay=sub.tcp_nodelay) conn = TCPROSTransport(protocol, resolved_name) conn.set_endpoint_id(pub_uri); t = threading.Thread(name=resolved_name, target=robust_connect_subscriber, args=(conn, dest_addr, dest_port, pub_uri, sub.receive_callback,resolved_name)) # don't enable this just yet, need to work on this logic #rospy.core._add_shutdown_thread(t) # Attach connection to _SubscriberImpl if sub.add_connection(conn): #pass tcp connection to handler # since the thread might cause the connection to close # it should only be started after the connection has been added to the subscriber # https://github.com/ros/ros_comm/issues/544 t.start() return 1, "Connected topic[%s]. Transport impl[%s]"%(resolved_name, conn.__class__.__name__), dest_port else: # _SubscriberImpl already closed or duplicate subscriber created conn.close() return 0, "ERROR: Race condition failure creating topic subscriber [%s]"%(resolved_name), 0 def supports(self, protocol): """ @param protocol: name of protocol @type protocol: str @return: True if protocol is supported @rtype: bool """ return protocol == TCPROS def get_supported(self): """ Get supported protocols """ return [[TCPROS]] def init_publisher(self, resolved_name, protocol): """ Initialize this node to receive an inbound TCP connection, i.e. startup a TCP server if one is not already running. @param resolved_name: topic name @type resolved__name: str @param protocol: negotiated protocol parameters. protocol[0] must be the string 'TCPROS' @type protocol: [str, value*] @return: (code, msg, [TCPROS, addr, port]) @rtype: (int, str, list) """ if protocol[0] != TCPROS: return 0, "Internal error: protocol does not match TCPROS: %s"%protocol, [] start_tcpros_server() addr, port = get_tcpros_server_address() return 1, "ready on %s:%s"%(addr, port), [TCPROS, addr, port] def topic_connection_handler(self, sock, client_addr, header): """ Process incoming topic connection. Reads in topic name from handshake and creates the appropriate L{TCPROSPub} handler for the connection. @param sock: socket connection @type sock: socket.socket @param client_addr: client address @type client_addr: (str, int) @param header: key/value pairs from handshake header @type header: dict @return: error string or None @rtype: str """ if rospy.core.is_shutdown_requested(): return "Node is shutting down" for required in ['topic', 'md5sum', 'callerid']: if not required in header: return "Missing required '%s' field"%required else: resolved_topic_name = header['topic'] md5sum = header['md5sum'] tm = rospy.impl.registration.get_topic_manager() topic = tm.get_publisher_impl(resolved_topic_name) if not topic: return "[%s] is not a publisher of [%s]. Topics are %s"%(rospy.names.get_caller_id(), resolved_topic_name, tm.get_publications()) elif not topic.data_class or topic.closed: return "Internal error processing topic [%s]"%(resolved_topic_name) elif md5sum != rospy.names.TOPIC_ANYTYPE and md5sum != topic.data_class._md5sum: data_class = topic.data_class actual_type = data_class._type # check to see if subscriber sent 'type' header. If they did, check that # types are same first as this provides a better debugging message if 'type' in header: requested_type = header['type'] if requested_type != actual_type: return "topic types do not match: [%s] vs. [%s]"%(requested_type, actual_type) else: # defaults to actual type requested_type = actual_type return "Client [%s] wants topic [%s] to have datatype/md5sum [%s/%s], but our version has [%s/%s] Dropping connection."%(header['callerid'], resolved_topic_name, requested_type, md5sum, actual_type, data_class._md5sum) else: #TODO:POLLING if polling header is present, have to spin up receive loop as well # #1334: tcp_nodelay support from subscriber option if 'tcp_nodelay' in header: tcp_nodelay = True if header['tcp_nodelay'].strip() == '1' else False else: tcp_nodelay = self.tcp_nodelay_map.get(resolved_topic_name, False) _configure_pub_socket(sock, tcp_nodelay) protocol = TCPROSPub(resolved_topic_name, topic.data_class, is_latch=topic.is_latch, headers=topic.headers) transport = TCPROSTransport(protocol, resolved_topic_name) transport.set_socket(sock, header['callerid']) transport.remote_endpoint = client_addr transport.write_header() topic.add_connection(transport) class QueuedConnection(object): """ It wraps a Transport instance and behaves like one but it queues the data written to it and relays them asynchronously to the wrapped instance. """ def __init__(self, connection, queue_size): """ ctor. @param connection: the wrapped transport instance @type connection: Transport @param queue_size: the maximum size of the queue, zero means infinite @type queue_size: int """ super(QueuedConnection, self).__init__() self._connection = connection self._queue_size = queue_size self._lock = threading.Lock() self._cond_data_available = threading.Condition(self._lock) self._connection.set_cleanup_callback(self._closed_connection_callback) self._queue = [] self._error = None self._thread = threading.Thread(target=self._run) self._thread.start() def _closed_connection_callback(self, connection): with self._lock: self._cond_data_available.notify() def __getattr__(self, name): if name.startswith('__'): raise AttributeError(name) return getattr(self._connection, name) def write_data(self, data): with self._lock: # if there was previously an error within the dispatch thread raise it if self._error: error = self._error self._error = None raise error # pop oldest data if queue limit is reached if self._queue_size > 0 and len(self._queue) == self._queue_size: del self._queue[0] self._queue.append(data) self._cond_data_available.notify() # effectively yields the rest of the thread quantum time.sleep(0) return True def _run(self): while not self._connection.done: queue = [] with self._lock: # wait for available data while not self._queue and not self._connection.done: self._cond_data_available.wait() # take all data from queue for processing outside of the lock if self._queue: queue = self._queue self._queue = [] # relay all data for data in queue: try: self._connection.write_data(data) except Exception as e: with self._lock: self._error = e
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/broadcast_manager.py
# Software License Agreement (BSD License) # # Copyright (c) 2017, The Apollo Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ import os import json import time import socket import struct import decimal import logging import traceback import threading import functools import rospy.core from rospy.core import signal_shutdown from rospy.impl.registration import Registration from rospy.impl.registration import get_topic_manager from rospy.impl.registration import get_service_manager from rospy.impl.registration import get_node_handler from rosgraph.network import parse_http_host_and_port,get_host_name import sys env = os.environ.get('LD_LIBRARY_PATH') for sub_path in env.split(':'): sys.path.append(sub_path) from rospy.impl import participant NODE_NAME = 'node_name' TIMESTAMP = 'timestamp' XMLRPC_URI = 'xmlrpc_uri' REQUEST_TYPE = 'request_type' NODE_TIME = "node_time" TOPIC_NAME = "topic_name" TOPIC_TYPE = "topic_type" TOPIC_URI = "topic_uri" SERVICE_NAME = "service_name" SERVICE_TYPE = "service_type" SERVICE_URI = "service_uri" class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] def byteify(input): """ Convert unicode to str. """ if isinstance(input, dict): return {byteify(key): byteify(value) for key, value in input.iteritems()} elif isinstance(input, list): return [byteify(element) for element in input] elif isinstance(input, unicode): return input.encode('utf-8') else: return input class BroadcastManager(object): """ BroadcastManager. """ __metaclass__ = Singleton def __init__(self, name=None, callback=None): """ brief info for: __init__ """ super(BroadcastManager, self).__init__() self._logger = logging.getLogger(__name__) self._logger.setLevel(logging.INFO) if callback is None: self.callback = ["registerPublisher", "unregisterPublisher", "registerSubscriber", "unregisterSubscriber", "registerService", "unregisterService", "lookupService", "getTopicTypes", "lookupNode", "registerNode", ] else: self.callback = callback self._pubs = {} self._subs = {} self._service_cache = {} self._node_info = [] self._topic_info = [] self._pub_history = {} self._node_time = str(int(round(time.time()*1000))) if get_node_handler() is not None: self._name = get_node_handler().name while get_node_handler().uri is None: time.sleep(0.01) self._uri = get_node_handler().uri else: if name is None: self._name = "_null_name" else: self._name = name self._uri = "_null_uri" self._participant = participant.Participant(self._name) self._participant.init_py() self._broardcast_manager_thread = threading.Thread( target=self.run, args=()) self._broardcast_manager_thread.setDaemon(True) self._broardcast_manager_thread.start() def run(self): """ brief info for: thread run method """ self._logger.debug("starting broadcast_manager!") self._register_node() while True: try: msg = self._participant.read_msg() if msg is None: continue if(len(msg) > 0): data = self._unpack_msg(msg.strip()) if self._name == data[NODE_NAME]: if data[REQUEST_TYPE] == "registerNode" \ and self._uri != data[XMLRPC_URI] \ and int(data[NODE_TIME]) > int(self._node_time): signal_shutdown("it has already same name node, exit it now.") continue self._logger.debug("recv data: %s " % data) cb = '_' + data[REQUEST_TYPE] + "Callback" try: func = getattr(self, cb) func(data) except AttributeError: pass else: time.sleep(0.005) except Exception as e: self._logger.error("[broadcast_manager] Unexpected error: %s" % e) finally: pass def updateHandler(self): self._name = get_node_handler().name while get_node_handler().uri is None: time.sleep(0.01) self._uri = get_node_handler().uri def getUri(self, caller_id): """ getUri """ return 1, "", self._uri def getPid(self, caller_id): """ Get the PID of this server """ return 1, "", os.getpid() """ Publisher functions Subscirber functions Service functions """ def registerPublisher(self, name, topic, datatype, uri): """ registerPublisher """ data = self._generate_message("registerPublisher") data[TOPIC_NAME] = topic data[TOPIC_TYPE] = datatype self._send(self._encode(data)) if topic not in self._pubs: self._pubs[topic] = set() self._pubs[topic].add(uri) return 1, "Registered [%s] as publisher of [%s]" % (name, topic), [] def unregisterPublisher(self, name, topic, uri): """ unregisterPublisher """ data = self._generate_message("unregisterPublisher") data[NODE_NAME] = name data[TOPIC_NAME] = topic data[TOPIC_URI] = uri self._send(self._encode(data)) try: self._pubs[topic].remove(uri) except KeyError: pass return 1, "unregisterPublisher" ,0 def registerSubscriber(self, name, topic, datatype, uri): """ registerSubscriber """ data = self._generate_message("registerSubscriber") data[TOPIC_NAME] = topic data[TOPIC_TYPE] = datatype self._send(self._encode(data)) if topic not in self._subs: self._subs[topic] = set() self._subs[topic].add(uri) if topic in self._pub_history: for data in self._pub_history[topic]: self._registerPublisherCallback(self._unpack_msg(data)) return 1, "Subscribed to [%s]" % topic, [] def unregisterSubscriber(self, name, topic, uri): """ unregisterSubscriber """ data = self._generate_message("unregisterSubscriber") data[NODE_NAME] = name data[TOPIC_NAME] = topic data[TOPIC_URI] = uri self._send(self._encode(data)) try: self._subs[topic].remove(data[XMLRPC_URI]) except KeyError: pass return 1, "unregisterSubscriber" ,0 def registerService(self, name, service_name, service_uri, uri): """ registerService """ self._service_cache[service_name] = service_uri data = self._generate_message("registerService") data[SERVICE_NAME] = service_name data[SERVICE_URI] = service_uri self._send(self._encode(data)) return 1, "Registered [%s] as provider of [%s] with service_uri[%s]" % \ (name, service_name, service_uri), 1 def unregisterService(self, name, service_name, service_uri): """ unregisterService """ try: del self._service_cache[service_name] except KeyError: pass data = self._generate_message("unregisterService") data[NODE_NAME] = name data[SERVICE_NAME] = service_name data[SERVICE_URI] = service_uri self._send(self._encode(data)) return 1, "unregisterService" ,0 def lookupService(self, caller_id, service_name): """ lookupService """ retry = 5 while(retry > 0): try: return 1, "rosrpc URI: [%s]" % self._service_cache[service_name], self._service_cache[service_name] except KeyError: time.sleep(0.5) retry = retry - 1 return -1, "no provider", "" def lookupNode(self, caller_id, node_name): """ lookupNode """ node_info = [data for data in self._node_info if data[0] == node_name] if node_info: return 1, "node api", node_info[0][1] else: return -1, "unknown node" ,None def get_pubs(self): return self._pubs def get_subs(self): return self._subs """ Callbacks """ def _registerPublisherCallback(self, data): name = data[NODE_NAME] topic = data[TOPIC_NAME] topic_type = data[TOPIC_TYPE] topic_uri = data[XMLRPC_URI] uri_list = [topic_uri] topic_info = [x for x in self._topic_info if x[0] == topic] if topic_info: topic_info[0][1] = topic_type else: self._topic_info.append([topic, topic_type]) tm = get_topic_manager() try: tm.lock.acquire() if tm.has_subscription(topic): self._logger.debug("I has sub topic : %s" % topic) get_node_handler().publisherUpdate(name, topic, uri_list) except Exception as e: self._logger.error( "registerPublisherCallback error is %s" % e) self._logger.error(traceback.format_exc()) finally: tm.lock.release() if topic not in self._pubs: self._pubs[topic] = set() self._pubs[topic].add(topic_uri) if topic not in self._pub_history: self._pub_history[topic] = set() self._pub_history[topic].add(self._encode(data)) def _unregisterPublisherCallback(self, data): name = data[NODE_NAME] topic = data[TOPIC_NAME] uri = data[XMLRPC_URI] uri_list = [uri] tm = get_topic_manager() try: tm.lock.acquire() if tm.has_subscription(topic): self._logger.debug("I has sub topic, recv unregisSub: %s" % topic) get_node_handler().reg_man.reg_removed(topic, uri_list, Registration.SUB) except Exception as e: self._logger.error( "unregisterPublisherCallback error is %s" % e) self._logger.error(traceback.format_exc()) finally: tm.lock.release() try: self._pubs[topic].remove(uri) except KeyError: pass try: self._pub_history[topic].remove(self._encode(data)) except KeyError: pass def _registerSubscriberCallback(self, data): topic = data[TOPIC_NAME] topic_uri = data[XMLRPC_URI] if topic not in self._subs: self._subs[topic] = set() self._subs[topic].add(topic_uri) def _unregisterSubscriberCallback(self, data): uri = data[XMLRPC_URI] topic = data[TOPIC_NAME] try: self._subs[topic].remove(uri) except KeyError: pass def _registerServiceCallback(self, data): service_name = data[SERVICE_NAME] service_uri = data[SERVICE_URI] self._service_cache[service_name] = service_uri def _unregisterServiceCallback(self, data): service_name = data[SERVICE_NAME] service_uri = data[SERVICE_URI] try: del self._service_cache[service_name] except KeyError: pass def _registerNodeCallback(self, data): name = data[NODE_NAME] uri = data[XMLRPC_URI] node_info = [x for x in self._node_info if x[0] == name] if node_info: node_info[0][1] = uri else: self._node_info.append([name, uri]) def _register_node(self): """ _register_node """ data = self._generate_message("registerNode") data[NODE_TIME] = self._node_time self._send(self._encode(data)) """ Basic functions """ def _generate_message(self, request, timestamp=None): if timestamp is None: nsec_time = str(int(round(time.time()*1000))) else: nsec_time = timestamp header = {} header[REQUEST_TYPE] = request header[NODE_NAME] = self._name header[XMLRPC_URI] = self._uri header[TIMESTAMP] = nsec_time return header def _send(self, data): """ brief info for: Get _master_handler internal dict stuct according to dict_type """ self._participant.send(data) def _recv(self, size=1024): """ brief info for: Get _master_handler internal dict stuct according to dict_type """ msg = addr = None try: msg, addr = self._sock.recvfrom(size) except Exception as e: self._logger.error("socket recv error is %s" % e) self._logger.error(traceback.format_exc()) finally: pass return msg, addr def _unpack_msg(self, msg): try: data = json.loads(msg, object_hook=byteify) except Exception as e: self._logger.error("parse json failed! %s" % e) return data def _encode(self, data): return json.dumps(data)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/paramserver.py
# Software License Agreement (BSD License) # # Copyright (c) 2009, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Parameter Server Cache""" import threading #TODO: get rid of this routine entirely. It doesn't work with the current PS representation. class ParamServerCache(object): """ Cache of values on the parameter server. Implementation is just a thread-safe dictionary. """ def __init__(self): self.lock = threading.Lock() self.d = {} self.notifier = None ## Delete parameter from cache def delete(self, key): with self.lock: del self.d[key] def set_notifier(self, notifier): """ Notifier implements any parameter subscription logic. The notifier should be a function that takes in a key and value that represents a parameter update. Notifier is called under lock and thus must not implement any lengthy computation. """ self.notifier = notifier def update(self, key, value): """ Update the value of the parameter in the cache @param key: parameter key @type key: str @param value: parameter value @type value: str @raise: KeyError if key is not already in the cache. """ # TODOXXX: remove this code, as it is wrong. It is remaining # in place to maintain a unit test until the correct logic is # implemented. update() needs to check all subscribed keys and # do a prefix match. The best way to do this is probably to # pull the paramserver implementation from rosmaster and use # it here. if not key in self.d: raise KeyError(key) with self.lock: self.d[key] = value if self.notifier is not None: self.notifier(key, value) def set(self, key, value): """ Set the value of the parameter in the cache. This is a prerequisite of calling update(). @param key: parameter key @type key: str @param value: parameter value @type value: str """ with self.lock: self.d[key] = value def get(self, key): """ @param key: parameter key @type key: str @return: Current value for parameter @raise: KeyError """ with self.lock: return self.d[key] _param_server_cache = None def get_param_server_cache(): """ Get a handle on the client-wide parameter server cache """ global _param_server_cache if _param_server_cache is None: _param_server_cache = ParamServerCache() return _param_server_cache
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/masterslave.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Internal use: ROS Node (Slave) API. The Node API is implemented by the L{ROSHandler}. API return convention: (statusCode, statusMessage, returnValue) - statusCode: an integer indicating the completion condition of the method. - statusMessage: a human-readable string message for debugging - returnValue: the return value of the method; method-specific. Current status codes: - -1: ERROR: Error on the part of the caller, e.g. an invalid parameter - 0: FAILURE: Method was attempted but failed to complete correctly. - 1: SUCCESS: Method completed successfully. Individual methods may assign additional meaning/semantics to statusCode. """ import os import sys import itertools import logging import socket import threading import traceback import time try: #py3k import urllib.parse as urlparse except ImportError: import urlparse from rosgraph.xmlrpc import XmlRpcHandler import rospy.names import rospy.rostime import rospy.impl.tcpros from rospy.core import * from rospy.impl.paramserver import get_param_server_cache from rospy.impl.registration import RegManager, get_topic_manager from rospy.impl.validators import non_empty, ParameterInvalid # Return code slots STATUS = 0 MSG = 1 VAL = 2 # pseudo-validators ############################### # these validators actually return tuples instead of a function and it is up to a custom # validator on the class itself to perform the validation def is_publishers_list(paramName): return ('is_publishers_list', paramName) _logger = logging.getLogger("rospy.impl.masterslave") LOG_API = True def apivalidate(error_return_value, validators=()): """ ROS master/slave arg-checking decorator. Applies the specified validator to the corresponding argument and also remaps each argument to be the value returned by the validator. Thus, arguments can be simultaneously validated and canonicalized prior to actual function call. @param error_return_value: API value to return if call unexpectedly fails @param validators: sequence of validators to apply to each arg. None means no validation for the parameter is required. As all api methods take caller_id as the first parameter, the validators start with the second param. @type validators: sequence """ def check_validates(f): assert len(validators) == f.__code__.co_argcount - 2, "%s failed arg check"%f #ignore self and caller_id def validated_f(*args, **kwds): if LOG_API: _logger.debug("%s%s", f.__name__, str(args[1:])) #print "%s%s"%(f.func_name, str(args[1:])) if len(args) == 1: _logger.error("%s invoked without caller_id paramter"%f.__name__) return -1, "missing required caller_id parameter", error_return_value elif len(args) != f.__code__.co_argcount: return -1, "Error: bad call arity", error_return_value instance = args[0] caller_id = args[1] if not isinstance(caller_id, str): _logger.error("%s: invalid caller_id param type", f.__name__) return -1, "caller_id must be a string", error_return_value newArgs = [instance, caller_id] #canonicalized args try: for (v, a) in zip(validators, args[2:]): if v: try: #simultaneously validate + canonicalized args if type(v) == list or type(v) == tuple: newArgs.append(instance._custom_validate(v[0], v[1], a, caller_id)) else: newArgs.append(v(a, caller_id)) except ParameterInvalid as e: _logger.error("%s: invalid parameter: %s", f.__name__, str(e) or 'error') return -1, str(e) or 'error', error_return_value else: newArgs.append(a) if LOG_API: retval = f(*newArgs, **kwds) _logger.debug("%s%s returns %s", f.__name__, args[1:], retval) return retval else: code, msg, val = f(*newArgs, **kwds) if val is None: return -1, "Internal error (None value returned)", error_return_value return code, msg, val except TypeError as te: #most likely wrong arg number _logger.error(traceback.format_exc()) return -1, "Error: invalid arguments: %s"%te, error_return_value except Exception as e: #internal failure _logger.error(traceback.format_exc()) return 0, "Internal failure: %s"%e, error_return_value validated_f.__name__ = f.__name__ validated_f.__doc__ = f.__doc__ #preserve doc return validated_f return check_validates class ROSHandler(XmlRpcHandler): """ Base handler for both slave and master nodes. API methods generally provide the capability for establishing point-to-point connections with other nodes. Instance methods are XML-RPC API methods, so care must be taken as to what is added here. """ def __init__(self, name, master_uri): """ Base constructor for ROS nodes/masters @param name: ROS name of this node @type name: str @param master_uri: URI of master node, or None if this node is the master @type master_uri: str """ super(ROSHandler, self).__init__() self.masterUri = master_uri self.name = name self.uri = None self.done = False # initialize protocol handlers. The master will not have any. self.protocol_handlers = [] handler = rospy.impl.tcpros.get_tcpros_handler() if handler is not None: self.protocol_handlers.append(handler) self.reg_man = RegManager(self) ############################################################################### # INTERNAL def _is_registered(self): """ @return: True if slave API is registered with master. @rtype: bool """ if self.reg_man is None: return False else: return self.reg_man.is_registered() def _ready(self, uri): """ @param uri: XML-RPC URI @type uri: str callback from ROSNode to inform handler of correct i/o information """ _logger.info("_ready: %s", uri) self.uri = uri #connect up topics in separate thread if self.reg_man: t = threading.Thread(target=self.reg_man.start, args=(uri, self.masterUri)) rospy.core._add_shutdown_thread(t) t.start() def _custom_validate(self, validation, param_name, param_value, caller_id): """ Implements validation rules that require access to internal ROSHandler state. @param validation: name of validation rule to use @type validation: str @param param_name: name of parameter being validated @type param_name: str @param param_value str: value of parameter @type param_value: str @param caller_id: value of caller_id parameter to API method @type caller_id: str @raise ParameterInvalid: if the parameter does not meet validation @return: new value for parameter, after validation """ if validation == 'is_publishers_list': if not type(param_value) == list: raise ParameterInvalid("ERROR: param [%s] must be a list"%param_name) for v in param_value: if not isinstance(v, str): raise ParameterInvalid("ERROR: param [%s] must be a list of strings"%param_name) parsed = urlparse.urlparse(v) if not parsed[0] or not parsed[1]: #protocol and host raise ParameterInvalid("ERROR: param [%s] does not contain valid URLs [%s]"%(param_name, v)) return param_value else: raise ParameterInvalid("ERROR: param [%s] has an unknown validation type [%s]"%(param_name, validation)) ## static map for tracking which arguments to a function should be remapped # { methodName : [ arg indices ] _remap_table = { } @classmethod def remappings(cls, methodName): """ @internal @param cls: class to register remappings on @type cls: Class: class to register remappings on @return: parameters (by pos) that should be remapped because they are names @rtype: list """ if methodName in cls._remap_table: return cls._remap_table[methodName] else: return [] ############################################################################### # UNOFFICIAL/PYTHON-ONLY API @apivalidate('') ## (Python-Only API) Get the XML-RPC URI of this server ## @param self ## @param caller_id str: ROS caller id ## @return [int, str, str]: [1, "", xmlRpcUri] def getUri(self, caller_id): return 1, "", self.uri @apivalidate('') ## (Python-Only API) Get the ROS node name of this server ## @param self ## @param caller_id str: ROS caller id ## @return [int, str, str]: [1, "", ROS node name] def getName(self, caller_id): return 1, "", self.name ############################################################################### # EXTERNAL API @apivalidate([]) def getBusStats(self, caller_id): """ Retrieve transport/topic statistics @param caller_id: ROS caller id @type caller_id: str @return: [publishStats, subscribeStats, serviceStats]:: publishStats: [[topicName, messageDataSent, pubConnectionData]...[topicNameN, messageDataSentN, pubConnectionDataN]] pubConnectionData: [connectionId, bytesSent, numSent, connected]* . subscribeStats: [[topicName, subConnectionData]...[topicNameN, subConnectionDataN]] subConnectionData: [connectionId, bytesReceived, dropEstimate, connected]* . dropEstimate is -1 if no estimate. serviceStats: not sure yet, probably akin to [numRequests, bytesReceived, bytesSent] """ pub_stats, sub_stats = get_topic_manager().get_pub_sub_stats() #TODO: serviceStats return 1, '', [pub_stats, sub_stats, []] @apivalidate([]) def getBusInfo(self, caller_id): """ Retrieve transport/topic connection information @param caller_id: ROS caller id @type caller_id: str """ return 1, "bus info", get_topic_manager().get_pub_sub_info() @apivalidate('') def getMasterUri(self, caller_id): """ Get the URI of the master node. @param caller_id: ROS caller id @type caller_id: str @return: [code, msg, masterUri] @rtype: [int, str, str] """ if self.masterUri: return 1, self.masterUri, self.masterUri else: return 0, "master URI not set", "" def _shutdown(self, reason=''): """ @param reason: human-readable debug string @type reason: str """ if not self.done: self.done = True if reason: _logger.info(reason) if self.protocol_handlers: for handler in self.protocol_handlers: handler.shutdown() del self.protocol_handlers[:] self.protocol_handlers = None return True @apivalidate(0, (None, )) def shutdown(self, caller_id, msg=''): """ Stop this server @param caller_id: ROS caller id @type caller_id: str @param msg: a message describing why the node is being shutdown. @type msg: str @return: [code, msg, 0] @rtype: [int, str, int] """ if msg: print("shutdown request: %s"%msg) else: print("shutdown requst") if self._shutdown('external shutdown request from [%s]: %s'%(caller_id, msg)): signal_shutdown('external shutdown request from [%s]: [%s]'%(caller_id, msg)) return 1, "shutdown", 0 @apivalidate(-1) def getPid(self, caller_id): """ Get the PID of this server @param caller_id: ROS caller id @type caller_id: str @return: [1, "", serverProcessPID] @rtype: [int, str, int] """ return 1, "", os.getpid() ############################################################################### # PUB/SUB APIS @apivalidate([]) def getSubscriptions(self, caller_id): """ Retrieve a list of topics that this node subscribes to. @param caller_id: ROS caller id @type caller_id: str @return: list of topics this node subscribes to. @rtype: [int, str, [ [topic1, topicType1]...[topicN, topicTypeN]]] """ return 1, "subscriptions", get_topic_manager().get_subscriptions() @apivalidate([]) def getPublications(self, caller_id): """ Retrieve a list of topics that this node publishes. @param caller_id: ROS caller id @type caller_id: str @return: list of topics published by this node. @rtype: [int, str, [ [topic1, topicType1]...[topicN, topicTypeN]]] """ return 1, "publications", get_topic_manager().get_publications() def _connect_topic(self, topic, pub_uri): """ Connect subscriber to topic. @param topic: Topic name to connect. @type topic: str @param pub_uri: API URI of topic publisher. @type pub_uri: str @return: [code, msg, numConnects]. numConnects is the number of subscribers connected to the topic. @rtype: [int, str, int] """ caller_id = rospy.names.get_caller_id() sub = get_topic_manager().get_subscriber_impl(topic) if not sub: return -1, "No subscriber for topic [%s]"%topic, 0 elif sub.has_connection(pub_uri): return 1, "_connect_topic[%s]: subscriber already connected to publisher [%s]"%(topic, pub_uri), 0 #Negotiate with source for connection # - collect supported protocols protocols = [] for h in self.protocol_handlers: #currently only TCPROS protocols.extend(h.get_supported()) if not protocols: return 0, "ERROR: no available protocol handlers", 0 _logger.debug("connect[%s]: calling requestTopic(%s, %s, %s)", topic, caller_id, topic, str(protocols)) # 1) have to preserve original (unresolved) params as this may # go outside our graph # 2) xmlrpclib doesn't give us any way of affecting the # timeout other than affecting the global timeout. We need # to set a timeout to prevent infinite hangs. 60 seconds is # a *very* long time. All of the rospy code right now sets # individual socket timeouts, but this could potentially # affect user code. socket.setdefaulttimeout(60.) tries = 0 max_num_tries = 3 success = False while not success: tries += 1 try: code, msg, result = \ xmlrpcapi(pub_uri).requestTopic(caller_id, topic, protocols) success = True except Exception as e: if tries >= max_num_tries: return 0, "unable to requestTopic: %s"%str(e), 0 else: _logger.debug("Retrying for %s" % topic) #Create the connection (if possible) if code <= 0: _logger.debug("connect[%s]: requestTopic did not succeed %s, %s", pub_uri, code, msg) return code, msg, 0 elif not result or type(protocols) != list: return 0, "ERROR: publisher returned invalid protocol choice: %s"%(str(result)), 0 _logger.debug("connect[%s]: requestTopic returned protocol list %s", topic, result) protocol = result[0] for h in self.protocol_handlers: if h.supports(protocol): return h.create_transport(topic, pub_uri, result) return 0, "ERROR: publisher returned unsupported protocol choice: %s"%result, 0 @apivalidate(-1, (global_name('parameter_key'), None)) def paramUpdate(self, caller_id, parameter_key, parameter_value): """ Callback from master of current publisher list for specified topic. @param caller_id: ROS caller id @type caller_id: str @param parameter_key str: parameter name, globally resolved @type parameter_key: str @param parameter_value New parameter value @type parameter_value: XMLRPC-legal value @return: [code, status, ignore]. If code is -1 ERROR, the node is not subscribed to parameter_key @rtype: [int, str, int] """ try: get_param_server_cache().update(parameter_key, parameter_value) return 1, '', 0 except KeyError: return -1, 'not subscribed', 0 @apivalidate(-1, (is_topic('topic'), is_publishers_list('publishers'))) def publisherUpdate(self, caller_id, topic, publishers): """ Callback from master of current publisher list for specified topic. @param caller_id: ROS caller id @type caller_id: str @param topic str: topic name @type topic: str @param publishers: list of current publishers for topic in the form of XMLRPC URIs @type publishers: [str] @return: [code, status, ignore] @rtype: [int, str, int] """ if self.reg_man: for uri in publishers: self.reg_man.publisher_update(topic, publishers) return 1, "", 0 _remap_table['requestTopic'] = [0] # remap topic @apivalidate([], (is_topic('topic'), non_empty('protocols'))) def requestTopic(self, caller_id, topic, protocols): """ Publisher node API method called by a subscriber node. Request that source allocate a channel for communication. Subscriber provides a list of desired protocols for communication. Publisher returns the selected protocol along with any additional params required for establishing connection. For example, for a TCP/IP-based connection, the source node may return a port number of TCP/IP server. @param caller_id str: ROS caller id @type caller_id: str @param topic: topic name @type topic: str @param protocols: list of desired protocols for communication in order of preference. Each protocol is a list of the form [ProtocolName, ProtocolParam1, ProtocolParam2...N] @type protocols: [[str, XmlRpcLegalValue*]] @return: [code, msg, protocolParams]. protocolParams may be an empty list if there are no compatible protocols. @rtype: [int, str, [str, XmlRpcLegalValue*]] """ if not get_topic_manager().has_publication(topic): return -1, "Not a publisher of [%s]"%topic, [] for protocol in protocols: #simple for now: select first implementation protocol_id = protocol[0] for h in self.protocol_handlers: if h.supports(protocol_id): _logger.debug("requestTopic[%s]: choosing protocol %s", topic, protocol_id) return h.init_publisher(topic, protocol) return 0, "no supported protocol implementations", []
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/participant.py
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.11 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_participant', [dirname(__file__)]) except ImportError: import _participant return _participant if fp is not None: try: _mod = imp.load_module('_participant', fp, pathname, description) finally: fp.close() return _mod _participant = swig_import_helper() del swig_import_helper else: import _participant del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 class Listener(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Listener, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Listener, name) __repr__ = _swig_repr def __init__(self, *args): this = _participant.new_Listener(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _participant.delete_Listener __del__ = lambda self : None; def onSubscriptionMatched(self, *args): return _participant.Listener_onSubscriptionMatched(self, *args) def onNewDataMessage(self, *args): return _participant.Listener_onNewDataMessage(self, *args) def register_callback(self, *args): return _participant.Listener_register_callback(self, *args) Listener_swigregister = _participant.Listener_swigregister Listener_swigregister(Listener) class Participant(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Participant, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Participant, name) __repr__ = _swig_repr def __init__(self, *args): this = _participant.new_Participant(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _participant.delete_Participant __del__ = lambda self : None; def init(self, *args): return _participant.Participant_init(self, *args) def init_py(self): return _participant.Participant_init_py(self) def cache_msg(self, *args): return _participant.Participant_cache_msg(self, *args) def read_msg(self): return _participant.Participant_read_msg(self) def send(self, *args): return _participant.Participant_send(self, *args) Participant_swigregister = _participant.Participant_swigregister Participant_swigregister(Participant) # This file is compatible with both classic and new-style classes.
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/tcpros_service.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Internal use: Service-specific extensions for TCPROS support""" import io import socket import struct import sys import logging import time import traceback import genpy import rosgraph import rosgraph.names import rosgraph.network from rospy.exceptions import TransportInitError, TransportTerminated, ROSException, ROSInterruptException from rospy.service import _Service, ServiceException from rospy.impl.registration import get_service_manager from rospy.impl.tcpros_base import TCPROSTransport, TCPROSTransportProtocol, \ get_tcpros_server_address, start_tcpros_server, recv_buff, \ DEFAULT_BUFF_SIZE from rospy.core import logwarn, loginfo, logerr, logdebug import rospy.core import rospy.msg import rospy.names import rospy.impl.validators import threading from broadcast_manager import BroadcastManager if sys.hexversion > 0x03000000: #Python3 def isstring(s): return isinstance(s, str) #Python 3.x else: def isstring(s): return isinstance(s, basestring) #Python 2.x logger = logging.getLogger('rospy.service') ######################################################### # Service helpers def wait_for_service(service, timeout=None): """ Blocks until service is available. Use this in initialization code if your program depends on a service already running. @param service: name of service @type service: str @param timeout: timeout time in seconds, None for no timeout. NOTE: timeout=0 is invalid as wait_for_service actually contacts the service, so non-blocking behavior is not possible. For timeout=0 uses cases, just call the service without waiting. @type timeout: double @raise ROSException: if specified timeout is exceeded @raise ROSInterruptException: if shutdown interrupts wait """ master = rosgraph.Master(rospy.names.get_caller_id()) def contact_service(resolved_name, timeout=10.0): try: uri = master.lookupService(resolved_name) except Exception as e: return False addr = rospy.core.parse_rosrpc_uri(uri) if rosgraph.network.use_ipv6(): s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # we always want to timeout just in case we're connecting # to a down service. s.settimeout(timeout) logdebug('connecting to ' + str(addr)) s.connect(addr) h = { 'probe' : '1', 'md5sum' : '*', 'callerid' : rospy.core.get_caller_id(), 'service': resolved_name } rosgraph.network.write_ros_handshake_header(s, h) return True finally: if s is not None: s.close() if timeout == 0.: raise ValueError("timeout must be non-zero") resolved_name = rospy.names.resolve_name(service) first = False if timeout: timeout_t = time.time() + timeout while not rospy.core.is_shutdown() and time.time() < timeout_t: try: if contact_service(resolved_name, timeout_t-time.time()): return time.sleep(0.3) except KeyboardInterrupt: # re-raise rospy.core.logdebug("wait_for_service: received keyboard interrupt, assuming signals disabled and re-raising") raise except: # service not actually up if first: first = False rospy.core.logerr("wait_for_service(%s): failed to contact [%s], will keep trying"%(resolved_name, uri)) if rospy.core.is_shutdown(): raise ROSInterruptException("rospy shutdown") else: raise ROSException("timeout exceeded while waiting for service %s"%resolved_name) else: while not rospy.core.is_shutdown(): try: if contact_service(resolved_name): return time.sleep(0.3) except KeyboardInterrupt: # re-raise rospy.core.logdebug("wait_for_service: received keyboard interrupt, assuming signals disabled and re-raising") raise except: # service not actually up if first: first = False rospy.core.logerr("wait_for_service(%s): failed to contact [%s], will keep trying"%(resolved_name, uri)) if rospy.core.is_shutdown(): raise ROSInterruptException("rospy shutdown") def convert_return_to_response(response, response_class): """ Convert return value of function to response instance. The rules/precedence for this are: 1. If the return type is the same as the response type, no conversion is done. 2. If the return type is a dictionary, it is used as a keyword-style initialization for a new response instance. 3. If the return type is *not* a list type, it is passed in as a single arg to a new response instance. 4. If the return type is a list/tuple type, it is used as a args-style initialization for a new response instance. """ # use this declared ROS type check instead of a direct instance # check, which allows us to play tricks with serialization and # deserialization if isinstance(response, genpy.Message) and response._type == response_class._type: #if isinstance(response, response_class): return response elif type(response) == dict: # kwds response try: return response_class(**response) except AttributeError as e: raise ServiceException("handler returned invalid value: %s"%str(e)) elif response == None: raise ServiceException("service handler returned None") elif type(response) not in [list, tuple]: # single, non-list arg try: return response_class(response) except TypeError as e: raise ServiceException("handler returned invalid value: %s"%str(e)) else: # user returned a list, which has some ambiguous cases. Our resolution is that # all list/tuples are converted to *args try: return response_class(*response) except TypeError as e: raise ServiceException("handler returned wrong number of values: %s"%str(e)) def service_connection_handler(sock, client_addr, header): """ Process incoming service connection. For use with TCPROSServer. Reads in service name from handshake and creates the appropriate service handler for the connection. @param sock: socket connection @type sock: socket @param client_addr: client address @type client_addr: (str, int) @param header: key/value pairs from handshake header @type header: dict @return: error string or None @rtype: str """ for required in ['service', 'md5sum', 'callerid']: if not required in header: return "Missing required '%s' field"%required else: logger.debug("connection from %s:%s", client_addr[0], client_addr[1]) service_name = header['service'] #TODO: make service manager configurable. I think the right #thing to do is to make these singletons private members of a #Node instance and enable rospy to have multiple node #instances. sm = get_service_manager() md5sum = header['md5sum'] service = sm.get_service(service_name) if not service: return "[%s] is not a provider of [%s]"%(rospy.names.get_caller_id(), service_name) elif md5sum != rospy.names.SERVICE_ANYTYPE and md5sum != service.service_class._md5sum: return "request from [%s]: md5sums do not match: [%s] vs. [%s]"%(header['callerid'], md5sum, service.service_class._md5sum) else: transport = TCPROSTransport(service.protocol, service_name, header=header) transport.set_socket(sock, header['callerid']) transport.write_header() # using threadpool reduced performance by an order of # magnitude, need to investigate better t = threading.Thread(target=service.handle, args=(transport, header)) t.setDaemon(True) t.start() class TCPService(TCPROSTransportProtocol): """ Protocol implementation for Services over TCPROS """ def __init__(self, resolved_name, service_class, buff_size=DEFAULT_BUFF_SIZE): """ ctor. @param resolved_name: name of service @type resolved_name: str @param service_class: Service data type class @type service_class: Service @param buff_size int: size of buffer (bytes) to use for reading incoming requests. @type buff_size: int """ super(TCPService, self).__init__(resolved_name, service_class._request_class, buff_size=buff_size) self.service_class = service_class def get_header_fields(self): """ Protocol API @return: header fields @rtype: dict """ return {'service': self.resolved_name, 'type': self.service_class._type, 'md5sum': self.service_class._md5sum, 'callerid': rospy.names.get_caller_id() } class TCPROSServiceClient(TCPROSTransportProtocol): """Protocol Implementation for Service clients over TCPROS""" def __init__(self, resolved_name, service_class, headers=None, buff_size=DEFAULT_BUFF_SIZE): """ ctor. @param resolved_name: resolved service name @type resolved_name: str @param service_class: Service data type class @type service_class: Service @param headers: identifier for Service session @type headers: dict @param buff_size: size of buffer (bytes) for reading responses from Service. @type buff_size: int """ super(TCPROSServiceClient, self).__init__(resolved_name, service_class._response_class) self.service_class = service_class self.headers = headers or {} self.buff_size = buff_size def get_header_fields(self): """ TCPROSTransportProtocol API """ headers = {'service': self.resolved_name, 'md5sum': self.service_class._md5sum, 'callerid': rospy.names.get_caller_id()} # The current implementation allows user-supplied headers to # override protocol-specific headers. We may want to # eliminate this in the future if it is abused too severely. for k, v in self.headers.items(): headers[k] = v return headers def _read_ok_byte(self, b, sock): """ Utility for reading the OK-byte/error-message header preceding each message. @param sock: socket connection. Will be read from if OK byte is false and error message needs to be read @type sock: socket.socket @param b: buffer to read from @type b: StringIO """ if b.tell() == 0: return pos = b.tell() b.seek(0) ok = struct.unpack('<B', b.read(1))[0] # read in ok byte b.seek(pos) if not ok: str = self._read_service_error(sock, b) #_read_ok_byte has to reset state of the buffer to #consumed as this exception will bypass rest of #deserialized_messages logic. we currently can't have #multiple requests in flight, so we can keep this simple b.seek(0) b.truncate(0) raise ServiceException("service [%s] responded with an error: %s"%(self.resolved_name, str)) else: # success, set seek point to start of message b.seek(pos) def read_messages(self, b, msg_queue, sock): """ In service implementation, reads in OK byte that preceeds each response. The OK byte allows for the passing of error messages instead of a response message @param b: buffer @type b: StringIO @param msg_queue: Message queue to append to @type msg_queue: [Message] @param sock: socket to read from @type sock: socket.socket """ self._read_ok_byte(b, sock) rospy.msg.deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size, max_msgs=1, start=1) #rospy.msg #deserialize_messages only resets the buffer to the start #point if everything was consumed, so we have to further reset #it. if b.tell() == 1: b.seek(0) def _read_service_error(self, sock, b): """ Read service error from sock @param sock: socket to read from @type sock: socket @param b: currently read data from sock @type b: StringIO """ buff_size = 256 #can be small given that we are just reading an error string while b.tell() < 5: recv_buff(sock, b, buff_size) bval = b.getvalue() (length,) = struct.unpack('<I', bval[1:5]) # ready in len byte while b.tell() < (5 + length): recv_buff(sock, b, buff_size) bval = b.getvalue() return struct.unpack('<%ss'%length, bval[5:5+length])[0] # ready in len byte class ServiceProxy(_Service): """ Create a handle to a ROS service for invoking calls. Usage:: add_two_ints = ServiceProxy('add_two_ints', AddTwoInts) resp = add_two_ints(1, 2) """ def __init__(self, name, service_class, persistent=False, headers=None): """ ctor. @param name: name of service to call @type name: str @param service_class: auto-generated service class @type service_class: Service class @param persistent: (optional) if True, proxy maintains a persistent connection to service. While this results in better call performance, persistent connections are discouraged as they are less resistent to network issues and service restarts. @type persistent: bool @param headers: (optional) arbitrary headers @type headers: dict """ super(ServiceProxy, self).__init__(name, service_class) self.uri = None self.seq = 0 self.buff_size = DEFAULT_BUFF_SIZE self.persistent = persistent if persistent: if not headers: headers = {} headers['persistent'] = '1' self.protocol = TCPROSServiceClient(self.resolved_name, self.service_class, headers=headers) self.transport = None #for saving persistent connections def wait_for_service(self, timeout=None): wait_for_service(self.resolved_name, timeout=timeout) # #425 def __call__(self, *args, **kwds): """ Callable-style version of the service API. This accepts either a request message instance, or you can call directly with arguments to create a new request instance. e.g.:: add_two_ints(AddTwoIntsRequest(1, 2)) add_two_ints(1, 2) add_two_ints(a=1, b=2) @param args: arguments to remote service @param kwds: message keyword arguments @raise ROSSerializationException: If unable to serialize message. This is usually a type error with one of the fields. """ return self.call(*args, **kwds) def _get_service_uri(self, request): """ private routine for getting URI of service to call @param request: request message @type request: L{rospy.Message} """ if not isinstance(request, genpy.Message): raise TypeError("request object is not a valid request message instance") # in order to support more interesting overrides, we only # check that it declares the same ROS type instead of a # stricter class check #if not self.request_class == request.__class__: if not self.request_class._type == request._type: raise TypeError("request object type [%s] does not match service type [%s]"%(request.__class__, self.request_class)) #TODO: subscribe to service changes #if self.uri is None: if 1: #always do lookup for now, in the future we need to optimize try: try: master = rosgraph.Master(rospy.names.get_caller_id()) self.uri = master.lookupService(self.resolved_name) except socket.error: raise ServiceException("unable to contact master") except Exception as e: logger.error("[%s]: lookup service failed with message [%s]", self.resolved_name, str(e)) raise ServiceException("service [%s] unavailable"%self.resolved_name) # validate try: rospy.core.parse_rosrpc_uri(self.uri) except rospy.impl.validators.ParameterInvalid: raise ServiceException("master returned invalid ROSRPC URI: %s"%self.uri) except socket.error as e: logger.error("[%s]: socket error contacting service, master is probably unavailable",self.resolved_name) return self.uri def call(self, *args, **kwds): """ Call the service. This accepts either a request message instance, or you can call directly with arguments to create a new request instance. e.g.:: add_two_ints(AddTwoIntsRequest(1, 2)) add_two_ints(1, 2) add_two_ints(a=1, b=2) @raise TypeError: if request is not of the valid type (Message) @raise ServiceException: if communication with remote service fails @raise ROSInterruptException: if node shutdown (e.g. ctrl-C) interrupts service call @raise ROSSerializationException: If unable to serialize message. This is usually a type error with one of the fields. """ # convert args/kwds to request message class request = rospy.msg.args_kwds_to_message(self.request_class, args, kwds) # initialize transport if self.transport is None: service_uri = self._get_service_uri(request) dest_addr, dest_port = rospy.core.parse_rosrpc_uri(service_uri) # connect to service transport = TCPROSTransport(self.protocol, self.resolved_name) transport.buff_size = self.buff_size try: transport.connect(dest_addr, dest_port, service_uri) except TransportInitError as e: # can be a connection or md5sum mismatch raise ServiceException("unable to connect to service: %s"%e) self.transport = transport else: transport = self.transport # send the actual request message self.seq += 1 transport.send_message(request, self.seq) try: responses = transport.receive_once() if len(responses) == 0: raise ServiceException("service [%s] returned no response"%self.resolved_name) elif len(responses) > 1: raise ServiceException("service [%s] returned multiple responses: %s"%(self.resolved_name, len(responses))) except rospy.exceptions.TransportException as e: # convert lower-level exception to exposed type if rospy.core.is_shutdown(): raise rospy.exceptions.ROSInterruptException("node shutdown interrupted service call") else: raise ServiceException("transport error completing service call: %s"%(str(e))) finally: if not self.persistent: transport.close() self.transport = None return responses[0] def close(self): """Close this ServiceProxy. This only has an effect on persistent ServiceProxy instances.""" if self.transport is not None: self.transport.close() class ServiceImpl(_Service): """ Implementation of ROS Service. This intermediary class allows for more configuration of behavior than the Service class. """ def __init__(self, name, service_class, handler, buff_size=DEFAULT_BUFF_SIZE, error_handler=None): super(ServiceImpl, self).__init__(name, service_class) if not name or not isstring(name): raise ValueError("service name is not a non-empty string") # #2202 if not rosgraph.names.is_legal_name(name): import warnings warnings.warn("'%s' is not a legal ROS graph resource name. This may cause problems with other ROS tools"%name, stacklevel=2) self.handler = handler if error_handler is not None: self.error_handler = error_handler self.registered = False self.seq = 0 self.done = False self.buff_size=buff_size start_tcpros_server() #lazy-init the tcprosserver host, port = get_tcpros_server_address() self.uri = '%s%s:%s'%(rospy.core.ROSRPC, host, port) logdebug("... service URL is %s"%self.uri) self.protocol = TCPService(self.resolved_name, service_class, self.buff_size) logdebug("[%s]: new Service instance"%self.resolved_name) # TODO: should consider renaming to unregister def error_handler(self, e, exc_type, exc_value, tb): logerr("Error processing request: %s\n%s" % (e, traceback.format_exception(exc_type, exc_value, tb))) def shutdown(self, reason=''): """ Stop this service @param reason: human-readable shutdown reason @type reason: str """ self.done = True logdebug('[%s].shutdown: reason [%s]'%(self.resolved_name, reason)) try: #TODO: make service manager configurable get_service_manager().unregister(self.resolved_name, self) except Exception as e: logerr("Unable to unregister with master: "+traceback.format_exc()) raise ServiceException("Unable to connect to master: %s"%e) def spin(self): """ Let service run and take over thread until service or node shutdown. Use this method to keep your scripts from exiting execution. """ try: while not rospy.core.is_shutdown() and not self.done: time.sleep(0.5) except KeyboardInterrupt: logdebug("keyboard interrupt, shutting down") def _write_service_error(self, transport, err_msg): """ Send error message to client @param transport: transport connection to client @type transport: Transport @param err_msg: error message to send to client @type err_msg: str """ transport.write_data(struct.pack('<BI%ss'%len(err_msg), 0, len(err_msg), err_msg)) def _handle_request(self, transport, request): """ Process a single incoming request. @param transport: transport instance @type transport: L{TCPROSTransport} @param request: Message @type request: genpy.Message """ try: # convert return type to response Message instance response = convert_return_to_response(self.handler(request), self.response_class) self.seq += 1 # ok byte transport.write_buff.write(struct.pack('<B', 1)) transport.send_message(response, self.seq) except ServiceException as e: rospy.core.rospydebug("handler raised ServiceException: %s"%(e)) self._write_service_error(transport, "service cannot process request: %s"%e) except Exception as e: (exc_type, exc_value, tb) = sys.exc_info() self.error_handler(e, exc_type, exc_value, tb) self._write_service_error(transport, "error processing request: %s"%e) def handle(self, transport, header): """ Process incoming request. This method should be run in its own thread. If header['persistent'] is set to 1, method will block until connection is broken. @param transport: transport instance @type transport: L{TCPROSTransport} @param header: headers from client @type header: dict """ if 'persistent' in header and \ header['persistent'].lower() in ['1', 'true']: persistent = True else: persistent = False if header.get('probe', None) == '1': #this will likely do more in the future transport.close() return handle_done = False while not handle_done: try: requests = transport.receive_once() for request in requests: self._handle_request(transport, request) if not persistent: handle_done = True except rospy.exceptions.TransportTerminated as e: if not persistent: logerr("incoming connection failed: %s"%e) logdebug("service[%s]: transport terminated"%self.resolved_name) handle_done = True transport.close() class Service(ServiceImpl): """ Declare a ROS service. Service requests are passed to the specified handler. Service Usage:: s = Service('getmapservice', GetMap, get_map_handler) """ def __init__(self, name, service_class, handler, buff_size=DEFAULT_BUFF_SIZE, error_handler=None): """ ctor. @param name: service name, ``str`` @param service_class: Service definition class @param handler: callback function for processing service request. Function takes in a ServiceRequest and returns a ServiceResponse of the appropriate type. Function may also return a list, tuple, or dictionary with arguments to initialize a ServiceResponse instance of the correct type. If handler cannot process request, it may either return None, to indicate failure, or it may raise a rospy.ServiceException to send a specific error message to the client. Returning None is always considered a failure. @type handler: fn(req)->resp @param buff_size: size of buffer for reading incoming requests. Should be at least size of request message @type buff_size: int @param error_handler: callback function for handling errors raised in the service code. @type error_handler: fn(exception, exception_type, exception_value, traceback)->None """ super(Service, self).__init__(name, service_class, handler, buff_size, error_handler) #TODO: make service manager configurable get_service_manager().register(self.resolved_name, self)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/tcpros.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ TCPROS connection protocol. Implements: U{http://ros.org/wiki/ROS/TCPROS} The rospy tcpros implementation is split into three areas: - L{rospy.tcpros_base}: common TCPROS routines, including header and connection processing - L{rospy.tcpros_pubsub}: Topic-specific capabilities for publishing and subscribing - L{rospy.tcpros_service}: Service-specific capabilities """ import rospy.impl.tcpros_service from rospy.impl.tcpros_base import init_tcpros_server, DEFAULT_BUFF_SIZE from rospy.impl.tcpros_pubsub import TCPROSHandler _handler = TCPROSHandler() def init_tcpros(port=0): """ @param tcpros_port: override the port of the TCP server @type tcpros_port: int """ server = init_tcpros_server(port) server.topic_connection_handler = _handler.topic_connection_handler server.service_connection_handler = rospy.impl.tcpros_service.service_connection_handler def get_tcpros_handler(): return _handler
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/simtime.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal-use: Support for simulated clock.""" import traceback import rosgraph from rosgraph_msgs.msg import Clock import rospy.core import rospy.rostime import rospy.topics # ROS clock topics and parameter config _ROSCLOCK = '/clock' _USE_SIMTIME = '/use_sim_time' # Subscriber handles for /clock and /time _rostime_sub = None _rosclock_sub = None 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) try: code, msg, val = m.getParam(rospy.names.get_caller_id(), _USE_SIMTIME) if code == 1 and val: return True except Exception as e: pass return False from rospy.rostime import _set_rostime def _set_rostime_clock_wrapper(time_msg): _set_rostime(time_msg.clock) def _set_rostime_time_wrapper(time_msg): _set_rostime(time_msg.rostime) def init_simtime(): """ Initialize the ROS time system by connecting to the /time topic IFF the /use_sim_time parameter is set. """ import logging logger = logging.getLogger("rospy.simtime") try: if not _is_use_simtime(): print("%s is not set, will not subscribe to simulated time [%s] topic"%(_USE_SIMTIME, _ROSCLOCK)) else: global _rostime_sub, _clock_sub if _rostime_sub is None: logger.info("initializing %s core topic"%_ROSCLOCK) _clock_sub = rospy.topics.Subscriber(_ROSCLOCK, Clock, _set_rostime_clock_wrapper, queue_size=1) logger.info("connected to core topic %s"%_ROSCLOCK) _set_rostime(rospy.rostime.Time(0, 0)) rospy.rostime.set_rostime_initialized(True) return True except Exception as e: #logger.error("Unable to initialize %s: %s\n%s", _ROSCLOCK, e, traceback.format_exc()) #return False rospy.rostime.set_rostime_initialized(True) return True
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/statistics.py
# Software License Agreement (BSD License) # # Copyright (c) 2013-2014 Dariush Forouher # All rights reserved. # # Based on code adapted from diagnostics_updater by Blaise Gassend # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from math import sqrt import logging import sys from rosgraph_msgs.msg import TopicStatistics import rospy _logger = logging.getLogger('rospy.impl.statistics') class SubscriberStatisticsLogger(): """ Class that monitors each subscriber. this class basically just keeps a collection of ConnectionStatisticsLogger. """ @classmethod def is_enabled(cls): # disable statistics if node can't talk to parameter server # which is the case in unit tests try: return rospy.get_param("/enable_statistics", False) except Exception: return False def __init__(self, subscriber): self.subscriber_name = subscriber.name self.connections = dict() self.read_parameters() def read_parameters(self): """ Fetch window parameters from parameter server """ # Range of window length, in seconds self.min_elements = rospy.get_param("/statistics_window_min_elements", 10) self.max_elements = rospy.get_param("/statistics_window_max_elements", 100) # Range of acceptable messages in window. # Window size will be adjusted if number of observed is # outside this range. self.max_window = rospy.get_param("/statistics_window_max_size", 64) self.min_window = rospy.get_param("/statistics_window_min_size", 4) def callback(self, msg, publisher, stat_bytes): """ This method is called for every message that has been received. @param msg: The message received. @param publisher: The name of the publisher node that sent the msg @param stat_bytes: A counter, how many bytes have been moved across this connection since it exists. This method just looks up the ConnectionStatisticsLogger for the specific connection between publisher and subscriber and delegates to statistics logging to that instance. """ # /clock is special, as it is subscribed very early # also exclude /statistics to reduce noise. if self.subscriber_name == "/clock" or self.subscriber_name == "/statistics": return try: # create ConnectionStatisticsLogger for new connections logger = self.connections.get(publisher) if logger is None: logger = ConnectionStatisticsLogger(self.subscriber_name, rospy.get_name(), publisher) self.connections[publisher] = logger # delegate stuff to that instance logger.callback(self, msg, stat_bytes) except Exception as e: rospy.logerr("Unexpected error during statistics measurement: %s", str(e)) def shutdown(self): for logger in self.connections.values(): logger.shutdown() self.connections.clear() class ConnectionStatisticsLogger(): """ Class that monitors lots of stuff for each connection. is created whenever a subscriber is created. is destroyed whenever its parent subscriber is destroyed. its lifecycle is therefore bound to its parent subscriber. """ def __init__(self, topic, subscriber, publisher): """ Constructor. @param topic: Name of the topic @param subscriber: Name of the subscriber @param publisher: Name of the publisher These three should uniquely identify the connection. """ self.topic = topic self.subscriber = subscriber self.publisher = publisher self.pub = rospy.Publisher("/statistics", TopicStatistics, queue_size=10) # reset window self.last_pub_time = rospy.Time(0) self.pub_frequency = rospy.Duration(1.0) # timestamp age self.age_list_ = [] # period calculations self.arrival_time_list_ = [] self.last_seq_ = 0 self.dropped_msgs_ = 0 self.window_start = rospy.Time.now() # temporary variables self.stat_bytes_last_ = 0 self.stat_bytes_window_ = 0 def sendStatistics(self, subscriber_statistics_logger): """ Send out statistics. Aggregate collected stats information. Currently done blocking. Might be moved to own thread later. But at the moment any computation done here should be rather quick. """ curtime = rospy.Time.now() msg = TopicStatistics() msg.topic = self.topic msg.node_sub = self.subscriber msg.node_pub = self.publisher msg.window_start = self.window_start msg.window_stop = curtime # Calculate bytes since last message msg.traffic = self.stat_bytes_window_ - self.stat_bytes_last_ msg.delivered_msgs = len(self.arrival_time_list_) msg.dropped_msgs = self.dropped_msgs_ # we can only calculate message age if the messages did contain Header fields. if len(self.age_list_) > 0: msg.stamp_age_mean = rospy.Duration(sum(self.age_list_, rospy.Duration(0)).to_sec() / len(self.age_list_)) variance = sum((rospy.Duration((msg.stamp_age_mean - value).to_sec() ** 2) for value in self.age_list_), rospy.Duration(0)) / len(self.age_list_) msg.stamp_age_stddev = rospy.Duration(sqrt(variance.to_sec())) msg.stamp_age_max = max(self.age_list_) else: msg.stamp_age_mean = rospy.Duration(0) msg.stamp_age_stddev = rospy.Duration(0) msg.stamp_age_max = rospy.Duration(0) # computer period/frequency. we need at least two messages within the window to do this. if len(self.arrival_time_list_) > 1: periods = [j - i for i, j in zip(self.arrival_time_list_[:-1], self.arrival_time_list_[1:])] msg.period_mean = rospy.Duration(sum(periods, rospy.Duration(0)).to_sec() / len(periods)) variance = sum((rospy.Duration((msg.period_mean - value).to_sec() ** 2) for value in periods), rospy.Duration(0)) / len(periods) msg.period_stddev = rospy.Duration(sqrt(variance.to_sec())) msg.period_max = max(periods) else: msg.period_mean = rospy.Duration(0) msg.period_stddev = rospy.Duration(0) msg.period_max = rospy.Duration(0) self.pub.publish(msg) # adjust window, if message count is not appropriate. if len(self.arrival_time_list_) > subscriber_statistics_logger.max_elements and self.pub_frequency.to_sec() * 2 <= subscriber_statistics_logger.max_window: self.pub_frequency *= 2 if len(self.arrival_time_list_) < subscriber_statistics_logger.min_elements and self.pub_frequency.to_sec() / 2 >= subscriber_statistics_logger.min_window: self.pub_frequency /= 2 # clear collected stats, start new window. self.age_list_ = [] self.arrival_time_list_ = [] self.dropped_msgs_ = 0 self.window_start = curtime self.stat_bytes_last_ = self.stat_bytes_window_ def callback(self, subscriber_statistics_logger, msg, stat_bytes): """ This method is called for every message, that is received on this subscriber. this callback will keep some statistics and publish the results periodically on a topic. the publishing should probably be done asynchronically in another thread. @param msg: The message, that has been received. The message has usually been already deserialized. However this is not always the case. (AnyMsg) @param stat_bytes: A counter, how many bytes have been moved across this connection since it exists. Any computing-heavy stuff should be done somewhere else, as this callback has to return before the message is delivered to the user. """ arrival_time = rospy.Time.now() self.arrival_time_list_.append(arrival_time) self.stat_bytes_window_ = stat_bytes # rospy has the feature to subscribe a topic with AnyMsg which aren't deserialized. # Those subscribers won't have a header. But as these subscribers are rather rare # ("rostopic hz" is the only one I know of), I'm gonna ignore them. if msg._has_header: self.age_list_.append(arrival_time - msg.header.stamp) if self.last_seq_ + 1 != msg.header.seq: self.dropped_msgs_ = self.dropped_msgs_ + 1 self.last_seq_ = msg.header.seq # send out statistics with a certain frequency if self.last_pub_time + self.pub_frequency < arrival_time: self.last_pub_time = arrival_time self.sendStatistics(subscriber_statistics_logger) def shutdown(self): self.pub.unregister()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/tcpros_base.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal use: common TCPROS libraries""" try: from cStringIO import StringIO #Python 2.x python3 = 0 except ImportError: from io import StringIO, BytesIO #Python 3.x python3 = 1 import socket import logging import threading import time import traceback import select import rosgraph import rosgraph.network from genpy import DeserializationError, Message from rosgraph.network import read_ros_handshake_header, write_ros_handshake_header # TODO: remove * import from core from rospy.core import * from rospy.core import logwarn, loginfo, logerr, logdebug, rospydebug, rospyerr, rospywarn from rospy.exceptions import ROSInternalException, TransportException, TransportTerminated, TransportInitError from rospy.msg import deserialize_messages, serialize_message from rospy.service import ServiceException from rospy.impl.transport import Transport, BIDIRECTIONAL import google.protobuf logger = logging.getLogger('rospy.tcpros') # Receive buffer size for topics/services (in bytes) DEFAULT_BUFF_SIZE = 65536 ## name of our customized TCP protocol for accepting flows over server socket TCPROS = "TCPROS" _PARAM_TCP_KEEPALIVE = '/tcp_keepalive' _use_tcp_keepalive = None _use_tcp_keepalive_lock = threading.Lock() 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()) try: code, msg, val = m.getParam(rospy.names.get_caller_id(), _PARAM_TCP_KEEPALIVE) _use_tcp_keepalive = val if code == 1 else True except Exception: _use_tcp_keepalive = True return _use_tcp_keepalive def recv_buff(sock, b, buff_size): """ Read data from socket into buffer. @param sock: socket to read from @type sock: socket.socket @param b: buffer to receive into @type b: StringIO @param buff_size: recv read size @type buff_size: int @return: number of bytes read @rtype: int """ d = sock.recv(buff_size) if d: b.write(d) return len(d) else: #bomb out raise TransportTerminated("unable to receive data from sender, check sender's logs for details") class TCPServer(object): """ Simple server that accepts inbound TCP/IP connections and hands them off to a handler function. TCPServer obeys the ROS_IP/ROS_HOSTNAME environment variables """ def __init__(self, inbound_handler, port=0): """ Setup a server socket listening on the specified port. If the port is omitted, will choose any open port. @param inbound_handler: handler to invoke with new connection @type inbound_handler: fn(sock, addr) @param port: port to bind to, omit/0 to bind to any @type port: int """ self.port = port #will get overwritten if port=0 self.addr = None #set at socket bind self.is_shutdown = False self.inbound_handler = inbound_handler try: self.server_sock = self._create_server_sock() except: self.server_sock = None raise def start(self): """Runs the run() loop in a separate thread""" t = threading.Thread(target=self.run, args=()) t.setDaemon(True) t.start() def run(self): """ Main TCP receive loop. Should be run in a separate thread -- use start() to do this automatically. """ self.is_shutdown = False if not self.server_sock: raise ROSInternalException("%s did not connect"%self.__class__.__name__) while not self.is_shutdown: try: (client_sock, client_addr) = self.server_sock.accept() except socket.timeout: continue except IOError as e: (errno, msg) = e.args if errno == 4: #interrupted system call continue raise if self.is_shutdown: break try: #leave threading decisions up to inbound_handler self.inbound_handler(client_sock, client_addr) except socket.error as e: if not self.is_shutdown: traceback.print_exc() logwarn("Failed to handle inbound connection due to socket error: %s"%e) logdebug("TCPServer[%s] shutting down", self.port) def get_full_addr(self): """ @return: (ip address, port) of server socket binding @rtype: (str, int) """ # return rosgraph.network.get_host_name() instead of address so that it # obeys ROS_IP/ROS_HOSTNAME behavior return (rosgraph.network.get_host_name(), self.port) def _create_server_sock(self): """ binds the server socket. ROS_IP/ROS_HOSTNAME may restrict binding to loopback interface. """ if rosgraph.network.use_ipv6(): server_sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) logdebug('binding to ' + str(rosgraph.network.get_bind_address()) + ' ' + str(self.port)) server_sock.bind((rosgraph.network.get_bind_address(), self.port)) (self.addr, self.port) = server_sock.getsockname()[0:2] logdebug('bound to ' + str(self.addr) + ' ' + str(self.port)) server_sock.listen(5) return server_sock def shutdown(self): """shutdown I/O resources uses by this server""" if not self.is_shutdown: self.is_shutdown = True self.server_sock.close() # base maintains a tcpros_server singleton that is shared between # services and topics for inbound connections. This global is set in # the tcprosserver constructor. Constructor is called by init_tcpros() _tcpros_server = None def init_tcpros_server(port=0): """ starts the TCPROS server socket for inbound connections @param port: listen on the provided port. If the port number is 0, the port will be chosen randomly @type port: int """ global _tcpros_server if _tcpros_server is None: _tcpros_server = TCPROSServer(port=port) rospy.core.add_shutdown_hook(_tcpros_server.shutdown) return _tcpros_server def start_tcpros_server(): """ start the TCPROS server if it has not started already """ if _tcpros_server is None: init_tcpros_server() return _tcpros_server.start_server() # provide an accessor of this so that the TCPROS Server is entirely hidden from upper layers def get_tcpros_server_address(): """ get the address of the tcpros server. @raise Exception: if tcpros server has not been started or created """ return _tcpros_server.get_address() def _error_connection_handler(sock, client_addr, header): """ utility handler that does nothing more than provide a rejection header @param sock: socket connection @type sock: socket.socket @param client_addr: client address @type client_addr: str @param header: request header @type header: dict """ return {'error': "unhandled connection"} class TCPROSServer(object): """ ROS Protocol handler for TCPROS. Accepts both TCPROS topic connections as well as ROS service connections over TCP. TCP server socket is run once start_server() is called -- this is implicitly called during init_publisher(). """ def __init__(self, port=0): """ Constructur @param port: port number to bind to (default 0/any) @type port: int """ self.port = port self.tcp_ros_server = None #: server for receiving tcp conn self.lock = threading.Lock() # should be set to fn(sock, client_addr, header) for topic connections self.topic_connection_handler = _error_connection_handler # should be set to fn(sock, client_addr, header) for service connections self.service_connection_handler = _error_connection_handler def start_server(self): """ Starts the TCP socket server if one is not already running """ if self.tcp_ros_server: return with self.lock: try: if not self.tcp_ros_server: self.tcp_ros_server = TCPServer(self._tcp_server_callback, self.port) self.tcp_ros_server.start() except Exception as e: self.tcp_ros_server = None logerr("unable to start TCPROS server: %s\n%s"%(e, traceback.format_exc())) return 0, "unable to establish TCPROS server: %s"%e, [] def get_address(self): """ @return: address and port of TCP server socket for accepting inbound connections @rtype: str, int """ if self.tcp_ros_server is not None: return self.tcp_ros_server.get_full_addr() return None, None def shutdown(self, reason=''): """stops the TCP/IP server responsible for receiving inbound connections""" if self.tcp_ros_server: self.tcp_ros_server.shutdown() def _tcp_server_callback(self, sock, client_addr): """ TCPServer callback: detects incoming topic or service connection and passes connection accordingly @param sock: socket connection @type sock: socket.socket @param client_addr: client address @type client_addr: (str, int) @raise TransportInitError: If transport cannot be succesfully initialized """ #TODOXXX:rewrite this logic so it is possible to create TCPROSTransport object first, set its protocol, #and then use that to do the writing try: buff_size = 4096 # size of read buffer if python3 == 0: #initialize read_ros_handshake_header with BytesIO for Python 3 (instead of bytesarray()) header = read_ros_handshake_header(sock, StringIO(), buff_size) else: header = read_ros_handshake_header(sock, BytesIO(), buff_size) if 'topic' in header: err_msg = self.topic_connection_handler(sock, client_addr, header) elif 'service' in header: err_msg = self.service_connection_handler(sock, client_addr, header) else: err_msg = 'no topic or service name detected' if err_msg: # shutdown race condition: nodes that come up and down # quickly can receive connections during teardown. # We use is_shutdown_requested() because we can get # into bad connection states during client shutdown # hooks. if not rospy.core.is_shutdown_requested(): write_ros_handshake_header(sock, {'error' : err_msg}) raise TransportInitError("Could not process inbound connection: "+err_msg+str(header)) else: write_ros_handshake_header(sock, {'error' : 'node shutting down'}) return except rospy.exceptions.TransportInitError as e: logwarn(str(e)) if sock is not None: sock.close() except Exception as e: # collect stack trace separately in local log file if not rospy.core.is_shutdown_requested(): logwarn("Inbound TCP/IP connection failed: %s", e) rospyerr("Inbound TCP/IP connection failed:\n%s", traceback.format_exc()) if sock is not None: sock.close() class TCPROSTransportProtocol(object): """ Abstraction of TCPROS connections. Implementations Services/Publishers/Subscribers must implement this protocol, which defines how messages are deserialized from an inbound connection (read_messages()) as well as which fields to send when creating a new connection (get_header_fields()). """ def __init__(self, resolved_name, recv_data_class, queue_size=None, buff_size=DEFAULT_BUFF_SIZE): """ ctor @param resolved_name: resolved service or topic name @type resolved_name: str @param recv_data_class: message class for deserializing inbound messages @type recv_data_class: Class @param queue_size: maximum number of inbound messages to maintain @type queue_size: int @param buff_size: receive buffer size (in bytes) for reading from the connection. @type buff_size: int """ if recv_data_class and not issubclass(recv_data_class, Message) and not issubclass(recv_data_class, google.protobuf.message.Message): raise TransportInitError("Unable to initialize transport: data class is not a message data class") self.resolved_name = resolved_name self.recv_data_class = recv_data_class self.queue_size = queue_size self.buff_size = buff_size self.direction = BIDIRECTIONAL def read_messages(self, b, msg_queue, sock): """ @param b StringIO: read buffer @param msg_queue [Message]: queue of deserialized messages @type msg_queue: [Message] @param sock socket: protocol can optionally read more data from the socket, but in most cases the required data will already be in b """ # default implementation deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size) def get_header_fields(self): """ Header fields that should be sent over the connection. The header fields are protocol specific (i.e. service vs. topic, publisher vs. subscriber). @return: {str : str}: header fields to send over connection @rtype: dict """ return {} # TODO: this still isn't as clean and seamless as I want it to # be. This code came from the merger of publisher, subscriber, and # service code into a common TCPROS transport class. The transport is # customized by a 'protocol' class, which is how the different # pub/sub/service behaviors are achieved. More behavior needs to be # transferred from the transport class into the protocol class, # e.g. deserialization as the state each maintains is somewhat # duplicative. I would also come up with a better name than # protocol. class TCPROSTransport(Transport): """ Generic implementation of TCPROS exchange routines for both topics and services """ transport_type = 'TCPROS' def __init__(self, protocol, name, header=None): """ ctor @param name str: identifier @param protocol TCPROSTransportProtocol protocol implementation @param header dict: (optional) handshake header if transport handshake header was already read off of transport. @raise TransportInitError if transport cannot be initialized according to arguments """ super(TCPROSTransport, self).__init__(protocol.direction, name=name) if not name: raise TransportInitError("Unable to initialize transport: name is not set") self.protocol = protocol self.socket = None self.endpoint_id = 'unknown' self.callerid_pub = 'unknown' self.dest_address = None # for reconnection if python3 == 0: # Python 2.x self.read_buff = StringIO() self.write_buff = StringIO() else: # Python 3.x self.read_buff = BytesIO() self.write_buff = BytesIO() #self.write_buff = StringIO() self.header = header # #1852 have to hold onto latched messages on subscriber side self.is_latched = False self.latch = None # save the fileno separately so we can garbage collect the # socket but still unregister will poll objects self._fileno = None # these fields are actually set by the remote # publisher/service. they are set for tools that connect # without knowing the actual field name self.md5sum = None self.type = None # Endpoint Details (IP, Port) self.local_endpoint = (None, None) self.remote_endpoint = (None, None) def get_transport_info(self): """ Get detailed connection information. Similar to getTransportInfo() in 'libros/transport/transport_tcp.cpp' e.g. TCPROS connection on port 41374 to [127.0.0.1:40623 on socket 6] """ return "%s connection on port %s to [%s:%s on socket %s]" % (self.transport_type, self.local_endpoint[1], self.remote_endpoint[0], self.remote_endpoint[1], self._fileno) def fileno(self): """ Get descriptor for select """ return self._fileno def set_endpoint_id(self, endpoint_id): """ Set the endpoint_id of this transport. Allows the endpoint_id to be set before the socket is initialized. """ self.endpoint_id = endpoint_id def set_socket(self, sock, endpoint_id): """ Set the socket for this transport @param sock: socket @type sock: socket.socket @param endpoint_id: identifier for connection endpoint @type endpoint_id: str @raise TransportInitError: if socket has already been set """ if self.socket is not None: raise TransportInitError("socket already initialized") self.socket = sock self.endpoint_id = endpoint_id self._fileno = sock.fileno() self.local_endpoint = self.socket.getsockname() def connect(self, dest_addr, dest_port, endpoint_id, timeout=None): """ Establish TCP connection to the specified address/port. connect() always calls L{write_header()} and L{read_header()} after the connection is made @param dest_addr: destination IP address @type dest_addr: str @param dest_port: destination port @type dest_port: int @param endpoint_id: string identifier for connection (for statistics) @type endpoint_id: str @param timeout: (optional keyword) timeout in seconds @type timeout: float @raise TransportInitError: if unable to create connection """ # first make sure that if ROS_HOSTNAME=localhost, we will not attempt # to connect to anything other than localhost if ("ROS_HOSTNAME" in os.environ) and (os.environ["ROS_HOSTNAME"] == "localhost"): if not rosgraph.network.is_local_address(dest_addr): msg = "attempted to connect to non-local host [%s] from a node launched with ROS_HOSTNAME=localhost" % (dest_addr) logwarn(msg) self.close() raise TransportInitError(msg) # bubble up # now we can proceed with trying to connect. try: self.endpoint_id = endpoint_id self.dest_address = (dest_addr, dest_port) if rosgraph.network.use_ipv6(): s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if _is_use_tcp_keepalive(): # OSX (among others) does not define these options if hasattr(socket, 'TCP_KEEPCNT') and \ hasattr(socket, 'TCP_KEEPIDLE') and \ hasattr(socket, 'TCP_KEEPINTVL'): # turn on KEEPALIVE s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # - # keepalive failures before actual connection failure s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 9) # - timeout before starting KEEPALIVE process s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60) # - interval to send KEEPALIVE after IDLE timeout s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10) if timeout is not None: s.settimeout(timeout) self.socket = s logdebug('connecting to ' + str(dest_addr)+ ' ' + str(dest_port)) self.socket.connect((dest_addr, dest_port)) self.write_header() self.read_header() self.local_endpoint = self.socket.getsockname() self.remote_endpoint = (dest_addr, dest_port) except TransportInitError as tie: rospyerr("Unable to initiate TCP/IP socket to %s:%s (%s): %s"%(dest_addr, dest_port, endpoint_id, traceback.format_exc())) raise except Exception as e: #logerr("Unknown error initiating TCP/IP socket to %s:%s (%s): %s"%(dest_addr, dest_port, endpoint_id, str(e))) rospywarn("Unknown error initiating TCP/IP socket to %s:%s (%s): %s"%(dest_addr, dest_port, endpoint_id, traceback.format_exc())) # FATAL: no reconnection as error is unknown self.close() raise TransportInitError(str(e)) #re-raise i/o error def _validate_header(self, header): """ Validate header and initialize fields accordingly @param header: header fields from publisher @type header: dict @raise TransportInitError: if header fails to validate """ self.header = header if 'error' in header: raise TransportInitError("remote error reported: %s"%header['error']) for required in ['md5sum', 'type']: if not required in header: raise TransportInitError("header missing required field [%s]"%required) self.type = header['type'] self.md5sum = header['md5sum'] if 'callerid' in header: self.callerid_pub = header['callerid'] if header.get('latching', '0') == '1': self.is_latched = True def write_header(self): """Writes the TCPROS header to the active connection.""" # socket may still be getting spun up, so wait for it to be writable sock = self.socket protocol = self.protocol # race condition on close, better fix is to pass these in, # functional style, but right now trying to cause minimal # perturbance to codebase. if sock is None or protocol is None: return fileno = sock.fileno() ready = None while not ready: _, ready, _ = select.select([], [fileno], []) logger.debug("[%s]: writing header", self.name) sock.setblocking(1) self.stat_bytes += write_ros_handshake_header(sock, protocol.get_header_fields()) def read_header(self): """ Read TCPROS header from active socket @raise TransportInitError if header fails to validate """ sock = self.socket if sock is None: return sock.setblocking(1) # TODO: add bytes received to self.stat_bytes self._validate_header(read_ros_handshake_header(sock, self.read_buff, self.protocol.buff_size)) def send_message(self, msg, seq): """ Convenience routine for services to send a message across a particular connection. NOTE: write_data is much more efficient if same message is being sent to multiple connections. Not threadsafe. @param msg: message to send @type msg: Msg @param seq: sequence number for message @type seq: int @raise TransportException: if error occurred sending message """ # this will call write_data(), so no need to keep track of stats serialize_message(self.write_buff, seq, msg) self.write_data(self.write_buff.getvalue()) self.write_buff.truncate(0) def write_data(self, data): """ Write raw data to transport @raise TransportInitialiationError: could not be initialized @raise TransportTerminated: no longer open for publishing """ if not self.socket: raise TransportInitError("TCPROS transport was not successfully initialized") if self.done: raise TransportTerminated("connection closed") try: #TODO: get rid of sendalls and replace with async-style publishing self.socket.sendall(data) self.stat_bytes += len(data) self.stat_num_msg += 1 except IOError as ioe: #for now, just document common errno's in code (errno, msg) = ioe.args if errno == 32: #broken pipe logdebug("ERROR: Broken Pipe") self.close() raise TransportTerminated(str(errno)+msg) raise #re-raise except socket.error as se: #for now, just document common errno's in code (errno, msg) = se.args if errno == 32: #broken pipe logdebug("[%s]: Closing connection [%s] due to broken pipe", self.name, self.endpoint_id) self.close() raise TransportTerminated(msg) elif errno == 104: #connection reset by peer logdebug("[%s]: Peer [%s] has closed connection", self.name, self.endpoint_id) self.close() raise TransportTerminated(msg) else: rospydebug("unknown socket error writing data: %s",traceback.format_exc()) logdebug("[%s]: closing connection [%s] due to unknown socket error: %s", self.name, self.endpoint_id, msg) self.close() raise TransportTerminated(str(errno)+' '+msg) return True def receive_once(self): """ block until messages are read off of socket @return: list of newly received messages @rtype: [Msg] @raise TransportException: if unable to receive message due to error """ sock = self.socket if sock is None: raise TransportException("connection not initialized") b = self.read_buff msg_queue = [] p = self.protocol try: sock.setblocking(1) while not msg_queue and not self.done and not is_shutdown(): if b.tell() >= 4: p.read_messages(b, msg_queue, sock) if not msg_queue: self.stat_bytes += recv_buff(sock, b, p.buff_size) self.stat_num_msg += len(msg_queue) #STATS # set the _connection_header field for m in msg_queue: setattr(m.__class__, '_connection_header', self.header) # #1852: keep track of last latched message if self.is_latched and msg_queue: self.latch = msg_queue[-1] return msg_queue except DeserializationError as e: rospyerr(traceback.format_exc()) raise TransportException("receive_once[%s]: DeserializationError %s"%(self.name, str(e))) except TransportTerminated as e: raise #reraise except ServiceException as e: raise except Exception as e: rospyerr(traceback.format_exc()) raise TransportException("receive_once[%s]: unexpected error %s"%(self.name, str(e))) return retval def _reconnect(self): # This reconnection logic is very hacky right now. I need to # rewrite the I/O core so that this is handled more centrally. if self.dest_address is None: raise ROSInitException("internal error with reconnection state: address not stored") interval = 0.5 # seconds while self.socket is None and not self.done and not rospy.is_shutdown(): try: # set a timeout so that we can continue polling for # exit. 30. is a bit high, but I'm concerned about # embedded platforms. To do this properly, we'd have # to move to non-blocking routines. self.connect(self.dest_address[0], self.dest_address[1], self.endpoint_id, timeout=30.) except TransportInitError: self.socket = None if self.socket is None: # exponential backoff interval = interval * 2 time.sleep(interval) def receive_loop(self, msgs_callback): """ Receive messages until shutdown @param msgs_callback: callback to invoke for new messages received @type msgs_callback: fn([msg]) """ # - use assert here as this would be an internal error, aka bug logger.debug("receive_loop for [%s]", self.name) try: while not self.done and not is_shutdown(): try: if self.socket is not None: msgs = self.receive_once() if not self.done and not is_shutdown(): msgs_callback(msgs, self) else: self._reconnect() except TransportException as e: # set socket to None so we reconnect try: if self.socket is not None: try: self.socket.shutdown() except: pass finally: self.socket.close() except: pass self.socket = None except DeserializationError as e: #TODO: how should we handle reconnect in this case? logerr("[%s] error deserializing incoming request: %s"%self.name, str(e)) rospyerr("[%s] error deserializing incoming request: %s"%self.name, traceback.format_exc()) except: # in many cases this will be a normal hangup, but log internally try: #1467 sometimes we get exceptions due to #interpreter shutdown, so blanket ignore those if #the reporting fails rospydebug("exception in receive loop for [%s], may be normal. Exception is %s",self.name, traceback.format_exc()) except: pass rospydebug("receive_loop[%s]: done condition met, exited loop"%self.name) finally: if not self.done: self.close() def close(self): """close i/o and release resources""" if not self.done: try: if self.socket is not None: try: self.socket.shutdown(socket.SHUT_RDWR) except: pass finally: self.socket.close() finally: self.socket = self.read_buff = self.write_buff = self.protocol = None super(TCPROSTransport, self).close()
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/init.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """ Internal use: rospy initialization. This is mainly routines for initializing the master or slave based on the OS environment. """ import os import sys import logging import time import traceback import rosgraph import rosgraph.roslogging import rosgraph.xmlrpc from ..names import _set_caller_id from ..core import is_shutdown, signal_shutdown, rospyerr from .tcpros import init_tcpros from rospy.impl.masterslave import ROSHandler from rospy.impl.registration import set_node_handler, set_broadcast_manager, get_broadcast_manager from rospy.impl.broadcast_manager import Singleton, BroadcastManager DEFAULT_NODE_PORT = 0 #bind to any open port DEFAULT_MASTER_PORT=11311 #default port for master's to bind to DEFAULT_MASTER_URI = 'http://localhost:%s/'%DEFAULT_MASTER_PORT ################################################### # rospy module lower-level initialization def _node_run_error(e): """ If XML-RPC errors out of the run() method, this handler is invoked """ rospyerr(traceback.format_exc()) signal_shutdown('error in XML-RPC server: %s'%(e)) 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) set_node_handler(handler) set_broadcast_manager(BroadcastManager()) get_broadcast_manager().updateHandler() 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 class RosStreamHandler(rosgraph.roslogging.RosStreamHandler): def __init__(self, colorize=True): super(RosStreamHandler, self).__init__(colorize)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy
apollo_public_repos/apollo-platform/ros/ros_comm/rospy/src/rospy/impl/rosout.py
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Revision $Id$ """Internal use: support for /rosout logging in rospy""" import logging import sys import traceback import rospy.names from rospy.core import get_caller_id from rospy.exceptions import ROSException from rospy.topics import Publisher, Subscriber from rospy.rostime import Time from rospy.impl.registration import get_topic_manager #Log message for rosout from rosgraph_msgs.msg import Log _ROSOUT = '/rosout' _rosout_pub = None _rospy_to_logging_levels = { Log.DEBUG: logging.DEBUG, Log.INFO: logging.INFO, Log.WARN: logging.WARNING, Log.ERROR: logging.ERROR, Log.FATAL: logging.CRITICAL, } def init_rosout(): logger = logging.getLogger("rospy.rosout") try: global _rosout_pub if _rosout_pub is None: logger.info("initializing %s core topic"%_ROSOUT) _rosout_pub = Publisher(_ROSOUT, Log, latch=True, queue_size=100) logger.info("connected to core topic %s"%_ROSOUT) return True except Exception as e: logger.error("Unable to initialize %s: %s\n%s", _ROSOUT, e, traceback.format_exc()) return False _in_rosout = False ## log an error to the /rosout topic def _rosout(level, msg, fname, line, func): global _in_rosout try: if _rosout_pub is not None: # protect against infinite recursion if not _in_rosout: try: _in_rosout = True msg = str(msg) topics = get_topic_manager().get_topics() l = Log(level=level, name=str(rospy.names.get_caller_id()), msg=str(msg), topics=topics, file=fname, line=line, function=func) l.header.stamp = Time.now() _rosout_pub.publish(l) finally: _in_rosout = False except Exception as e: #traceback.print_exc() # don't use logerr in this case as that is recursive here logger = logging.getLogger("rospy.rosout") logger.error("Unable to report rosout: %s\n%s", e, traceback.format_exc()) return False _logging_to_rospy_levels = { logging.DEBUG: Log.DEBUG, logging.INFO: Log.INFO, logging.WARNING: Log.WARN, logging.ERROR: Log.ERROR, logging.CRITICAL: Log.FATAL, } class RosOutHandler(logging.Handler): def emit(self, record): _rosout(_logging_to_rospy_levels[record.levelno], record.getMessage(), record.filename, record.lineno, record.funcName) ## Load loggers for publishing to /rosout ## @param level int: Log level. Loggers >= level will be loaded. def load_rosout_handlers(level): logger = logging.getLogger('rosout') logger.addHandler(RosOutHandler()) if level != None: logger.setLevel(_rospy_to_logging_levels[level])
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(roslz4) if(NOT WIN32) set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra") endif() find_package(catkin REQUIRED) find_path(lz4_INCLUDE_DIRS NAMES lz4.h) if (NOT lz4_INCLUDE_DIRS) message(FATAL_ERROR "lz4 includes not found") endif() find_library(lz4_LIBRARIES NAMES lz4) if (NOT lz4_LIBRARIES) message(FATAL_ERROR "lz4 library not found") endif() catkin_python_setup() catkin_package( INCLUDE_DIRS include LIBRARIES roslz4 DEPENDS lz4) include_directories(include ${lz4_INCLUDE_DIRS} ${catkin_INCLUDE_DIRS}) add_library(roslz4 src/lz4s.c src/xxhash.c) set_source_files_properties( src/lz4s.c PROPERTIES COMPILE_FLAGS "-Wno-sign-compare") target_link_libraries(roslz4 ${lz4_LIBRARIES} ${catkin_LIBRARIES}) if(NOT ANDROID) # Python bindings set(Python_ADDITIONAL_VERSIONS "${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}") find_package(PythonLibs "${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}" REQUIRED) include_directories(${PYTHON_INCLUDE_PATH}) add_library(roslz4_py src/_roslz4module.c) set_source_files_properties( src/_roslz4module.c PROPERTIES COMPILE_FLAGS "-Wno-missing-field-initializers -Wno-unused-variable") set_target_properties( roslz4_py PROPERTIES OUTPUT_NAME roslz4 PREFIX "_" SUFFIX ".so" LIBRARY_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/${PYTHON_INSTALL_DIR}/roslz4) target_link_libraries(roslz4_py roslz4 ${catkin_LIBRARIES} ${PYTHON_LIBRARIES}) endif() install(TARGETS roslz4 ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) if(NOT ANDROID) install(TARGETS roslz4_py LIBRARY DESTINATION ${CATKIN_PACKAGE_PYTHON_DESTINATION}) endif() install(DIRECTORY include/${PROJECT_NAME} DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.h" ) # Testing if (CATKIN_ENABLE_TESTING) catkin_add_gtest(test_roslz4 test/roslz4_test.cpp) if (TARGET test_roslz4) target_link_libraries(test_roslz4 roslz4 ${catkin_LIBRARIES}) endif() endif()
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/package.xml
<?xml version="1.0"?> <package> <name>roslz4</name> <version>1.11.21</version> <description> A Python and C++ implementation of the LZ4 streaming format. Large data streams are split into blocks which are compressed using the very fast LZ4 compression algorithm. </description> <maintainer email="bcharrow@seas.upenn.edu">Ben Charrow</maintainer> <license>BSD</license> <author email="bcharrow@seas.upenn.edu">Ben Charrow</author> <buildtool_depend>catkin</buildtool_depend> <build_depend>lz4</build_depend> <run_depend>lz4</run_depend> <test_depend>rosunit</test_depend> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/setup.py
#!/usr/bin/env python from distutils.core import setup, Extension from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['roslz4'], package_dir={'': 'src'}, requires=[], ) setup(**d)
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/roslz4/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-roslz4-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package roslz4 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- * use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_) 1.11.18 (2016-03-17) -------------------- * fix compiler warnings 1.11.17 (2016-03-11) -------------------- 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- * fix import of compiled library with Python 3.x (`#563 <https://github.com/ros/ros_comm/pull/563>`_) 1.11.10 (2014-12-22) -------------------- * disable lz4 Python bindings on Android (`#521 <https://github.com/ros/ros_comm/pull/521>`_) 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- * fix finding specific version of PythonLibs with CMake 3 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- * fix symbol problem on OSX (`#405 <https://github.com/ros/ros_comm/issues/405>`_) * fix return value in the Python module (`#406 <https://github.com/ros/ros_comm/issues/406>`_) 1.11.1 (2014-05-07) ------------------- * initial release
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/test/roslz4_test.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Ben Charrow * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include <gtest/gtest.h> #include <roslz4/lz4s.h> class CompressATest :public testing::Test { protected: void SetUp() { for (size_t i = 0; i < sizeof(input); ++i) { input[i] = 'a'; } for (size_t i = 0; i < sizeof(output); ++i) { output[i] = 0; } for (size_t i = 0; i < sizeof(other); ++i) { other[i] = 0; } } char input[1024]; char output[1048]; char other[1024]; }; TEST_F(CompressATest, Stream) { // Compression roslz4_stream stream; int ret; ret = roslz4_compressStart(&stream, 4); ASSERT_EQ(ROSLZ4_OK, ret); stream.input_left = sizeof(input); stream.input_next = input; stream.output_left = sizeof(output); stream.output_next = output; int counter; for (counter = 0; ret == ROSLZ4_OK; ++counter) { ret = roslz4_compress(&stream, ROSLZ4_FINISH); } ASSERT_EQ(ROSLZ4_STREAM_END, ret); int output_size = stream.output_next - output; roslz4_compressEnd(&stream); // Decompression stream.input_left = output_size; stream.input_next = output; stream.output_left = sizeof(other); stream.output_next = other; ret = roslz4_decompressStart(&stream); ASSERT_EQ(ROSLZ4_OK, ret); ret = roslz4_decompress(&stream); ASSERT_EQ(ROSLZ4_STREAM_END, ret); roslz4_decompressEnd(&stream); for (size_t i = 0; i < sizeof(other); ++i) { ASSERT_EQ(input[i], other[i]) << "Original and uncompressed data differ at index " << i; } } TEST_F(CompressATest, Oneshot) { // Compression unsigned int comp_size = sizeof(output); int ret = roslz4_buffToBuffCompress(input, sizeof(input), output, &comp_size, 4); ASSERT_EQ(ROSLZ4_OK, ret); // Decompression unsigned int decomp_size = sizeof(other); ret = roslz4_buffToBuffDecompress(output, comp_size, other, &decomp_size); ASSERT_EQ(ROSLZ4_OK, ret); ASSERT_EQ(sizeof(input), decomp_size); for (size_t i = 0; i < sizeof(other); ++i) { ASSERT_EQ(input[i], other[i]) << "Original and uncompressed data differ at index " << i; } } TEST_F(CompressATest, OneshotDataCorruption) { unsigned int comp_size = sizeof(output); int ret = roslz4_buffToBuffCompress(input, sizeof(input), output, &comp_size, 4); ASSERT_EQ(ROSLZ4_OK, ret); output[20] += 1; unsigned int decomp_size = sizeof(other); ret = roslz4_buffToBuffDecompress(output, comp_size, other, &decomp_size); ASSERT_EQ(ROSLZ4_DATA_ERROR, ret); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/include
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/include/roslz4/lz4s.h
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Ben Charrow * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #ifndef ROSLZ4_LZ4S_H #define ROSLZ4_LZ4S_H #include <lz4.h> #ifdef __cplusplus extern "C" { #endif // Return codes const int ROSLZ4_MEMORY_ERROR = -5; const int ROSLZ4_PARAM_ERROR = -4; const int ROSLZ4_DATA_ERROR = -3; const int ROSLZ4_OUTPUT_SMALL = -2; const int ROSLZ4_ERROR = -1; const int ROSLZ4_OK = 0; const int ROSLZ4_STREAM_END = 2; // Actions const int ROSLZ4_RUN = 0; const int ROSLZ4_FINISH = 1; typedef struct { char *input_next; int input_left; char *output_next; int output_left; int total_in; int total_out; int block_size_id; // Internal use void *state; } roslz4_stream; // Low level functions int roslz4_blockSizeFromIndex(int block_id); int roslz4_compressStart(roslz4_stream *stream, int block_size_id); int roslz4_compress(roslz4_stream *stream, int action); void roslz4_compressEnd(roslz4_stream *stream); int roslz4_decompressStart(roslz4_stream *stream); int roslz4_decompress(roslz4_stream *stream); void roslz4_decompressEnd(roslz4_stream *str); // Oneshot compression / decompression int roslz4_buffToBuffCompress(char *input, unsigned int input_size, char *output, unsigned int *output_size, int block_size_id); int roslz4_buffToBuffDecompress(char *input, unsigned int input_size, char *output, unsigned int *output_size); #ifdef __cplusplus } #endif #endif // ROSLZ4_LZ4S_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/src/_roslz4module.c
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Ben Charrow * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include "Python.h" #include "roslz4/lz4s.h" struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct module_state _state; #endif /* Taken from Python's _bz2module.c */ static int grow_buffer(PyObject **buf) { /* Expand the buffer by an amount proportional to the current size, giving us amortized linear-time behavior. Use a less-than-double growth factor to avoid excessive allocation. */ size_t size = PyBytes_GET_SIZE(*buf); size_t new_size = size + (size >> 3) + 6; if (new_size > size) { return _PyBytes_Resize(buf, new_size); } else { /* overflow */ PyErr_SetString(PyExc_OverflowError, "Unable to allocate buffer - output too large"); return -1; } } /*============================== LZ4Compressor ==============================*/ typedef struct { PyObject_HEAD roslz4_stream stream; } LZ4Compressor; static void LZ4Compressor_dealloc(LZ4Compressor *self) { roslz4_compressEnd(&self->stream); Py_TYPE(self)->tp_free((PyObject*)self); } static int LZ4Compressor_init(LZ4Compressor *self, PyObject *args, PyObject *kwds) { (void)kwds; if (!PyArg_ParseTuple(args, ":__init__")) { return -1; } int ret = roslz4_compressStart(&self->stream, 6); if (ret != ROSLZ4_OK) { PyErr_SetString(PyExc_RuntimeError, "error initializing roslz4 stream"); return -1; } return 0; } static PyObject * compress_impl(LZ4Compressor *self, Py_buffer *input, PyObject *output) { /* Allocate output string */ int initial_size = roslz4_blockSizeFromIndex(self->stream.block_size_id) + 64; output = PyBytes_FromStringAndSize(NULL, initial_size); if (!output) { if (input != NULL) { PyBuffer_Release(input); } return NULL; } /* Setup stream */ int action; if (input != NULL) { action = ROSLZ4_RUN; self->stream.input_next = input->buf; self->stream.input_left = input->len; } else { action = ROSLZ4_FINISH; self->stream.input_next = NULL; self->stream.input_left = 0; } self->stream.output_next = PyBytes_AS_STRING(output); self->stream.output_left = PyBytes_GET_SIZE(output); /* Compress data */ int status; int output_written = 0; while ((action == ROSLZ4_FINISH) || (action == ROSLZ4_RUN && self->stream.input_left > 0)) { int out_start = self->stream.total_out; status = roslz4_compress(&self->stream, action); output_written += self->stream.total_out - out_start; if (status == ROSLZ4_OK) { continue; } else if (status == ROSLZ4_STREAM_END) { break; } else if (status == ROSLZ4_OUTPUT_SMALL) { if (grow_buffer(&output) < 0) { goto error; } self->stream.output_next = PyBytes_AS_STRING(output) + output_written; self->stream.output_left = PyBytes_GET_SIZE(output) - output_written; } else if (status == ROSLZ4_PARAM_ERROR) { PyErr_SetString(PyExc_IOError, "bad block size parameter"); goto error; } else if (status == ROSLZ4_ERROR) { PyErr_SetString(PyExc_IOError, "error compressing"); goto error; } else { PyErr_Format(PyExc_RuntimeError, "unhandled return code %i", status); goto error; } } /* Shrink return buffer */ if (output_written != PyBytes_GET_SIZE(output)) { _PyBytes_Resize(&output, output_written); } if (input != NULL) { PyBuffer_Release(input); } return output; error: if (input != NULL) { PyBuffer_Release(input); } Py_XDECREF(output); return NULL; } static PyObject * LZ4Compressor_compress(LZ4Compressor *self, PyObject *args) { Py_buffer input; PyObject *output = NULL; /* TODO: Keyword argument */ if (!PyArg_ParseTuple(args, "s*:compress", &input)) { return NULL; } return compress_impl(self, &input, output); } static PyObject * LZ4Compressor_flush(LZ4Compressor *self, PyObject *args) { PyObject *output = NULL; if (!PyArg_ParseTuple(args, ":flush")) { return NULL; } return compress_impl(self, NULL, output); } static PyMethodDef LZ4Compressor_methods[] = { {"compress", (PyCFunction)LZ4Compressor_compress, METH_VARARGS, "method doc"}, {"flush", (PyCFunction)LZ4Compressor_flush, METH_VARARGS, "method doc"}, {NULL} /* Sentinel */ }; static PyTypeObject LZ4Compressor_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_roslz4.LZ4Compressor", /* tp_name */ sizeof(LZ4Compressor), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)LZ4Compressor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "LZ4Compressor objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ LZ4Compressor_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)LZ4Compressor_init /* tp_init */ }; /*============================= LZ4Decompressor =============================*/ typedef struct { PyObject_HEAD roslz4_stream stream; } LZ4Decompressor; static void LZ4Decompressor_dealloc(LZ4Decompressor *self) { roslz4_decompressEnd(&self->stream); Py_TYPE(self)->tp_free((PyObject*)self); } static int LZ4Decompressor_init(LZ4Decompressor *self, PyObject *args, PyObject *kwds) { (void)kwds; if (!PyArg_ParseTuple(args, ":__init__")) { return -1; } int ret = roslz4_decompressStart(&self->stream); if (ret != ROSLZ4_OK) { PyErr_SetString(PyExc_RuntimeError, "error initializing roslz4 stream"); return -1; } return 0; } static PyObject * LZ4Decompressor_decompress(LZ4Decompressor *self, PyObject *args) { Py_buffer input; PyObject *output = NULL; /* TODO: Keyword argument */ if (!PyArg_ParseTuple(args, "s*:decompress", &input)) { return NULL; } /* Allocate 1 output block. If header not read, use compression block size */ int block_size; if (self->stream.block_size_id == -1 ) { block_size = roslz4_blockSizeFromIndex(6); } else { block_size = roslz4_blockSizeFromIndex(self->stream.block_size_id); } output = PyBytes_FromStringAndSize(NULL, block_size); if (!output) { PyBuffer_Release(&input); return NULL; } /* Setup stream */ self->stream.input_next = input.buf; self->stream.input_left = input.len; self->stream.output_next = PyBytes_AS_STRING(output); self->stream.output_left = PyBytes_GET_SIZE(output); int output_written = 0; while (self->stream.input_left > 0) { int out_start = self->stream.total_out; int status = roslz4_decompress(&self->stream); output_written += self->stream.total_out - out_start; if (status == ROSLZ4_OK) { continue; } else if (status == ROSLZ4_STREAM_END) { break; } else if (status == ROSLZ4_OUTPUT_SMALL) { if (grow_buffer(&output) < 0) { goto error; } self->stream.output_next = PyBytes_AS_STRING(output) + output_written; self->stream.output_left = PyBytes_GET_SIZE(output) - output_written; } else if (status == ROSLZ4_ERROR) { PyErr_SetString(PyExc_IOError, "error decompressing"); goto error; } else if (status == ROSLZ4_DATA_ERROR) { PyErr_SetString(PyExc_IOError, "malformed data to decompress"); goto error; } else { PyErr_Format(PyExc_RuntimeError, "unhandled return code %i", status); goto error; } } if (output_written != PyBytes_GET_SIZE(output)) { _PyBytes_Resize(&output, output_written); } PyBuffer_Release(&input); return output; error: PyBuffer_Release(&input); Py_XDECREF(output); return NULL; } static PyMethodDef LZ4Decompressor_methods[] = { {"decompress", (PyCFunction)LZ4Decompressor_decompress, METH_VARARGS, "method doc"}, {NULL} /* Sentinel */ }; static PyTypeObject LZ4Decompressor_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_roslz4.LZ4Decompressor", /* tp_name */ sizeof(LZ4Decompressor), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)LZ4Decompressor_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "LZ4Decompressor objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ LZ4Decompressor_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)LZ4Decompressor_init /* tp_init */ }; /*========================== Module initialization ==========================*/ #if PY_MAJOR_VERSION >= 3 static int roslz4_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int roslz4_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_roslz4", NULL, sizeof(struct module_state), NULL, NULL, roslz4_traverse, roslz4_clear, NULL }; #define INITERROR return NULL PyObject * PyInit__roslz4(void) #else #define INITERROR return void init_roslz4(void) #endif { PyObject *m; LZ4Compressor_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&LZ4Compressor_Type) < 0) { INITERROR; } LZ4Decompressor_Type.tp_new = PyType_GenericNew; if (PyType_Ready(&LZ4Decompressor_Type) < 0) { INITERROR; } #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule("_roslz4", NULL); #endif if (m == NULL) { INITERROR; } Py_INCREF(&LZ4Compressor_Type); PyModule_AddObject(m, "LZ4Compressor", (PyObject *)&LZ4Compressor_Type); Py_INCREF(&LZ4Decompressor_Type); PyModule_AddObject(m, "LZ4Decompressor", (PyObject *)&LZ4Decompressor_Type); #if PY_MAJOR_VERSION >= 3 return m; #endif }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/src/xxhash.h
/* xxHash - Fast Hash algorithm Header File Copyright (C) 2012-2014, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - xxHash source repository : http://code.google.com/p/xxhash/ */ /* Notice extracted from xxHash homepage : xxHash is an extremely fast Hash algorithm, running at RAM speed limits. It also successfully passes all tests from the SMHasher suite. Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) Name Speed Q.Score Author xxHash 5.4 GB/s 10 CrapWow 3.2 GB/s 2 Andrew MumurHash 3a 2.7 GB/s 10 Austin Appleby SpookyHash 2.0 GB/s 10 Bob Jenkins SBox 1.4 GB/s 9 Bret Mulvey Lookup3 1.2 GB/s 9 Bob Jenkins SuperFastHash 1.2 GB/s 1 Paul Hsieh CityHash64 1.05 GB/s 10 Pike & Alakuijala FNV 0.55 GB/s 5 Fowler, Noll, Vo CRC32 0.43 GB/s 9 MD5-32 0.33 GB/s 10 Ronald L. Rivest SHA1-32 0.28 GB/s 10 Q.Score is a measure of quality of the hash function. It depends on successfully passing SMHasher test set. 10 is a perfect score. */ #pragma once #if defined (__cplusplus) extern "C" { #endif //**************************** // Type //**************************** typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; //**************************** // Simple Hash Functions //**************************** unsigned int XXH32 (const void* input, int len, unsigned int seed); /* XXH32() : Calculate the 32-bits hash of sequence of length "len" stored at memory address "input". The memory between input & input+len must be valid (allocated and read-accessible). "seed" can be used to alter the result predictably. This function successfully passes all SMHasher tests. Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s Note that "len" is type "int", which means it is limited to 2^31-1. If your data is larger, use the advanced functions below. */ //**************************** // Advanced Hash Functions //**************************** void* XXH32_init (unsigned int seed); XXH_errorcode XXH32_update (void* state, const void* input, int len); unsigned int XXH32_digest (void* state); /* These functions calculate the xxhash of an input provided in several small packets, as opposed to an input provided as a single block. It must be started with : void* XXH32_init() The function returns a pointer which holds the state of calculation. This pointer must be provided as "void* state" parameter for XXH32_update(). XXH32_update() can be called as many times as necessary. The user must provide a valid (allocated) input. The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. Note that "len" is type "int", which means it is limited to 2^31-1. If your data is larger, it is recommended to chunk your data into blocks of size for example 2^30 (1GB) to avoid any "int" overflow issue. Finally, you can end the calculation anytime, by using XXH32_digest(). This function returns the final 32-bits hash. You must provide the same "void* state" parameter created by XXH32_init(). Memory will be freed by XXH32_digest(). */ int XXH32_sizeofState(); XXH_errorcode XXH32_resetState(void* state, unsigned int seed); #define XXH32_SIZEOFSTATE 48 typedef struct { long long ll[(XXH32_SIZEOFSTATE+(sizeof(long long)-1))/sizeof(long long)]; } XXH32_stateSpace_t; /* These functions allow user application to make its own allocation for state. XXH32_sizeofState() is used to know how much space must be allocated for the xxHash 32-bits state. Note that the state must be aligned to access 'long long' fields. Memory must be allocated and referenced by a pointer. This pointer must then be provided as 'state' into XXH32_resetState(), which initializes the state. For static allocation purposes (such as allocation on stack, or freestanding systems without malloc()), use the structure XXH32_stateSpace_t, which will ensure that memory space is large enough and correctly aligned to access 'long long' fields. */ unsigned int XXH32_intermediateDigest (void* state); /* This function does the same as XXH32_digest(), generating a 32-bit hash, but preserve memory context. This way, it becomes possible to generate intermediate hashes, and then continue feeding data with XXH32_update(). To free memory context, use XXH32_digest(), or free(). */ //**************************** // Deprecated function names //**************************** // The following translations are provided to ease code transition // You are encouraged to no longer this function names #define XXH32_feed XXH32_update #define XXH32_result XXH32_digest #define XXH32_getIntermediateResult XXH32_intermediateDigest #if defined (__cplusplus) } #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/src/xxhash.c
/* xxHash - Fast Hash algorithm Copyright (C) 2012-2014, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - xxHash source repository : http://code.google.com/p/xxhash/ */ //************************************** // Tuning parameters //************************************** // Unaligned memory access is automatically enabled for "common" CPU, such as x86. // For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected. // If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance. // You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32). #if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) # define XXH_USE_UNALIGNED_ACCESS 1 #endif // XXH_ACCEPT_NULL_INPUT_POINTER : // If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. // When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. // This option has a very small performance cost (only measurable on small inputs). // By default, this option is disabled. To enable it, uncomment below define : //#define XXH_ACCEPT_NULL_INPUT_POINTER 1 // XXH_FORCE_NATIVE_FORMAT : // By default, xxHash library provides endian-independant Hash values, based on little-endian convention. // Results are therefore identical for little-endian and big-endian CPU. // This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. // Should endian-independance be of no importance for your application, you may set the #define below to 1. // It will improve speed for Big-endian CPU. // This option has no impact on Little_Endian CPU. #define XXH_FORCE_NATIVE_FORMAT 0 //************************************** // Compiler Specific Options //************************************** // Disable some Visual warning messages #ifdef _MSC_VER // Visual Studio # pragma warning(disable : 4127) // disable: C4127: conditional expression is constant #endif #ifdef _MSC_VER // Visual Studio # define FORCE_INLINE static __forceinline #else # ifdef __GNUC__ # define FORCE_INLINE static inline __attribute__((always_inline)) # else # define FORCE_INLINE static inline # endif #endif //************************************** // Includes & Memory related functions //************************************** #include "xxhash.h" // Modify the local functions below should you wish to use some other memory related routines // for malloc(), free() #include <stdlib.h> FORCE_INLINE void* XXH_malloc(size_t s) { return malloc(s); } FORCE_INLINE void XXH_free (void* p) { free(p); } // for memcpy() #include <string.h> FORCE_INLINE void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } //************************************** // Basic Types //************************************** #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99 # include <stdint.h> typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; typedef int32_t S32; typedef uint64_t U64; #else typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; typedef unsigned long long U64; #endif #if defined(__GNUC__) && !defined(XXH_USE_UNALIGNED_ACCESS) # define _PACKED __attribute__ ((packed)) #else # define _PACKED #endif #if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) # ifdef __IBMC__ # pragma pack(1) # else # pragma pack(push, 1) # endif #endif typedef struct _U32_S { U32 v; } _PACKED U32_S; #if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) # pragma pack(pop) #endif #define A32(x) (((U32_S *)(x))->v) //*************************************** // Compiler-specific Functions and Macros //*************************************** #define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) // Note : although _rotl exists for minGW (GCC under windows), performance seems poor #if defined(_MSC_VER) # define XXH_rotl32(x,r) _rotl(x,r) #else # define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) #endif #if defined(_MSC_VER) // Visual Studio # define XXH_swap32 _byteswap_ulong #elif GCC_VERSION >= 403 # define XXH_swap32 __builtin_bswap32 #else static inline U32 XXH_swap32 (U32 x) { return ((x << 24) & 0xff000000 ) | ((x << 8) & 0x00ff0000 ) | ((x >> 8) & 0x0000ff00 ) | ((x >> 24) & 0x000000ff );} #endif //************************************** // Constants //************************************** #define PRIME32_1 2654435761U #define PRIME32_2 2246822519U #define PRIME32_3 3266489917U #define PRIME32_4 668265263U #define PRIME32_5 374761393U //************************************** // Architecture Macros //************************************** typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; #ifndef XXH_CPU_LITTLE_ENDIAN // It is possible to define XXH_CPU_LITTLE_ENDIAN externally, for example using a compiler switch static const int one = 1; # define XXH_CPU_LITTLE_ENDIAN (*(char*)(&one)) #endif //************************************** // Macros //************************************** #define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(!!(c)) }; } // use only *after* variable declarations //**************************** // Memory reads //**************************** typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; FORCE_INLINE U32 XXH_readLE32_align(const U32* ptr, XXH_endianess endian, XXH_alignment align) { if (align==XXH_unaligned) return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr)); else return endian==XXH_littleEndian ? *ptr : XXH_swap32(*ptr); } FORCE_INLINE U32 XXH_readLE32(const U32* ptr, XXH_endianess endian) { return XXH_readLE32_align(ptr, endian, XXH_unaligned); } //**************************** // Simple Hash Functions //**************************** FORCE_INLINE U32 XXH32_endian_align(const void* input, int len, U32 seed, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; U32 h32; #ifdef XXH_ACCEPT_NULL_INPUT_POINTER if (p==NULL) { len=0; p=(const BYTE*)(size_t)16; } #endif if (len>=16) { const BYTE* const limit = bEnd - 16; U32 v1 = seed + PRIME32_1 + PRIME32_2; U32 v2 = seed + PRIME32_2; U32 v3 = seed + 0; U32 v4 = seed - PRIME32_1; do { v1 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4; v2 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4; v3 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4; v4 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4; } while (p<=limit); h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); } else { h32 = seed + PRIME32_5; } h32 += (U32) len; while (p<=bEnd-4) { h32 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_3; h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; p+=4; } while (p<bEnd) { h32 += (*p) * PRIME32_5; h32 = XXH_rotl32(h32, 11) * PRIME32_1 ; p++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } U32 XXH32(const void* input, int len, U32 seed) { #if 0 // Simple version, good for code maintenance, but unfortunately slow for small inputs void* state = XXH32_init(seed); XXH32_update(state, input, len); return XXH32_digest(state); #else XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; # if !defined(XXH_USE_UNALIGNED_ACCESS) if ((((size_t)input) & 3)) // Input is aligned, let's leverage the speed advantage { if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); else return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); } # endif if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); else return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); #endif } //**************************** // Advanced Hash Functions //**************************** struct XXH_state32_t { U64 total_len; U32 seed; U32 v1; U32 v2; U32 v3; U32 v4; int memsize; char memory[16]; }; int XXH32_sizeofState() { XXH_STATIC_ASSERT(XXH32_SIZEOFSTATE >= sizeof(struct XXH_state32_t)); // A compilation error here means XXH32_SIZEOFSTATE is not large enough return sizeof(struct XXH_state32_t); } XXH_errorcode XXH32_resetState(void* state_in, U32 seed) { struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; state->seed = seed; state->v1 = seed + PRIME32_1 + PRIME32_2; state->v2 = seed + PRIME32_2; state->v3 = seed + 0; state->v4 = seed - PRIME32_1; state->total_len = 0; state->memsize = 0; return XXH_OK; } void* XXH32_init (U32 seed) { void* state = XXH_malloc (sizeof(struct XXH_state32_t)); XXH32_resetState(state, seed); return state; } FORCE_INLINE XXH_errorcode XXH32_update_endian (void* state_in, const void* input, int len, XXH_endianess endian) { struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; #ifdef XXH_ACCEPT_NULL_INPUT_POINTER if (input==NULL) return XXH_ERROR; #endif state->total_len += len; if (state->memsize + len < 16) // fill in tmp buffer { XXH_memcpy(state->memory + state->memsize, input, len); state->memsize += len; return XXH_OK; } if (state->memsize) // some data left from previous update { XXH_memcpy(state->memory + state->memsize, input, 16-state->memsize); { const U32* p32 = (const U32*)state->memory; state->v1 += XXH_readLE32(p32, endian) * PRIME32_2; state->v1 = XXH_rotl32(state->v1, 13); state->v1 *= PRIME32_1; p32++; state->v2 += XXH_readLE32(p32, endian) * PRIME32_2; state->v2 = XXH_rotl32(state->v2, 13); state->v2 *= PRIME32_1; p32++; state->v3 += XXH_readLE32(p32, endian) * PRIME32_2; state->v3 = XXH_rotl32(state->v3, 13); state->v3 *= PRIME32_1; p32++; state->v4 += XXH_readLE32(p32, endian) * PRIME32_2; state->v4 = XXH_rotl32(state->v4, 13); state->v4 *= PRIME32_1; p32++; } p += 16-state->memsize; state->memsize = 0; } if (p <= bEnd-16) { const BYTE* const limit = bEnd - 16; U32 v1 = state->v1; U32 v2 = state->v2; U32 v3 = state->v3; U32 v4 = state->v4; do { v1 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4; v2 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4; v3 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4; v4 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4; } while (p<=limit); state->v1 = v1; state->v2 = v2; state->v3 = v3; state->v4 = v4; } if (p < bEnd) { XXH_memcpy(state->memory, p, bEnd-p); state->memsize = (int)(bEnd-p); } return XXH_OK; } XXH_errorcode XXH32_update (void* state_in, const void* input, int len) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_update_endian(state_in, input, len, XXH_littleEndian); else return XXH32_update_endian(state_in, input, len, XXH_bigEndian); } FORCE_INLINE U32 XXH32_intermediateDigest_endian (void* state_in, XXH_endianess endian) { struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; const BYTE * p = (const BYTE*)state->memory; BYTE* bEnd = (BYTE*)state->memory + state->memsize; U32 h32; if (state->total_len >= 16) { h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); } else { h32 = state->seed + PRIME32_5; } h32 += (U32) state->total_len; while (p<=bEnd-4) { h32 += XXH_readLE32((const U32*)p, endian) * PRIME32_3; h32 = XXH_rotl32(h32, 17) * PRIME32_4; p+=4; } while (p<bEnd) { h32 += (*p) * PRIME32_5; h32 = XXH_rotl32(h32, 11) * PRIME32_1; p++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } U32 XXH32_intermediateDigest (void* state_in) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_intermediateDigest_endian(state_in, XXH_littleEndian); else return XXH32_intermediateDigest_endian(state_in, XXH_bigEndian); } U32 XXH32_digest (void* state_in) { U32 h32 = XXH32_intermediateDigest(state_in); XXH_free(state_in); return h32; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/src/lz4s.c
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Ben Charrow * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include "roslz4/lz4s.h" #include "xxhash.h" #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #if 0 #define DEBUG(...) fprintf(stderr, __VA_ARGS__) #else #define DEBUG(...) #endif // magic numbers const uint32_t kMagicNumber = 0x184D2204; const uint32_t kEndOfStream = 0x00000000; // Bitmasks const uint8_t k1Bits = 0x01; const uint8_t k2Bits = 0x03; const uint8_t k3Bits = 0x07; const uint8_t k4Bits = 0x0F; const uint8_t k8Bits = 0xFF; uint32_t readUInt32(unsigned char *buffer) { return ((buffer[0] << 0) | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24)); } void writeUInt32(unsigned char *buffer, uint32_t val) { buffer[0] = val & 0xFF; buffer[1] = (val >> 8) & 0xFF; buffer[2] = (val >> 16) & 0xFF; buffer[3] = (val >> 24) & 0xFF; } int min(int a, int b) { return a < b ? a : b; } /*========================== Low level compression ==========================*/ typedef struct { int block_independence_flag; int block_checksum_flag; int stream_checksum_flag; char *buffer; int buffer_size; int buffer_offset; int finished; // 1 if done compressing/decompressing; 0 otherwise void* xxh32_state; // Compression state int wrote_header; // Decompression state char header[10]; uint32_t block_size; // Size of current block int block_size_read; // # of bytes read for current block_size int block_uncompressed; // 1 if block is uncompressed, 0 otherwise uint32_t stream_checksum; // Storage for checksum int stream_checksum_read; // # of bytes read for stream_checksum } stream_state; void advanceInput(roslz4_stream *str, int nbytes) { str->input_next += nbytes; str->input_left -= nbytes; str->total_in += nbytes; } void advanceOutput(roslz4_stream *str, int nbytes) { str->output_next += nbytes; str->output_left -= nbytes; str->total_out += nbytes; } void fillUInt32(roslz4_stream *str, uint32_t *dest_val, int *offset) { char *dest = (char*) dest_val; int to_copy = min(4 - *offset, str->input_left); memcpy(dest + *offset, str->input_next, to_copy); advanceInput(str, to_copy); *offset += to_copy; } int writeHeader(roslz4_stream *str) { if (str->output_left < 7) { return ROSLZ4_OUTPUT_SMALL; // Output must have 7 bytes } stream_state *state = str->state; writeUInt32((unsigned char*) str->output_next, kMagicNumber); int version = 1; char *out = str->output_next; *(out+4) = ((unsigned)version & k2Bits) << 6; *(out+4) |= ((unsigned)state->block_independence_flag & k1Bits) << 5; *(out+4) |= ((unsigned)state->block_checksum_flag & k1Bits) << 4; *(out+4) |= ((unsigned)state->stream_checksum_flag & k1Bits) << 2; *(out+5) = ((unsigned)str->block_size_id & k3Bits) << 4; // Checksum: 2nd byte of hash of header flags unsigned char checksum = (XXH32(str->output_next + 4, 2, 0) >> 8) & k8Bits; *(str->output_next+6) = checksum; advanceOutput(str, 7); DEBUG("writeHeader() Put 7 bytes in output\n"); return ROSLZ4_OK; } int writeEOS(roslz4_stream *str) { if (str->output_left < 8) { return ROSLZ4_OUTPUT_SMALL; } stream_state *state = str->state; state->finished = 1; writeUInt32((unsigned char*) str->output_next, kEndOfStream); advanceOutput(str, 4); uint32_t stream_checksum = XXH32_digest(state->xxh32_state); writeUInt32((unsigned char*) str->output_next, stream_checksum); advanceOutput(str, 4); state->xxh32_state = NULL; DEBUG("writeEOS() Wrote 8 bytes to output %i\n", str->output_left); return ROSLZ4_STREAM_END; } // If successfull, number of bytes written to output // If error, LZ4 return code int bufferToOutput(roslz4_stream *str) { stream_state *state = str->state; uint32_t uncomp_size = state->buffer_offset; if (state->buffer_offset == 0) { return 0; // No data to flush } else if (str->output_left - 4 < uncomp_size) { DEBUG("bufferToOutput() Not enough space left in output\n"); return ROSLZ4_OUTPUT_SMALL; } DEBUG("bufferToOutput() Flushing %i bytes, %i left in output\n", state->buffer_offset, str->output_left); // Shrink output by 1 to detect if data is not compressible uint32_t comp_size = LZ4_compress_limitedOutput(state->buffer, str->output_next + 4, (int) state->buffer_offset, (int) uncomp_size - 1); uint32_t wrote; if (comp_size > 0) { DEBUG("bufferToOutput() Compressed to %i bytes\n", comp_size); // Write compressed data size wrote = 4 + comp_size; writeUInt32((unsigned char*)str->output_next, comp_size); } else { // Write uncompressed data DEBUG("bufferToOutput() Can't compress, copying input\n"); memcpy(str->output_next + 4, state->buffer, uncomp_size); // Write uncompressed data size. Signal data is uncompressed with high // order bit; won't confuse decompression because max block size is < 2GB wrote = 4 + uncomp_size; writeUInt32((unsigned char*) str->output_next, uncomp_size | 0x80000000); } advanceOutput(str, wrote); state->buffer_offset -= uncomp_size; DEBUG("bufferToOutput() Ate %i from buffer, wrote %i to output (%i)\n", uncomp_size, wrote, str->output_left); return wrote; } // Copy as much data as possible from input to internal buffer // Return number of bytes written if successful, LZ4 error code on error int inputToBuffer(roslz4_stream *str) { stream_state *state = str->state; if (str->input_left == 0 || state->buffer_size == state->buffer_offset) { return 0; } int buffer_left = state->buffer_size - state->buffer_offset; int to_copy = min(str->input_left, buffer_left); int ret = XXH32_update(state->xxh32_state, str->input_next, to_copy); if (ret == XXH_ERROR) { return ROSLZ4_ERROR; } memcpy(state->buffer + state->buffer_offset, str->input_next, to_copy); advanceInput(str, to_copy); state->buffer_offset += to_copy; DEBUG("inputToBuffer() Wrote % 5i bytes to buffer (size=% 5i)\n", to_copy, state->buffer_offset); return to_copy; } int streamStateAlloc(roslz4_stream *str) { stream_state *state = (stream_state*) malloc(sizeof(stream_state)); if (state == NULL) { return ROSLZ4_MEMORY_ERROR; // Allocation of state failed } str->state = state; str->block_size_id = -1; state->block_independence_flag = 1; state->block_checksum_flag = 0; state->stream_checksum_flag = 1; state->finished = 0; state->xxh32_state = XXH32_init(0); state->stream_checksum = 0; state->stream_checksum_read = 0; state->wrote_header = 0; state->buffer_offset = 0; state->buffer_size = 0; state->buffer = NULL; state->block_size = 0; state->block_size_read = 0; state->block_uncompressed = 0; str->total_in = 0; str->total_out = 0; return ROSLZ4_OK; } int streamResizeBuffer(roslz4_stream *str, int block_size_id) { stream_state *state = str->state; if (!(4 <= block_size_id && block_size_id <= 7)) { return ROSLZ4_PARAM_ERROR; // Invalid block size } str->block_size_id = block_size_id; state->buffer_offset = 0; state->buffer_size = roslz4_blockSizeFromIndex(str->block_size_id); state->buffer = (char*) malloc(sizeof(char) * state->buffer_size); if (state->buffer == NULL) { return ROSLZ4_MEMORY_ERROR; // Allocation of buffer failed } return ROSLZ4_OK; } void streamStateFree(roslz4_stream *str) { stream_state *state = str->state; if (state != NULL) { if (state->buffer != NULL) { free(state->buffer); } if (state->xxh32_state != NULL) { XXH32_digest(state->xxh32_state); } free(state); str->state = NULL; } } int roslz4_blockSizeFromIndex(int block_id) { return (1 << (8 + (2 * block_id))); } int roslz4_compressStart(roslz4_stream *str, int block_size_id) { int ret = streamStateAlloc(str); if (ret < 0) { return ret; } return streamResizeBuffer(str, block_size_id); } int roslz4_compress(roslz4_stream *str, int action) { int ret; stream_state *state = str->state; if (action != ROSLZ4_RUN && action != ROSLZ4_FINISH) { return ROSLZ4_PARAM_ERROR; // Unrecognized compression action } else if (state->finished) { return ROSLZ4_ERROR; // Cannot call action on finished stream } if (!state->wrote_header) { ret = writeHeader(str); if (ret < 0) { return ret; } state->wrote_header = 1; } // Copy input to internal buffer, compressing when full or finishing stream int read = 0, wrote = 0; do { read = inputToBuffer(str); if (read < 0) { return read; } wrote = 0; if (action == ROSLZ4_FINISH || state->buffer_offset == state->buffer_size) { wrote = bufferToOutput(str); if (wrote < 0) { return wrote; } } } while (read > 0 || wrote > 0); // Signal end of stream if finishing up, otherwise done if (action == ROSLZ4_FINISH) { return writeEOS(str); } else { return ROSLZ4_OK; } } void roslz4_compressEnd(roslz4_stream *str) { streamStateFree(str); } /*========================= Low level decompression =========================*/ int roslz4_decompressStart(roslz4_stream *str) { return streamStateAlloc(str); // Can't allocate internal buffer, block size is unknown until header is read } // Return 1 if header is present, 0 if more data is needed, // LZ4 error code (< 0) if error int processHeader(roslz4_stream *str) { stream_state *state = str->state; if (str->total_in >= 7) { return 1; } // Populate header buffer int to_copy = min(7 - str->total_in, str->input_left); memcpy(state->header + str->total_in, str->input_next, to_copy); advanceInput(str, to_copy); if (str->total_in < 7) { return 0; } // Parse header buffer unsigned char *header = (unsigned char*) state->header; uint32_t magic_number = readUInt32(header); if (magic_number != kMagicNumber) { return ROSLZ4_DATA_ERROR; // Stream does not start with magic number } // Check descriptor flags int version = (header[4] >> 6) & k2Bits; int block_independence_flag = (header[4] >> 5) & k1Bits; int block_checksum_flag = (header[4] >> 4) & k1Bits; int stream_size_flag = (header[4] >> 3) & k1Bits; int stream_checksum_flag = (header[4] >> 2) & k1Bits; int reserved1 = (header[4] >> 1) & k1Bits; int preset_dictionary_flag = (header[4] >> 0) & k1Bits; int reserved2 = (header[5] >> 7) & k1Bits; int block_max_id = (header[5] >> 4) & k3Bits; int reserved3 = (header[5] >> 0) & k4Bits; // LZ4 standard requirements if (version != 1) { return ROSLZ4_DATA_ERROR; // Wrong version number } if (reserved1 != 0 || reserved2 != 0 || reserved3 != 0) { return ROSLZ4_DATA_ERROR; // Reserved bits must be 0 } if (!(4 <= block_max_id && block_max_id <= 7)) { return ROSLZ4_DATA_ERROR; // Invalid block size } // Implementation requirements if (stream_size_flag != 0) { return ROSLZ4_DATA_ERROR; // Stream size not supported } if (preset_dictionary_flag != 0) { return ROSLZ4_DATA_ERROR; // Dictionary not supported } if (block_independence_flag != 1) { return ROSLZ4_DATA_ERROR; // Block dependence not supported } if (block_checksum_flag != 0) { return ROSLZ4_DATA_ERROR; // Block checksums not supported } if (stream_checksum_flag != 1) { return ROSLZ4_DATA_ERROR; // Must have stream checksum } int header_checksum = (XXH32(header + 4, 2, 0) >> 8) & k8Bits; int stored_header_checksum = (header[6] >> 0) & k8Bits; if (header_checksum != stored_header_checksum) { return ROSLZ4_DATA_ERROR; // Header checksum doesn't match } int ret = streamResizeBuffer(str, block_max_id); if (ret == ROSLZ4_OK) { return 1; } else { return ret; } } // Read block size, return 1 if value is stored in state->block_size 0 otherwise int readBlockSize(roslz4_stream *str) { stream_state *state = str->state; if (state->block_size_read < 4) { fillUInt32(str, &state->block_size, &state->block_size_read); if (state->block_size_read == 4) { state->block_size = readUInt32((unsigned char*)&state->block_size); state->block_uncompressed = ((unsigned)state->block_size >> 31) & k1Bits; state->block_size &= 0x7FFFFFFF; DEBUG("readBlockSize() Block size = %i uncompressed = %i\n", state->block_size, state->block_uncompressed); return 1; } else { return 0; } } return 1; } // Copy at most one blocks worth of data from input to internal buffer. // Return 1 if whole block has been read, 0 if not, LZ4 error otherwise int readBlock(roslz4_stream *str) { stream_state *state = str->state; if (state->block_size_read != 4 || state->block_size == kEndOfStream) { return ROSLZ4_ERROR; } int block_left = state->block_size - state->buffer_offset; int to_copy = min(str->input_left, block_left); memcpy(state->buffer + state->buffer_offset, str->input_next, to_copy); advanceInput(str, to_copy); state->buffer_offset += to_copy; DEBUG("readBlock() Read %i bytes from input (block = %i/%i)\n", to_copy, state->buffer_offset, state->block_size); return state->buffer_offset == state->block_size; } int decompressBlock(roslz4_stream *str) { stream_state *state = str->state; if (state->block_size_read != 4 || state->block_size != state->buffer_offset) { // Internal error: Can't decompress block, it's not in buffer return ROSLZ4_ERROR; } if (state->block_uncompressed) { if (str->output_left >= state->block_size) { memcpy(str->output_next, state->buffer, state->block_size); int ret = XXH32_update(state->xxh32_state, str->output_next, state->block_size); if (ret == XXH_ERROR) { return ROSLZ4_ERROR; } advanceOutput(str, state->block_size); state->block_size_read = 0; state->buffer_offset = 0; return ROSLZ4_OK; } else { return ROSLZ4_OUTPUT_SMALL; } } else { int decomp_size; decomp_size = LZ4_decompress_safe(state->buffer, str->output_next, state->block_size, str->output_left); if (decomp_size < 0) { if (str->output_left >= state->buffer_size) { return ROSLZ4_DATA_ERROR; // Must be a problem with the data stream } else { // Data error or output is small; increase output to disambiguate return ROSLZ4_OUTPUT_SMALL; } } else { int ret = XXH32_update(state->xxh32_state, str->output_next, decomp_size); if (ret == XXH_ERROR) { return ROSLZ4_ERROR; } advanceOutput(str, decomp_size); state->block_size_read = 0; state->buffer_offset = 0; return ROSLZ4_OK; } } } int readChecksum(roslz4_stream *str) { stream_state *state = str->state; fillUInt32(str, &state->stream_checksum, &state->stream_checksum_read); if (state->stream_checksum_read == 4) { state->finished = 1; state->stream_checksum = readUInt32((unsigned char*)&state->stream_checksum); uint32_t checksum = XXH32_digest(state->xxh32_state); state->xxh32_state = NULL; if (checksum == state->stream_checksum) { return ROSLZ4_STREAM_END; } else { return ROSLZ4_DATA_ERROR; } } return ROSLZ4_OK; } int roslz4_decompress(roslz4_stream *str) { stream_state *state = str->state; if (state->finished) { return ROSLZ4_ERROR; // Already reached end of stream } // Return if header isn't present or error was encountered int ret = processHeader(str); if (ret <= 0) { return ret; } // Read in blocks and decompress them as long as there's data to be processed while (str->input_left > 0) { ret = readBlockSize(str); if (ret == 0) { return ROSLZ4_OK; } if (state->block_size == kEndOfStream) { return readChecksum(str); } ret = readBlock(str); if (ret == 0) { return ROSLZ4_OK; } else if (ret < 0) { return ret; } ret = decompressBlock(str); if (ret < 0) { return ret; } } return ROSLZ4_OK; } void roslz4_decompressEnd(roslz4_stream *str) { streamStateFree(str); } /*=================== Oneshot compression / decompression ===================*/ int roslz4_buffToBuffCompress(char *input, unsigned int input_size, char *output, unsigned int *output_size, int block_size_id) { roslz4_stream stream; stream.input_next = input; stream.input_left = input_size; stream.output_next = output; stream.output_left = *output_size; int ret; ret = roslz4_compressStart(&stream, block_size_id); if (ret != ROSLZ4_OK) { return ret; } while (stream.input_left > 0 && ret != ROSLZ4_STREAM_END) { ret = roslz4_compress(&stream, ROSLZ4_FINISH); if (ret == ROSLZ4_ERROR || ret == ROSLZ4_OUTPUT_SMALL) { roslz4_compressEnd(&stream); return ret; } } *output_size = *output_size - stream.output_left; roslz4_compressEnd(&stream); if (stream.input_left == 0 && ret == ROSLZ4_STREAM_END) { return ROSLZ4_OK; // Success } else { return ROSLZ4_ERROR; // User did not provide exact buffer } } int roslz4_buffToBuffDecompress(char *input, unsigned int input_size, char *output, unsigned int *output_size) { roslz4_stream stream; stream.input_next = input; stream.input_left = input_size; stream.output_next = output; stream.output_left = *output_size; int ret; ret = roslz4_decompressStart(&stream); if (ret != ROSLZ4_OK) { return ret; } while (stream.input_left > 0 && ret != ROSLZ4_STREAM_END) { ret = roslz4_decompress(&stream); if (ret < 0) { roslz4_decompressEnd(&stream); return ret; } } *output_size = *output_size - stream.output_left; roslz4_decompressEnd(&stream); if (stream.input_left == 0 && ret == ROSLZ4_STREAM_END) { return ROSLZ4_OK; // Success } else { return ROSLZ4_ERROR; // User did not provide exact buffer } }
0
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/src
apollo_public_repos/apollo-platform/ros/ros_comm/roslz4/src/roslz4/__init__.py
# Software License Agreement (BSD License) # # Copyright (c) 2014, Ben Charrow # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from ._roslz4 import * def compress(data): compressor = LZ4Compressor() return compressor.compress(data) + compressor.flush() def decompress(data): decompressor = LZ4Decompressor() output = decompressor.decompress(data) return output
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(rosconsole) if(NOT WIN32) set_directory_properties(PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra") endif() find_package(catkin REQUIRED COMPONENTS cpp_common rostime rosunit) find_package(Boost COMPONENTS regex system thread) # select rosconsole backend set(ROSCONSOLE_BACKEND "" CACHE STRING "Type of rosconsole backend, one of 'log4cxx', 'glog', 'print'") set(rosconsole_backend_INCLUDE_DIRS) set(rosconsole_backend_LIBRARIES) if(ROSCONSOLE_BACKEND STREQUAL "" OR ROSCONSOLE_BACKEND STREQUAL "log4cxx") find_package(Log4cxx QUIET) if(NOT LOG4CXX_LIBRARIES) # backup plan, hope it is in the system path find_library(LOG4CXX_LIBRARIES log4cxx) endif() if(LOG4CXX_LIBRARIES) list(APPEND rosconsole_backend_INCLUDE_DIRS ${LOG4CXX_INCLUDE_DIRS}) list(APPEND rosconsole_backend_LIBRARIES rosconsole_log4cxx rosconsole_backend_interface ${LOG4CXX_LIBRARIES}) set(ROSCONSOLE_BACKEND "log4cxx") elseif(ROSCONSOLE_BACKEND STREQUAL "log4cxx") message(FATAL_ERROR "Couldn't find log4cxx library") endif() endif() if(ROSCONSOLE_BACKEND STREQUAL "" OR ROSCONSOLE_BACKEND STREQUAL "glog") find_package(PkgConfig) pkg_check_modules(GLOG QUIET libglog) if(GLOG_FOUND) list(APPEND rosconsole_backend_INCLUDE_DIRS ${GLOG_INCLUDE_DIRS}) list(APPEND rosconsole_backend_LIBRARIES rosconsole_glog rosconsole_backend_interface ${GLOG_LIBRARIES}) set(ROSCONSOLE_BACKEND "glog") elseif(ROSCONSOLE_BACKEND STREQUAL "glog") message(FATAL_ERROR "Couldn't find glog library") endif() endif() if(ROSCONSOLE_BACKEND STREQUAL "" OR ROSCONSOLE_BACKEND STREQUAL "print") list(APPEND rosconsole_backend_LIBRARIES rosconsole_print rosconsole_backend_interface) set(ROSCONSOLE_BACKEND "print") endif() message(STATUS "rosconsole backend: ${ROSCONSOLE_BACKEND}") catkin_package( INCLUDE_DIRS include ${rosconsole_backend_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} LIBRARIES rosconsole ${rosconsole_backend_LIBRARIES} ${Boost_LIBRARIES} CATKIN_DEPENDS cpp_common rostime CFG_EXTRAS rosconsole-extras.cmake ) include(${CATKIN_DEVEL_PREFIX}/share/${PROJECT_NAME}/cmake/rosconsole-extras.cmake) # See ticket: https://code.ros.org/trac/ros/ticket/3626 # On mac use g++-4.2 IF(${CMAKE_SYSTEM} MATCHES "Darwin-11.*") IF(EXISTS "/usr/bin/g++-4.2") set(CMAKE_CXX_COMPILER /usr/bin/g++-4.2) ELSE(EXISTS "/usr/bin/g++-4.2") # If there is no g++-4.2 use clang++ set(CMAKE_CXX_COMPILER /usr/bin/clang++) ENDIF(EXISTS "/usr/bin/g++-4.2") ENDIF(${CMAKE_SYSTEM} MATCHES "Darwin-11.*") include_directories(include ${catkin_INCLUDE_DIRS} ${rosconsole_backend_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) add_library(rosconsole_backend_interface src/rosconsole/rosconsole_backend.cpp) add_library(rosconsole src/rosconsole/rosconsole.cpp) target_link_libraries(rosconsole ${rosconsole_backend_LIBRARIES} ${catkin_LIBRARIES} ${Boost_LIBRARIES}) if(ROSCONSOLE_BACKEND STREQUAL "log4cxx") add_library(rosconsole_log4cxx src/rosconsole/impl/rosconsole_log4cxx.cpp) target_link_libraries(rosconsole_log4cxx rosconsole_backend_interface ${LOG4CXX_LIBRARIES} ${Boost_LIBRARIES}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/speed_test.cpp") add_executable(rosconsole_speed_test test/speed_test.cpp) target_link_libraries(rosconsole_speed_test rosconsole ${rosconsole_backend_LIBRARIES} ${catkin_LIBRARIES} ${Boost_LIBRARIES}) endif() elseif(ROSCONSOLE_BACKEND STREQUAL "glog") add_library(rosconsole_glog src/rosconsole/impl/rosconsole_glog.cpp) target_link_libraries(rosconsole_glog rosconsole_backend_interface ${GLOG_LIBRARIES}) elseif(ROSCONSOLE_BACKEND STREQUAL "print") add_library(rosconsole_print src/rosconsole/impl/rosconsole_print.cpp) target_link_libraries(rosconsole_print rosconsole_backend_interface) else() message(FATAL_ERROR "Unknown rosconsole backend '${ROSCONSOLE_BACKEND}'") endif() if(CMAKE_HOST_UNIX) catkin_add_env_hooks(10.rosconsole SHELLS sh DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/env-hooks) else() catkin_add_env_hooks(10.rosconsole SHELLS bat DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/env-hooks) endif() install(TARGETS rosconsole rosconsole_${ROSCONSOLE_BACKEND} rosconsole_backend_interface ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}) install(FILES config/rosconsole.config DESTINATION ${CATKIN_GLOBAL_SHARE_DESTINATION}/ros/config) install(DIRECTORY include/ DESTINATION ${CATKIN_GLOBAL_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.h") if(CATKIN_ENABLE_TESTING) catkin_add_gtest(${PROJECT_NAME}-utest test/utest.cpp) if(TARGET ${PROJECT_NAME}-utest) target_link_libraries(${PROJECT_NAME}-utest ${PROJECT_NAME}) endif() if(${CMAKE_SYSTEM_NAME} STREQUAL Linux) catkin_add_gtest(${PROJECT_NAME}-assertion_test test/assertion_test.cpp) if(TARGET ${PROJECT_NAME}-assertion_test) target_link_libraries(${PROJECT_NAME}-assertion_test ${PROJECT_NAME}) endif() endif() catkin_add_gtest(${PROJECT_NAME}-thread_test test/thread_test.cpp) if(TARGET ${PROJECT_NAME}-thread_test) target_link_libraries(${PROJECT_NAME}-thread_test ${PROJECT_NAME}) endif() endif()
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/package.xml
<package> <name>rosconsole</name> <version>1.11.21</version> <description>ROS console output library.</description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>BSD</license> <url>http://www.ros.org/wiki/rosconsole</url> <author>Josh Faust</author> <buildtool_depend>catkin</buildtool_depend> <build_depend>apr</build_depend> <build_depend>boost</build_depend> <build_depend>cpp_common</build_depend> <build_depend>log4cxx</build_depend> <build_depend>rostime</build_depend> <build_depend>rosunit</build_depend> <run_depend>apr</run_depend> <run_depend>cpp_common</run_depend> <run_depend>log4cxx</run_depend> <run_depend>rosbuild</run_depend> <run_depend>rostime</run_depend> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/mainpage.dox
/** * \mainpage * * \htmlinclude manifest.html * * \b rosconsole is a package for console output and logging. It provides a macro-based interface * which allows both printf- and stream-style output. It also wraps log4cxx (http://logging.apache.org/log4cxx/index.html), * which supports hierarchical loggers, verbosity levels and configuration-files. * */
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rosconsole/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-rosconsole-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package rosconsole ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- * fix building on GCC-6 (`#911 <https://github.com/ros/ros_comm/pull/911>`_) 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- * use directory specific compiler flags (`#785 <https://github.com/ros/ros_comm/pull/785>`_) 1.11.18 (2016-03-17) -------------------- * fix compiler warnings 1.11.17 (2016-03-11) -------------------- * use boost::make_shared instead of new for constructing boost::shared_ptr (`#740 <https://github.com/ros/ros_comm/issues/740>`_) 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- * avoid redefining ROS_ASSERT_ENABLED (`#628 <https://github.com/ros/ros_comm/pull/628>`_) 1.11.13 (2015-04-28) -------------------- 1.11.12 (2015-04-27) -------------------- 1.11.11 (2015-04-16) -------------------- * add DELAYED_THROTTLE versions of log macros (`#571 <https://github.com/ros/ros_comm/issues/571>`_) 1.11.10 (2014-12-22) -------------------- * fix various defects reported by coverity 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- 1.11.6 (2014-07-10) ------------------- 1.11.5 (2014-06-24) ------------------- * rename variables within rosconsole macros (`#442 <https://github.com/ros/ros_comm/issues/442>`_) 1.11.4 (2014-06-16) ------------------- 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- 1.11.0 (2014-03-04) ------------------- 1.10.0 (2014-02-11) ------------------- 1.9.54 (2014-01-27) ------------------- * fix rosconsole segfault when using ROSCONSOLE_FORMAT with (`#342 <https://github.com/ros/ros_comm/issues/342>`_) * add missing run/test dependencies on rosbuild to get ROS_ROOT environment variable 1.9.53 (2014-01-14) ------------------- * readd g_level_lockup symbol for backward compatibility when log4cxx is being used 1.9.52 (2014-01-08) ------------------- * fix missing export of rosconsole backend interface library 1.9.51 (2014-01-07) ------------------- * refactor rosconsole to not expose log4cxx, implement empty and log4cxx backends 1.9.50 (2013-10-04) ------------------- 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- * wrap condition in ROS_ASSERT_CMD in parenthesis (`#271 <https://github.com/ros/ros_comm/issues/271>`_) 1.9.47 (2013-07-03) ------------------- * force CMake policy before setting preprocessor definition to ensure correct escaping (`#245 <https://github.com/ros/ros_comm/issues/245>`_) * check for CATKIN_ENABLE_TESTING to enable configure without tests 1.9.46 (2013-06-18) ------------------- 1.9.45 (2013-06-06) ------------------- 1.9.44 (2013-03-21) ------------------- * fix install destination for dll's under Windows 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- * fix handling spaces in folder names (`ros/catkin#375 <https://github.com/ros/catkin/issues/375>`_) 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- * fix dependent packages by pass LOG4CXX include dirs and libraries along * fix usage of variable arguments in vFormatToBuffer() function 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/test/thread_test.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/console.h" #include <gtest/gtest.h> #include <boost/thread.hpp> #include "log4cxx/appenderskeleton.h" #include "log4cxx/spi/loggingevent.h" #include <vector> class TestAppender : public log4cxx::AppenderSkeleton { public: struct Info { log4cxx::LevelPtr level_; std::string message_; std::string logger_name_; }; typedef std::vector<Info> V_Info; V_Info info_; protected: virtual void append(const log4cxx::spi::LoggingEventPtr& event, log4cxx::helpers::Pool&) { Info info; info.level_ = event->getLevel(); info.message_ = event->getMessage(); info.logger_name_ = event->getLoggerName(); info_.push_back( info ); } virtual void close() { } virtual bool requiresLayout() const { return false; } }; void threadFunc(boost::barrier* b) { b->wait(); ROS_INFO("Hello"); } // Ensure all threaded calls go out TEST(Rosconsole, threadedCalls) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender( appender ); boost::thread_group tg; boost::barrier b(10); for (uint32_t i = 0; i < 10; ++i) { tg.create_thread(boost::bind(threadFunc, &b)); } tg.join_all(); ASSERT_EQ(appender->info_.size(), 10ULL); logger->removeAppender(appender); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::Time::init(); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/test/utest.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/console.h" #include "log4cxx/appenderskeleton.h" #include "log4cxx/spi/loggingevent.h" #include <vector> #include <stdexcept> #include <gtest/gtest.h> #include <boost/shared_array.hpp> class TestAppender : public log4cxx::AppenderSkeleton { public: struct Info { log4cxx::LevelPtr level_; std::string message_; std::string logger_name_; }; typedef std::vector<Info> V_Info; V_Info info_; protected: virtual void append(const log4cxx::spi::LoggingEventPtr& event, log4cxx::helpers::Pool&) { Info info; info.level_ = event->getLevel(); info.message_ = event->getMessage(); info.logger_name_ = event->getLoggerName(); info_.push_back( info ); } virtual void close() { } virtual bool requiresLayout() const { return false; } }; class TestAppenderWithThrow : public log4cxx::AppenderSkeleton { protected: virtual void append(const log4cxx::spi::LoggingEventPtr&, log4cxx::helpers::Pool&) { throw std::runtime_error("This should be caught"); } virtual void close() { } virtual bool requiresLayout() const { return false; } }; struct BasicFilter : public ros::console::FilterBase { BasicFilter(bool enabled) : enabled_(enabled) {} inline virtual bool isEnabled() { return enabled_; }; bool enabled_; }; BasicFilter g_filter(true); #define DEFINE_COND_TESTS(name, macro_base, level, log4cxx_level) \ TEST(RosConsole, name##Cond) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_COND(true, "Testing %d %d %d", 1, 2, 3); \ macro_base##_COND(false, "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##NamedCond) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_COND_NAMED(true, "test", "Testing %d %d %d", 1, 2, 3); \ macro_base##_COND_NAMED(false, "test", "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamCond) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_COND(true, "Testing " << 1 << " " << 2 << " " << 3); \ macro_base##_STREAM_COND(false, "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamCondNamed) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_COND_NAMED(true, "test", "Testing " << 1 << " " << 2 << " " << 3); \ macro_base##_STREAM_COND_NAMED(false, "test", "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } #define DEFINE_ONCE_TESTS(name, macro_base, level, log4cxx_level) \ TEST(RosConsole, name##Once) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_ONCE("Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##NamedOnce) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_ONCE_NAMED("test", "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamOnce) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_ONCE("Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamOnceNamed) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_ONCE_NAMED("test", "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } #define DEFINE_THROTTLE_TESTS(name, macro_base, level, log4cxx_level) \ TEST(RosConsole, name##Throttle) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_THROTTLE(0.5, "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##NamedThrottle) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_THROTTLE_NAMED(0.5, "test", "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamThrottle) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_THROTTLE(0.5, "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamThrottleNamed) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_THROTTLE_NAMED(0.5, "test", "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } #define DEFINE_FILTER_TESTS(name, macro_base, level, log4cxx_level) \ TEST(RosConsole, name##Filter) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_FILTER(&g_filter, "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##NamedFilter) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_FILTER_NAMED(&g_filter, "test", "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamFilter) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_FILTER(&g_filter, "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamFilterNamed) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_FILTER_NAMED(&g_filter, "test", "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } #define DEFINE_LEVEL_TESTS(name, macro_base, level, log4cxx_level) \ TEST(RosConsole, name) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base("Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##Named) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_NAMED("test", "Testing %d %d %d", 1, 2, 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##Stream) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM("Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ TEST(RosConsole, name##StreamNamed) \ { \ TestAppender* appender = new TestAppender; \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender( appender ); \ macro_base##_STREAM_NAMED("test", "Testing " << 1 << " " << 2 << " " << 3); \ ASSERT_EQ((int)appender->info_.size(), 1); \ EXPECT_STREQ(appender->info_[0].message_.c_str(), "Testing 1 2 3"); \ EXPECT_EQ(appender->info_[0].level_, log4cxx_level); \ EXPECT_STREQ(appender->info_[0].logger_name_.c_str(), ROSCONSOLE_ROOT_LOGGER_NAME".rosconsole.test"); \ log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->removeAppender( appender ); \ } \ DEFINE_COND_TESTS(name, macro_base, level, log4cxx_level) \ DEFINE_ONCE_TESTS(name, macro_base, level, log4cxx_level) \ DEFINE_THROTTLE_TESTS(name, macro_base, level, log4cxx_level) \ DEFINE_FILTER_TESTS(name, macro_base, level, log4cxx_level) DEFINE_LEVEL_TESTS(debug, ROS_DEBUG, ros::console::levels::Debug, log4cxx::Level::getDebug()) DEFINE_LEVEL_TESTS(info, ROS_INFO, ros::console::levels::Info, log4cxx::Level::getInfo()) DEFINE_LEVEL_TESTS(warn, ROS_WARN, ros::console::levels::Warn, log4cxx::Level::getWarn()) DEFINE_LEVEL_TESTS(error, ROS_ERROR, ros::console::levels::Error, log4cxx::Level::getError()) DEFINE_LEVEL_TESTS(fatal, ROS_FATAL, ros::console::levels::Fatal, log4cxx::Level::getFatal()) TEST(RosConsole, loggingLevels) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender( appender ); int pre_count = 0; int post_count = 0; { logger->setLevel( log4cxx::Level::getInfo() ); pre_count = appender->info_.size(); ROS_DEBUG("test"); ROS_INFO("test"); ROS_WARN("test"); ROS_ERROR("test"); ROS_FATAL("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 4); logger->setLevel( log4cxx::Level::getWarn() ); pre_count = appender->info_.size(); ROS_DEBUG("test"); ROS_INFO("test"); ROS_WARN("test"); ROS_ERROR("test"); ROS_FATAL("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 3); logger->setLevel( log4cxx::Level::getError() ); pre_count = appender->info_.size(); ROS_DEBUG("test"); ROS_INFO("test"); ROS_WARN("test"); ROS_ERROR("test"); ROS_FATAL("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 2); logger->setLevel( log4cxx::Level::getFatal() ); pre_count = appender->info_.size(); ROS_DEBUG("test"); ROS_INFO("test"); ROS_WARN("test"); ROS_ERROR("test"); ROS_FATAL("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 1); logger->setLevel( log4cxx::Level::getOff() ); pre_count = appender->info_.size(); ROS_DEBUG("test"); ROS_INFO("test"); ROS_WARN("test"); ROS_ERROR("test"); ROS_FATAL("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count); } { logger->setLevel( log4cxx::Level::getInfo() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM("test"); ROS_INFO_STREAM("test"); ROS_WARN_STREAM("test"); ROS_ERROR_STREAM("test"); ROS_FATAL_STREAM("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 4); logger->setLevel( log4cxx::Level::getWarn() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM("test"); ROS_INFO_STREAM("test"); ROS_WARN_STREAM("test"); ROS_ERROR_STREAM("test"); ROS_FATAL_STREAM("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 3); logger->setLevel( log4cxx::Level::getError() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM("test"); ROS_INFO_STREAM("test"); ROS_WARN_STREAM("test"); ROS_ERROR_STREAM("test"); ROS_FATAL_STREAM("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 2); logger->setLevel( log4cxx::Level::getFatal() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM("test"); ROS_INFO_STREAM("test"); ROS_WARN_STREAM("test"); ROS_ERROR_STREAM("test"); ROS_FATAL_STREAM("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 1); logger->setLevel( log4cxx::Level::getOff() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM("test"); ROS_INFO_STREAM("test"); ROS_WARN_STREAM("test"); ROS_ERROR_STREAM("test"); ROS_FATAL_STREAM("test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count); } { logger->setLevel( log4cxx::Level::getInfo() ); pre_count = appender->info_.size(); ROS_DEBUG_NAMED("test_name", "test"); ROS_INFO_NAMED("test_name", "test"); ROS_WARN_NAMED("test_name", "test"); ROS_ERROR_NAMED("test_name", "test"); ROS_FATAL_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 4); logger->setLevel( log4cxx::Level::getWarn() ); pre_count = appender->info_.size(); ROS_DEBUG_NAMED("test_name", "test"); ROS_INFO_NAMED("test_name", "test"); ROS_WARN_NAMED("test_name", "test"); ROS_ERROR_NAMED("test_name", "test"); ROS_FATAL_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 3); logger->setLevel( log4cxx::Level::getError() ); pre_count = appender->info_.size(); ROS_DEBUG_NAMED("test_name", "test"); ROS_INFO_NAMED("test_name", "test"); ROS_WARN_NAMED("test_name", "test"); ROS_ERROR_NAMED("test_name", "test"); ROS_FATAL_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 2); logger->setLevel( log4cxx::Level::getFatal() ); pre_count = appender->info_.size(); ROS_DEBUG_NAMED("test_name", "test"); ROS_INFO_NAMED("test_name", "test"); ROS_WARN_NAMED("test_name", "test"); ROS_ERROR_NAMED("test_name", "test"); ROS_FATAL_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 1); logger->setLevel( log4cxx::Level::getOff() ); pre_count = appender->info_.size(); ROS_DEBUG_NAMED("test_name", "test"); ROS_INFO_NAMED("test_name", "test"); ROS_WARN_NAMED("test_name", "test"); ROS_ERROR_NAMED("test_name", "test"); ROS_FATAL_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count); } { logger->setLevel( log4cxx::Level::getInfo() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM_NAMED("test_name", "test"); ROS_INFO_STREAM_NAMED("test_name", "test"); ROS_WARN_STREAM_NAMED("test_name", "test"); ROS_ERROR_STREAM_NAMED("test_name", "test"); ROS_FATAL_STREAM_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 4); logger->setLevel( log4cxx::Level::getWarn() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM_NAMED("test_name", "test"); ROS_INFO_STREAM_NAMED("test_name", "test"); ROS_WARN_STREAM_NAMED("test_name", "test"); ROS_ERROR_STREAM_NAMED("test_name", "test"); ROS_FATAL_STREAM_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 3); logger->setLevel( log4cxx::Level::getError() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM_NAMED("test_name", "test"); ROS_INFO_STREAM_NAMED("test_name", "test"); ROS_WARN_STREAM_NAMED("test_name", "test"); ROS_ERROR_STREAM_NAMED("test_name", "test"); ROS_FATAL_STREAM_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 2); logger->setLevel( log4cxx::Level::getFatal() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM_NAMED("test_name", "test"); ROS_INFO_STREAM_NAMED("test_name", "test"); ROS_WARN_STREAM_NAMED("test_name", "test"); ROS_ERROR_STREAM_NAMED("test_name", "test"); ROS_FATAL_STREAM_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 1); logger->setLevel( log4cxx::Level::getOff() ); pre_count = appender->info_.size(); ROS_DEBUG_STREAM_NAMED("test_name", "test"); ROS_INFO_STREAM_NAMED("test_name", "test"); ROS_WARN_STREAM_NAMED("test_name", "test"); ROS_ERROR_STREAM_NAMED("test_name", "test"); ROS_FATAL_STREAM_NAMED("test_name", "test"); post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count); } logger->removeAppender( appender ); } TEST(RosConsole, changingLevel) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender( appender ); logger->setLevel( log4cxx::Level::getError() ); for ( int i = ros::console::levels::Debug; i < ros::console::levels::Count; ++i ) { ROS_LOG((ros::console::Level)i, ROSCONSOLE_DEFAULT_NAME, "test"); } EXPECT_EQ((int)appender->info_.size(), 2); logger->removeAppender( appender ); logger->setLevel( log4cxx::Level::getDebug() ); } TEST(RosConsole, changingLoggerLevel) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender( appender ); logger->setLevel(log4cxx::Level::getDebug()); ros::console::notifyLoggerLevelsChanged(); ROS_LOG(ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, "test"); logger->setLevel(log4cxx::Level::getInfo()); ros::console::notifyLoggerLevelsChanged(); ROS_LOG(ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "test"); logger->setLevel(log4cxx::Level::getWarn()); ros::console::notifyLoggerLevelsChanged(); ROS_LOG(ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, "test"); logger->setLevel(log4cxx::Level::getError()); ros::console::notifyLoggerLevelsChanged(); ROS_LOG(ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, "test"); logger->setLevel(log4cxx::Level::getFatal()); ros::console::notifyLoggerLevelsChanged(); ROS_LOG(ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, "test"); EXPECT_EQ((int)appender->info_.size(), 5); logger->removeAppender( appender ); logger->setLevel( log4cxx::Level::getDebug() ); } TEST(RosConsole, longPrintfStyleOutput) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender( appender ); std::stringstream ss; for (int i = 0; i < 100000; ++i ) { ss << 'a'; } ROS_INFO("%s", ss.str().c_str()); ASSERT_EQ((int)appender->info_.size(), 1); EXPECT_STREQ(appender->info_[0].message_.c_str(), ss.str().c_str()); logger->removeAppender( appender ); logger->setLevel( log4cxx::Level::getDebug() ); } TEST(RosConsole, throwingAppender) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppenderWithThrow* appender = new TestAppenderWithThrow; logger->addAppender( appender ); try { ROS_INFO("Hello there"); } catch (std::exception& e) { FAIL(); } logger->removeAppender( appender ); logger->setLevel( log4cxx::Level::getDebug() ); } void onceFunc() { ROS_LOG_ONCE(ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); } TEST(RosConsole, once) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); onceFunc(); onceFunc(); EXPECT_EQ(appender->info_.size(), 1ULL); logger->removeAppender(appender); } void throttleFunc() { ROS_LOG_THROTTLE(0.5, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); } TEST(RosConsole, throttle) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); ros::Time start = ros::Time::now(); while (ros::Time::now() <= start + ros::Duration(0.5)) { throttleFunc(); ros::Duration(0.01).sleep(); } throttleFunc(); EXPECT_EQ(appender->info_.size(), 2ULL); logger->removeAppender(appender); } void delayedThrottleFunc() { ROS_LOG_DELAYED_THROTTLE(0.5, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); } void delayedThrottleFunc2() { ROS_LOG_DELAYED_THROTTLE(0.5, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello2"); } TEST(RosConsole, delayedThrottle) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); ros::Time start = ros::Time::now(); while (ros::Time::now() <= start + ros::Duration(0.4)) { delayedThrottleFunc(); ros::Duration(0.01).sleep(); } EXPECT_EQ(appender->info_.size(), 0ULL); const int pre_count = appender->info_.size(); start = ros::Time::now(); while (ros::Time::now() <= start + ros::Duration(0.6)) { delayedThrottleFunc2(); ros::Duration(0.01).sleep(); } const int post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 1); logger->removeAppender(appender); } void onceStreamFunc() { ROS_LOG_STREAM_ONCE(ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); } TEST(RosConsole, onceStream) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); onceStreamFunc(); onceStreamFunc(); EXPECT_EQ(appender->info_.size(), 1ULL); logger->removeAppender(appender); } void throttleStreamFunc() { ROS_LOG_STREAM_THROTTLE(0.5, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); } TEST(RosConsole, throttleStream) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); ros::Time start = ros::Time::now(); while (ros::Time::now() <= start + ros::Duration(0.5)) { throttleStreamFunc(); ros::Duration(0.01).sleep(); } throttleStreamFunc(); EXPECT_EQ(appender->info_.size(), 2ULL); logger->removeAppender(appender); } void delayedThrottleStreamFunc() { ROS_LOG_STREAM_DELAYED_THROTTLE(0.5, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); } void delayedThrottleStreamFunc2() { ROS_LOG_STREAM_DELAYED_THROTTLE(0.5, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello2"); } TEST(RosConsole, delayedStreamThrottle) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); ros::Time start = ros::Time::now(); while (ros::Time::now() <= start + ros::Duration(0.4)) { delayedThrottleStreamFunc(); ros::Duration(0.01).sleep(); } EXPECT_EQ(appender->info_.size(), 0ULL); const int pre_count = appender->info_.size(); start = ros::Time::now(); while (ros::Time::now() <= start + ros::Duration(0.6)) { delayedThrottleStreamFunc2(); ros::Duration(0.01).sleep(); } const int post_count = appender->info_.size(); EXPECT_EQ(post_count, pre_count + 1); logger->removeAppender(appender); } TEST(RosConsole, basicFilter) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); BasicFilter trueFilter(true), falseFilter(false); ROS_LOG_FILTER(&trueFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); ROS_LOG_FILTER(&falseFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello2"); ASSERT_EQ(appender->info_.size(), 1ULL); EXPECT_STREQ(appender->info_[0].message_.c_str(), "Hello"); logger->removeAppender(appender); } TEST(RosConsole, basicFilterStream) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); BasicFilter trueFilter(true), falseFilter(false); ROS_LOG_STREAM_FILTER(&trueFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); ROS_LOG_STREAM_FILTER(&falseFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello2"); ASSERT_EQ(appender->info_.size(), 1ULL); EXPECT_STREQ(appender->info_[0].message_.c_str(), "Hello"); logger->removeAppender(appender); } struct AdvancedFilter : public ros::console::FilterBase { AdvancedFilter(bool enabled) : enabled_(enabled) , count_(0) {} using ros::console::FilterBase::isEnabled; inline virtual bool isEnabled(ros::console::FilterParams& params) { fprintf(stderr, "%s %s:%d:%s\n", params.message, params.file, params.line, params.function); ++count_; return enabled_; } bool enabled_; int count_; }; TEST(RosConsole, advancedFilter) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); AdvancedFilter trueFilter(true), falseFilter(false); ROS_LOG_FILTER(&trueFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); ROS_LOG_FILTER(&falseFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello2"); ASSERT_EQ(appender->info_.size(), 1ULL); EXPECT_STREQ(appender->info_[0].message_.c_str(), "Hello"); EXPECT_EQ(trueFilter.count_, 1); EXPECT_EQ(falseFilter.count_, 1); logger->removeAppender(appender); } TEST(RosConsole, advancedFilterStream) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); AdvancedFilter trueFilter(true), falseFilter(false); ROS_LOG_STREAM_FILTER(&trueFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); ROS_LOG_STREAM_FILTER(&falseFilter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello2"); ASSERT_EQ(appender->info_.size(), 1ULL); EXPECT_STREQ(appender->info_[0].message_.c_str(), "Hello"); EXPECT_EQ(trueFilter.count_, 1); EXPECT_EQ(falseFilter.count_, 1); logger->removeAppender(appender); } struct ChangeFilter : public ros::console::FilterBase { using ros::console::FilterBase::isEnabled; inline virtual bool isEnabled(ros::console::FilterParams& params) { params.out_message = "haha"; params.level = ros::console::levels::Error; return true; } }; TEST(RosConsole, changeFilter) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); ChangeFilter filter; ROS_LOG_FILTER(&filter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); ASSERT_EQ(appender->info_.size(), 1ULL); EXPECT_STREQ(appender->info_[0].message_.c_str(), "haha"); EXPECT_EQ(appender->info_[0].level_, log4cxx::Level::getError()); logger->removeAppender(appender); } TEST(RosConsole, changeFilterStream) { log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); TestAppender* appender = new TestAppender; logger->addAppender(appender); ChangeFilter filter; ROS_LOG_STREAM_FILTER(&filter, ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, "Hello"); ASSERT_EQ(appender->info_.size(), 1ULL); EXPECT_STREQ(appender->info_[0].message_.c_str(), "haha"); EXPECT_EQ(appender->info_[0].level_, log4cxx::Level::getError()); logger->removeAppender(appender); } TEST(RosConsole, formatToBufferInitialZero) { boost::shared_array<char> buffer; size_t size = 0; ros::console::formatToBuffer(buffer, size, "Hello World %d", 5); EXPECT_EQ(size, 14U); EXPECT_STREQ(buffer.get(), "Hello World 5"); } TEST(RosConsole, formatToBufferInitialLargerThanFormat) { boost::shared_array<char> buffer(new char[30]); size_t size = 30; ros::console::formatToBuffer(buffer, size, "Hello World %d", 5); EXPECT_EQ(size, 30U); EXPECT_STREQ(buffer.get(), "Hello World 5"); } TEST(RosConsole, formatToString) { std::string str = ros::console::formatToString("Hello World %d", 5); EXPECT_STREQ(str.c_str(), "Hello World 5"); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::Time::init(); ROSCONSOLE_AUTOINIT; log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME)->removeAllAppenders(); log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getDebug()); log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME)->setLevel(log4cxx::Level::getDebug()); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/test/assertion_test.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define ROS_ASSERT_ENABLED #include "ros/assert.h" #include <gtest/gtest.h> void doAssert() { ROS_ASSERT(false); } void doBreak() { ROS_BREAK(); } void doAssertMessage() { ROS_ASSERT_MSG(false, "Testing %d %d %d", 1, 2, 3); } TEST(RosAssert, assert) { ROS_ASSERT(true); EXPECT_DEATH(doAssert(), "ASSERTION FAILED"); } TEST(RosAssert, breakpoint) { EXPECT_DEATH(doBreak(), "BREAKPOINT HIT"); } TEST(RosAssert, assertWithMessage) { ROS_ASSERT_MSG(true, "Testing %d %d %d", 1, 2, 3); EXPECT_DEATH(doAssertMessage(), "Testing 1 2 3"); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); ros::Time::init(); testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/cmake/rosconsole-extras.cmake.in
# ros_comm/tools/rosconsole/cmake/rosconsole-extras.cmake # force automatic escaping of preprocessor definitions cmake_policy(PUSH) cmake_policy(SET CMP0005 NEW) # add ROS_PACKAGE_NAME define required by the named logging macros add_definitions(-DROS_PACKAGE_NAME=\"${PROJECT_NAME}\") if("@ROSCONSOLE_BACKEND@" STREQUAL "log4cxx") # add ROSCONSOLE_BACKEND_LOG4CXX define required for backward compatible log4cxx symbols add_definitions(-DROSCONSOLE_BACKEND_LOG4CXX) endif() cmake_policy(POP)
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/config/rosconsole.config
# # rosconsole will find this file by default at $ROS_ROOT/config/rosconsole.config # # You can define your own by e.g. copying this file and setting # ROSCONSOLE_CONFIG_FILE (in your environment) to point to the new file # log4j.logger.ros=INFO log4j.logger.ros.roscpp.superdebug=WARN
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include/ros/console.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #ifndef ROSCONSOLE_ROSCONSOLE_H #define ROSCONSOLE_ROSCONSOLE_H #include "console_backend.h" #include <cstdio> #include <sstream> #include <ros/time.h> #include <cstdarg> #include <ros/macros.h> #include <map> #include <vector> #ifdef ROSCONSOLE_BACKEND_LOG4CXX #include "log4cxx/level.h" #endif // Import/export for windows dll's and visibility for gcc shared libraries. #ifdef ROS_BUILD_SHARED_LIBS // ros is being built around shared libraries #ifdef rosconsole_EXPORTS // we are building a shared lib/dll #define ROSCONSOLE_DECL ROS_HELPER_EXPORT #else // we are using shared lib/dll #define ROSCONSOLE_DECL ROS_HELPER_IMPORT #endif #else // ros is being built around static libraries #define ROSCONSOLE_DECL #endif #ifdef __GNUC__ #if __GNUC__ >= 3 #define ROSCONSOLE_PRINTF_ATTRIBUTE(a, b) __attribute__ ((__format__ (__printf__, a, b))); #endif #endif #ifndef ROSCONSOLE_PRINTF_ATTRIBUTE #define ROSCONSOLE_PRINTF_ATTRIBUTE(a, b) #endif namespace boost { template<typename T> class shared_array; } namespace ros { namespace console { ROSCONSOLE_DECL void shutdown(); #ifdef ROSCONSOLE_BACKEND_LOG4CXX extern ROSCONSOLE_DECL log4cxx::LevelPtr g_level_lookup[]; #endif extern ROSCONSOLE_DECL bool get_loggers(std::map<std::string, levels::Level>& loggers); extern ROSCONSOLE_DECL bool set_logger_level(const std::string& name, levels::Level level); /** * \brief Only exported because the macros need it. Do not use directly. */ extern ROSCONSOLE_DECL bool g_initialized; /** * \brief Only exported because the TopicManager need it. Do not use directly. */ extern ROSCONSOLE_DECL std::string g_last_error_message; class LogAppender { public: virtual void log(::ros::console::Level level, const char* str, const char* file, const char* function, int line) = 0; }; ROSCONSOLE_DECL void register_appender(LogAppender* appender); struct Token { /* * @param level * @param message * @param file * @param function * @param line */ virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int) = 0; }; typedef boost::shared_ptr<Token> TokenPtr; typedef std::vector<TokenPtr> V_Token; struct Formatter { void init(const char* fmt); void print(void* logger_handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line); std::string format_; V_Token tokens_; }; /** * \brief Only exported because the implementation need it. Do not use directly. */ extern ROSCONSOLE_DECL Formatter g_formatter; /** * \brief Don't call this directly. Performs any required initialization/configuration. Happens automatically when using the macro API. * * If you're going to be using log4cxx or any of the ::ros::console functions, and need the system to be initialized, use the * ROSCONSOLE_AUTOINIT macro. */ ROSCONSOLE_DECL void initialize(); class FilterBase; /** * \brief Don't call this directly. Use the ROS_LOG() macro instead. * @param level Logging level * @param file File this logging statement is from (usually generated with __FILE__) * @param line Line of code this logging statement is from (usually generated with __LINE__) * @param fmt Format string */ ROSCONSOLE_DECL void print(FilterBase* filter, void* logger, Level level, const char* file, int line, const char* function, const char* fmt, ...) ROSCONSOLE_PRINTF_ATTRIBUTE(7, 8); ROSCONSOLE_DECL void print(FilterBase* filter, void* logger, Level level, const std::stringstream& str, const char* file, int line, const char* function); struct ROSCONSOLE_DECL LogLocation; /** * \brief Registers a logging location with the system. * * This is used for the case where a logger's verbosity level changes, and we need to reset the enabled status of * all the logging statements. * @param loc The location to add */ ROSCONSOLE_DECL void registerLogLocation(LogLocation* loc); /** * \brief Tells the system that a logger's level has changed * * This must be called if a log4cxx::Logger's level has been changed in the middle of an application run. * Because of the way the static guard for enablement works, if a logger's level is changed and this * function is not called, only logging statements which are first hit *after* the change will be correct wrt * that logger. */ ROSCONSOLE_DECL void notifyLoggerLevelsChanged(); ROSCONSOLE_DECL void setFixedFilterToken(const std::string& key, const std::string& val); /** * \brief Parameter structure passed to FilterBase::isEnabled(...);. Includes both input and output parameters */ struct FilterParams { // input parameters const char* file; ///< [input] File the message came from int line; ///< [input] Line the message came from const char* function; ///< [input] Function the message came from const char* message; ///< [input] The formatted message that will be output // input/output parameters void* logger; ///< [input/output] Handle identifying logger that this message will be output to. If changed, uses the new logger Level level; ///< [input/output] Severity level. If changed, uses the new level // output parameters std::string out_message; ///< [output] If set, writes this message instead of the original }; /** * \brief Base-class for filters. Filters allow full user-defined control over whether or not a message should print. * The ROS_X_FILTER... macros provide the filtering functionality. * * Filters get a chance to veto the message from printing at two times: first before the message arguments are * evaluated and the message is formatted, and then once the message is formatted before it is printed. It is also possible * to change the message, logger and severity level at this stage (see the FilterParams struct for more details). * * When a ROS_X_FILTER... macro is called, here is the high-level view of how it uses the filter passed in: \verbatim if (<logging level is enabled> && filter->isEnabled()) { <format message> <fill out FilterParams> if (filter->isEnabled(params)) { <print message> } } \endverbatim */ class FilterBase { public: virtual ~FilterBase() {} /** * \brief Returns whether or not the log statement should be printed. Called before the log arguments are evaluated * and the message is formatted. */ inline virtual bool isEnabled() { return true; } /** * \brief Returns whether or not the log statement should be printed. Called once the message has been formatted, * and allows you to change the message, logger and severity level if necessary. */ inline virtual bool isEnabled(FilterParams&) { return true; } }; struct ROSCONSOLE_DECL LogLocation; /** * \brief Internal */ ROSCONSOLE_DECL void initializeLogLocation(LogLocation* loc, const std::string& name, Level level); /** * \brief Internal */ ROSCONSOLE_DECL void setLogLocationLevel(LogLocation* loc, Level level); /** * \brief Internal */ ROSCONSOLE_DECL void checkLogLocationEnabled(LogLocation* loc); /** * \brief Internal */ struct LogLocation { bool initialized_; bool logger_enabled_; ::ros::console::Level level_; void* logger_; }; ROSCONSOLE_DECL void vformatToBuffer(boost::shared_array<char>& buffer, size_t& buffer_size, const char* fmt, va_list args); ROSCONSOLE_DECL void formatToBuffer(boost::shared_array<char>& buffer, size_t& buffer_size, const char* fmt, ...); ROSCONSOLE_DECL std::string formatToString(const char* fmt, ...); } // namespace console } // namespace ros #ifdef WIN32 #define ROS_LIKELY(x) (x) #define ROS_UNLIKELY(x) (x) #else #define ROS_LIKELY(x) __builtin_expect((x),1) #define ROS_UNLIKELY(x) __builtin_expect((x),0) #endif #if defined(MSVC) #define __ROSCONSOLE_FUNCTION__ __FUNCSIG__ #elif defined(__GNUC__) #define __ROSCONSOLE_FUNCTION__ __PRETTY_FUNCTION__ #else #define __ROSCONSOLE_FUNCTION__ "" #endif #ifdef ROS_PACKAGE_NAME #define ROSCONSOLE_PACKAGE_NAME ROS_PACKAGE_NAME #else #define ROSCONSOLE_PACKAGE_NAME "unknown_package" #endif #define ROSCONSOLE_ROOT_LOGGER_NAME "ros" #define ROSCONSOLE_NAME_PREFIX ROSCONSOLE_ROOT_LOGGER_NAME "." ROSCONSOLE_PACKAGE_NAME #define ROSCONSOLE_DEFAULT_NAME ROSCONSOLE_NAME_PREFIX // These allow you to compile-out everything below a certain severity level if necessary #define ROSCONSOLE_SEVERITY_DEBUG 0 #define ROSCONSOLE_SEVERITY_INFO 1 #define ROSCONSOLE_SEVERITY_WARN 2 #define ROSCONSOLE_SEVERITY_ERROR 3 #define ROSCONSOLE_SEVERITY_FATAL 4 #define ROSCONSOLE_SEVERITY_NONE 5 /** * \def ROSCONSOLE_MIN_SEVERITY * * Define ROSCONSOLE_MIN_SEVERITY=ROSCONSOLE_SEVERITY_[DEBUG|INFO|WARN|ERROR|FATAL] in your build options to compile out anything below that severity */ #ifndef ROSCONSOLE_MIN_SEVERITY #define ROSCONSOLE_MIN_SEVERITY ROSCONSOLE_SEVERITY_DEBUG #endif /** * \def ROSCONSOLE_AUTOINIT * \brief Initializes the rosconsole library. Usually unnecessary to call directly. */ #define ROSCONSOLE_AUTOINIT \ do \ { \ if (ROS_UNLIKELY(!::ros::console::g_initialized)) \ { \ ::ros::console::initialize(); \ } \ } while(0) #define ROSCONSOLE_DEFINE_LOCATION(cond, level, name) \ ROSCONSOLE_AUTOINIT; \ static ::ros::console::LogLocation __rosconsole_define_location__loc = {false, false, ::ros::console::levels::Count, 0}; /* Initialized at compile-time */ \ if (ROS_UNLIKELY(!__rosconsole_define_location__loc.initialized_)) \ { \ initializeLogLocation(&__rosconsole_define_location__loc, name, level); \ } \ if (ROS_UNLIKELY(__rosconsole_define_location__loc.level_ != level)) \ { \ setLogLocationLevel(&__rosconsole_define_location__loc, level); \ checkLogLocationEnabled(&__rosconsole_define_location__loc); \ } \ bool __rosconsole_define_location__enabled = __rosconsole_define_location__loc.logger_enabled_ && (cond); #define ROSCONSOLE_PRINT_AT_LOCATION_WITH_FILTER(filter, ...) \ ::ros::console::print(filter, __rosconsole_define_location__loc.logger_, __rosconsole_define_location__loc.level_, __FILE__, __LINE__, __ROSCONSOLE_FUNCTION__, __VA_ARGS__) #define ROSCONSOLE_PRINT_AT_LOCATION(...) \ ROSCONSOLE_PRINT_AT_LOCATION_WITH_FILTER(0, __VA_ARGS__) // inside a macro which uses args use only well namespaced variable names in order to not overlay variables coming in via args #define ROSCONSOLE_PRINT_STREAM_AT_LOCATION_WITH_FILTER(filter, args) \ do \ { \ std::stringstream __rosconsole_print_stream_at_location_with_filter__ss__; \ __rosconsole_print_stream_at_location_with_filter__ss__ << args; \ ::ros::console::print(filter, __rosconsole_define_location__loc.logger_, __rosconsole_define_location__loc.level_, __rosconsole_print_stream_at_location_with_filter__ss__, __FILE__, __LINE__, __ROSCONSOLE_FUNCTION__); \ } while (0) #define ROSCONSOLE_PRINT_STREAM_AT_LOCATION(args) \ ROSCONSOLE_PRINT_STREAM_AT_LOCATION_WITH_FILTER(0, args) /** * \brief Log to a given named logger at a given verbosity level, only if a given condition has been met, with printf-style formatting * * \note The condition will only be evaluated if this logging statement is enabled * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_COND(cond, level, name, ...) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(cond, level, name); \ \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled)) \ { \ ROSCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only if a given condition has been met, with stream-style formatting * * \note The condition will only be evaluated if this logging statement is enabled * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_STREAM_COND(cond, level, name, args) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(cond, level, name); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled)) \ { \ ROSCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, only the first time it is hit when enabled, with printf-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_ONCE(level, name, ...) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ static bool hit = false; \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && ROS_UNLIKELY(!hit)) \ { \ hit = true; \ ROSCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) // inside a macro which uses args use only well namespaced variable names in order to not overlay variables coming in via args /** * \brief Log to a given named logger at a given verbosity level, only the first time it is hit when enabled, with printf-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_STREAM_ONCE(level, name, args) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ static bool __ros_log_stream_once__hit__ = false; \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && ROS_UNLIKELY(!__ros_log_stream_once__hit__)) \ { \ __ros_log_stream_once__hit__ = true; \ ROSCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define ROS_LOG_THROTTLE(rate, level, name, ...) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ static double last_hit = 0.0; \ ::ros::Time now = ::ros::Time::now(); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && ROS_UNLIKELY(last_hit + rate <= now.toSec())) \ { \ last_hit = now.toSec(); \ ROSCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) // inside a macro which uses args use only well namespaced variable names in order to not overlay variables coming in via args /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define ROS_LOG_STREAM_THROTTLE(rate, level, name, args) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ static double __ros_log_stream_throttle__last_hit__ = 0.0; \ ::ros::Time __ros_log_stream_throttle__now__ = ::ros::Time::now(); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && ROS_UNLIKELY(__ros_log_stream_throttle__last_hit__ + rate <= __ros_log_stream_throttle__now__.toSec())) \ { \ __ros_log_stream_throttle__last_hit__ = __ros_log_stream_throttle__now__.toSec(); \ ROSCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing, with printf-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at */ #define ROS_LOG_DELAYED_THROTTLE(rate, level, name, ...) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ ::ros::Time __ros_log_delayed_throttle__now__ = ::ros::Time::now(); \ static double __ros_log_delayed_throttle__last_hit__ = __ros_log_delayed_throttle__now__.toSec(); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && ROS_UNLIKELY(__ros_log_delayed_throttle__last_hit__ + rate <= __ros_log_delayed_throttle__now__.toSec())) \ { \ __ros_log_delayed_throttle__last_hit__ = __ros_log_delayed_throttle__now__.toSec(); \ ROSCONSOLE_PRINT_AT_LOCATION(__VA_ARGS__); \ } \ } while(0) // inside a macro which uses args use only well namespaced variable names in order to not overlay variables coming in via args /** * \brief Log to a given named logger at a given verbosity level, limited to a specific rate of printing and postponed first message * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. * \param rate The rate it should actually trigger at, and the delay before which no message will be shown. */ #define ROS_LOG_STREAM_DELAYED_THROTTLE(rate, level, name, args) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ ::ros::Time __ros_log_stream_delayed_throttle__now__ = ::ros::Time::now(); \ static double __ros_log_stream_delayed_throttle__last_hit__ = __ros_log_stream_delayed_throttle__now__.toSec(); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && ROS_UNLIKELY(__ros_log_stream_delayed_throttle__last_hit__ + rate <= __ros_log_stream_delayed_throttle__now__.toSec())) \ { \ __ros_log_stream_delayed_throttle__last_hit__ = __ros_log_stream_delayed_throttle__now__.toSec(); \ ROSCONSOLE_PRINT_STREAM_AT_LOCATION(args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with user-defined filtering, with printf-style formatting * * \param filter pointer to the filter to be used * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_FILTER(filter, level, name, ...) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && (filter)->isEnabled()) \ { \ ROSCONSOLE_PRINT_AT_LOCATION_WITH_FILTER(filter, __VA_ARGS__); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with user-defined filtering, with stream-style formatting * * \param cond Boolean condition to be evaluated * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_STREAM_FILTER(filter, level, name, args) \ do \ { \ ROSCONSOLE_DEFINE_LOCATION(true, level, name); \ if (ROS_UNLIKELY(__rosconsole_define_location__enabled) && (filter)->isEnabled()) \ { \ ROSCONSOLE_PRINT_STREAM_AT_LOCATION_WITH_FILTER(filter, args); \ } \ } while(0) /** * \brief Log to a given named logger at a given verbosity level, with printf-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG(level, name, ...) ROS_LOG_COND(true, level, name, __VA_ARGS__) /** * \brief Log to a given named logger at a given verbosity level, with stream-style formatting * * \param level One of the levels specified in ::ros::console::levels::Level * \param name Name of the logger. Note that this is the fully qualified name, and does NOT include "ros.<package_name>". Use ROSCONSOLE_DEFAULT_NAME if you would like to use the default name. */ #define ROS_LOG_STREAM(level, name, args) ROS_LOG_STREAM_COND(true, level, name, args) #include "rosconsole/macros_generated.h" #endif // ROSCONSOLE_ROSCONSOLE_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include/ros/static_assert.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #ifndef ROSCONSOLE_STATIC_ASSERT_H #define ROSCONSOLE_STATIC_ASSERT_H // boost's static assert provides better errors messages in the failure case when using // in templated situations #include <boost/static_assert.hpp> /** * \def ROS_COMPILE_ASSERT(cond) * \brief Compile-time assert. * * Only works with compile time statements, ie: @verbatim struct A { uint32_t a; }; ROS_COMPILE_ASSERT(sizeof(A) == 4); @endverbatim */ #define ROS_COMPILE_ASSERT(cond) BOOST_STATIC_ASSERT(cond) /** * \def ROS_STATIC_ASSERT(cond) * \brief Compile-time assert. * * Only works with compile time statements, ie: @verbatim struct A { uint32_t a; }; ROS_STATIC_ASSERT(sizeof(A) == 4); @endverbatim */ #define ROS_STATIC_ASSERT(cond) BOOST_STATIC_ASSERT(cond) #endif // ROSCONSOLE_STATIC_ASSERT_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include/ros/console_backend.h
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROSCONSOLE_CONSOLE_BACKEND_H #define ROSCONSOLE_CONSOLE_BACKEND_H namespace ros { namespace console { namespace levels { enum Level { Debug, Info, Warn, Error, Fatal, Count }; } typedef levels::Level Level; namespace backend { void notifyLoggerLevelsChanged(); extern void (*function_notifyLoggerLevelsChanged)(); void print(void* logger_handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line); extern void (*function_print)(void*, ::ros::console::Level, const char*, const char*, const char*, int); } // namespace backend } // namespace console } // namespace ros #endif // ROSCONSOLE_CONSOLE_BACKEND_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include/ros/assert.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #ifndef ROSCONSOLE_ROSASSERT_H #define ROSCONSOLE_ROSASSERT_H #include "ros/console.h" #include "ros/static_assert.h" /** \file */ /** \def ROS_ASSERT(cond) * \brief Asserts that the provided condition evaluates to true. * * If it is false, program execution will abort, with an informative * statement about which assertion failed, in what file. Use ROS_ASSERT * instead of assert() itself. * * If running inside a debugger, ROS_ASSERT will allow you to step past the assertion. */ /** \def ROS_ASSERT_MSG(cond, ...) * \brief Asserts that the provided condition evaluates to true. * * If it is false, program execution will abort, with an informative * statement about which assertion failed, in what file, and it will print out * a printf-style message you define. Example usage: @verbatim ROS_ASSERT_MSG(x > 0, "Uh oh, x went negative. Value = %d", x); @endverbatim * * If running inside a debugger, ROS_ASSERT will allow you to step past the assertion. */ /** * \def ROS_ASSERT_CMD() * \brief Runs a command if the provided condition is false * * For example: \verbatim ROS_ASSERT_CMD(x > 0, handleError(...)); \endverbatim */ /** \def ROS_BREAK() * \brief Aborts program execution. * * Aborts program execution with an informative message stating what file and * line it was called from. Use ROS_BREAK instead of calling assert(0) or * ROS_ASSERT(0). * * If running inside a debugger, ROS_BREAK will allow you to step past the breakpoint. */ /** \def ROS_ISSUE_BREAK() * \brief Always issues a breakpoint instruction. * * This define is mostly for internal use, but is useful if you want to simply issue a break * instruction in a cross-platform way. * * Currently implemented for Windows (any platform), powerpc64, and x86 */ #include <ros/platform.h> #ifdef WIN32 # if defined (__MINGW32__) # define ROS_ISSUE_BREAK() DebugBreak(); # else // MSVC # define ROS_ISSUE_BREAK() __debugbreak(); # endif #elif defined(__powerpc64__) # define ROS_ISSUE_BREAK() asm volatile ("tw 31,1,1"); #elif defined(__i386__) || defined(__ia64__) || defined(__x86_64__) # define ROS_ISSUE_BREAK() asm("int $3"); #else # include <stdlib.h> # define ROS_ISSUE_BREAK() abort(); #endif #ifndef NDEBUG #ifndef ROS_ASSERT_ENABLED #define ROS_ASSERT_ENABLED #endif #endif #ifdef ROS_ASSERT_ENABLED #define ROS_BREAK() \ do { \ ROS_FATAL("BREAKPOINT HIT\n\tfile = %s\n\tline=%d\n", __FILE__, __LINE__); \ ROS_ISSUE_BREAK() \ } while (0) #define ROS_ASSERT(cond) \ do { \ if (!(cond)) { \ ROS_FATAL("ASSERTION FAILED\n\tfile = %s\n\tline = %d\n\tcond = %s\n", __FILE__, __LINE__, #cond); \ ROS_ISSUE_BREAK() \ } \ } while (0) #define ROS_ASSERT_MSG(cond, ...) \ do { \ if (!(cond)) { \ ROS_FATAL("ASSERTION FAILED\n\tfile = %s\n\tline = %d\n\tcond = %s\n\tmessage = ", __FILE__, __LINE__, #cond); \ ROS_FATAL(__VA_ARGS__); \ ROS_FATAL("\n"); \ ROS_ISSUE_BREAK(); \ } \ } while (0) #define ROS_ASSERT_CMD(cond, cmd) \ do { \ if (!(cond)) { \ cmd; \ } \ } while (0) #else #define ROS_BREAK() #define ROS_ASSERT(cond) #define ROS_ASSERT_MSG(cond, ...) #define ROS_ASSERT_CMD(cond, cmd) #endif #endif // ROSCONSOLE_ROSASSERT_H
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/include/rosconsole/macros_generated.h
// !!!!!!!!!!!!!!!!!!!!!!! This is a generated file, do not edit manually /* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if (ROSCONSOLE_MIN_SEVERITY > ROSCONSOLE_SEVERITY_DEBUG) #define ROS_DEBUG(...) #define ROS_DEBUG_STREAM(args) #define ROS_DEBUG_NAMED(name, ...) #define ROS_DEBUG_STREAM_NAMED(name, args) #define ROS_DEBUG_COND(cond, ...) #define ROS_DEBUG_STREAM_COND(cond, args) #define ROS_DEBUG_COND_NAMED(cond, name, ...) #define ROS_DEBUG_STREAM_COND_NAMED(cond, name, args) #define ROS_DEBUG_ONCE(...) #define ROS_DEBUG_STREAM_ONCE(args) #define ROS_DEBUG_ONCE_NAMED(name, ...) #define ROS_DEBUG_STREAM_ONCE_NAMED(name, args) #define ROS_DEBUG_THROTTLE(rate, ...) #define ROS_DEBUG_STREAM_THROTTLE(rate, args) #define ROS_DEBUG_THROTTLE_NAMED(rate, name, ...) #define ROS_DEBUG_STREAM_THROTTLE_NAMED(rate, name, args) #define ROS_DEBUG_DELAYED_THROTTLE(rate, ...) #define ROS_DEBUG_STREAM_DELAYED_THROTTLE(rate, args) #define ROS_DEBUG_DELAYED_THROTTLE_NAMED(rate, name, ...) #define ROS_DEBUG_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) #define ROS_DEBUG_FILTER(filter, ...) #define ROS_DEBUG_STREAM_FILTER(filter, args) #define ROS_DEBUG_FILTER_NAMED(filter, name, ...) #define ROS_DEBUG_STREAM_FILTER_NAMED(filter, name, args) #else #define ROS_DEBUG(...) ROS_LOG(::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_DEBUG_STREAM(args) ROS_LOG_STREAM(::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_DEBUG_NAMED(name, ...) ROS_LOG(::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_DEBUG_STREAM_NAMED(name, args) ROS_LOG_STREAM(::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_DEBUG_COND(cond, ...) ROS_LOG_COND(cond, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_DEBUG_STREAM_COND(cond, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_DEBUG_COND_NAMED(cond, name, ...) ROS_LOG_COND(cond, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_DEBUG_STREAM_COND_NAMED(cond, name, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_DEBUG_ONCE(...) ROS_LOG_ONCE(::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_DEBUG_STREAM_ONCE(args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_DEBUG_ONCE_NAMED(name, ...) ROS_LOG_ONCE(::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_DEBUG_STREAM_ONCE_NAMED(name, args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_DEBUG_THROTTLE(rate, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_DEBUG_STREAM_THROTTLE(rate, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_DEBUG_THROTTLE_NAMED(rate, name, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_DEBUG_STREAM_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_DEBUG_DELAYED_THROTTLE(rate, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_DEBUG_STREAM_DELAYED_THROTTLE(rate, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_DEBUG_DELAYED_THROTTLE_NAMED(rate, name, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_DEBUG_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_DEBUG_FILTER(filter, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_DEBUG_STREAM_FILTER(filter, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Debug, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_DEBUG_FILTER_NAMED(filter, name, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_DEBUG_STREAM_FILTER_NAMED(filter, name, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Debug, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #endif #if (ROSCONSOLE_MIN_SEVERITY > ROSCONSOLE_SEVERITY_INFO) #define ROS_INFO(...) #define ROS_INFO_STREAM(args) #define ROS_INFO_NAMED(name, ...) #define ROS_INFO_STREAM_NAMED(name, args) #define ROS_INFO_COND(cond, ...) #define ROS_INFO_STREAM_COND(cond, args) #define ROS_INFO_COND_NAMED(cond, name, ...) #define ROS_INFO_STREAM_COND_NAMED(cond, name, args) #define ROS_INFO_ONCE(...) #define ROS_INFO_STREAM_ONCE(args) #define ROS_INFO_ONCE_NAMED(name, ...) #define ROS_INFO_STREAM_ONCE_NAMED(name, args) #define ROS_INFO_THROTTLE(rate, ...) #define ROS_INFO_STREAM_THROTTLE(rate, args) #define ROS_INFO_THROTTLE_NAMED(rate, name, ...) #define ROS_INFO_STREAM_THROTTLE_NAMED(rate, name, args) #define ROS_INFO_DELAYED_THROTTLE(rate, ...) #define ROS_INFO_STREAM_DELAYED_THROTTLE(rate, args) #define ROS_INFO_DELAYED_THROTTLE_NAMED(rate, name, ...) #define ROS_INFO_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) #define ROS_INFO_FILTER(filter, ...) #define ROS_INFO_STREAM_FILTER(filter, args) #define ROS_INFO_FILTER_NAMED(filter, name, ...) #define ROS_INFO_STREAM_FILTER_NAMED(filter, name, args) #else #define ROS_INFO(...) ROS_LOG(::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_INFO_STREAM(args) ROS_LOG_STREAM(::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_INFO_NAMED(name, ...) ROS_LOG(::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_INFO_STREAM_NAMED(name, args) ROS_LOG_STREAM(::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_INFO_COND(cond, ...) ROS_LOG_COND(cond, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_INFO_STREAM_COND(cond, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_INFO_COND_NAMED(cond, name, ...) ROS_LOG_COND(cond, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_INFO_STREAM_COND_NAMED(cond, name, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_INFO_ONCE(...) ROS_LOG_ONCE(::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_INFO_STREAM_ONCE(args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_INFO_ONCE_NAMED(name, ...) ROS_LOG_ONCE(::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_INFO_STREAM_ONCE_NAMED(name, args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_INFO_THROTTLE(rate, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_INFO_STREAM_THROTTLE(rate, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_INFO_THROTTLE_NAMED(rate, name, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_INFO_STREAM_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_INFO_DELAYED_THROTTLE(rate, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_INFO_STREAM_DELAYED_THROTTLE(rate, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_INFO_DELAYED_THROTTLE_NAMED(rate, name, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_INFO_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_INFO_FILTER(filter, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_INFO_STREAM_FILTER(filter, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Info, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_INFO_FILTER_NAMED(filter, name, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_INFO_STREAM_FILTER_NAMED(filter, name, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Info, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #endif #if (ROSCONSOLE_MIN_SEVERITY > ROSCONSOLE_SEVERITY_WARN) #define ROS_WARN(...) #define ROS_WARN_STREAM(args) #define ROS_WARN_NAMED(name, ...) #define ROS_WARN_STREAM_NAMED(name, args) #define ROS_WARN_COND(cond, ...) #define ROS_WARN_STREAM_COND(cond, args) #define ROS_WARN_COND_NAMED(cond, name, ...) #define ROS_WARN_STREAM_COND_NAMED(cond, name, args) #define ROS_WARN_ONCE(...) #define ROS_WARN_STREAM_ONCE(args) #define ROS_WARN_ONCE_NAMED(name, ...) #define ROS_WARN_STREAM_ONCE_NAMED(name, args) #define ROS_WARN_THROTTLE(rate, ...) #define ROS_WARN_STREAM_THROTTLE(rate, args) #define ROS_WARN_THROTTLE_NAMED(rate, name, ...) #define ROS_WARN_STREAM_THROTTLE_NAMED(rate, name, args) #define ROS_WARN_DELAYED_THROTTLE(rate, ...) #define ROS_WARN_STREAM_DELAYED_THROTTLE(rate, args) #define ROS_WARN_DELAYED_THROTTLE_NAMED(rate, name, ...) #define ROS_WARN_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) #define ROS_WARN_FILTER(filter, ...) #define ROS_WARN_STREAM_FILTER(filter, args) #define ROS_WARN_FILTER_NAMED(filter, name, ...) #define ROS_WARN_STREAM_FILTER_NAMED(filter, name, args) #else #define ROS_WARN(...) ROS_LOG(::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_WARN_STREAM(args) ROS_LOG_STREAM(::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_WARN_NAMED(name, ...) ROS_LOG(::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_WARN_STREAM_NAMED(name, args) ROS_LOG_STREAM(::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_WARN_COND(cond, ...) ROS_LOG_COND(cond, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_WARN_STREAM_COND(cond, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_WARN_COND_NAMED(cond, name, ...) ROS_LOG_COND(cond, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_WARN_STREAM_COND_NAMED(cond, name, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_WARN_ONCE(...) ROS_LOG_ONCE(::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_WARN_STREAM_ONCE(args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_WARN_ONCE_NAMED(name, ...) ROS_LOG_ONCE(::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_WARN_STREAM_ONCE_NAMED(name, args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_WARN_THROTTLE(rate, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_WARN_STREAM_THROTTLE(rate, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_WARN_THROTTLE_NAMED(rate, name, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_WARN_STREAM_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_WARN_DELAYED_THROTTLE(rate, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_WARN_STREAM_DELAYED_THROTTLE(rate, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_WARN_DELAYED_THROTTLE_NAMED(rate, name, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_WARN_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_WARN_FILTER(filter, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_WARN_STREAM_FILTER(filter, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Warn, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_WARN_FILTER_NAMED(filter, name, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_WARN_STREAM_FILTER_NAMED(filter, name, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Warn, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #endif #if (ROSCONSOLE_MIN_SEVERITY > ROSCONSOLE_SEVERITY_ERROR) #define ROS_ERROR(...) #define ROS_ERROR_STREAM(args) #define ROS_ERROR_NAMED(name, ...) #define ROS_ERROR_STREAM_NAMED(name, args) #define ROS_ERROR_COND(cond, ...) #define ROS_ERROR_STREAM_COND(cond, args) #define ROS_ERROR_COND_NAMED(cond, name, ...) #define ROS_ERROR_STREAM_COND_NAMED(cond, name, args) #define ROS_ERROR_ONCE(...) #define ROS_ERROR_STREAM_ONCE(args) #define ROS_ERROR_ONCE_NAMED(name, ...) #define ROS_ERROR_STREAM_ONCE_NAMED(name, args) #define ROS_ERROR_THROTTLE(rate, ...) #define ROS_ERROR_STREAM_THROTTLE(rate, args) #define ROS_ERROR_THROTTLE_NAMED(rate, name, ...) #define ROS_ERROR_STREAM_THROTTLE_NAMED(rate, name, args) #define ROS_ERROR_DELAYED_THROTTLE(rate, ...) #define ROS_ERROR_STREAM_DELAYED_THROTTLE(rate, args) #define ROS_ERROR_DELAYED_THROTTLE_NAMED(rate, name, ...) #define ROS_ERROR_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) #define ROS_ERROR_FILTER(filter, ...) #define ROS_ERROR_STREAM_FILTER(filter, args) #define ROS_ERROR_FILTER_NAMED(filter, name, ...) #define ROS_ERROR_STREAM_FILTER_NAMED(filter, name, args) #else #define ROS_ERROR(...) ROS_LOG(::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_ERROR_STREAM(args) ROS_LOG_STREAM(::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_ERROR_NAMED(name, ...) ROS_LOG(::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_ERROR_STREAM_NAMED(name, args) ROS_LOG_STREAM(::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_ERROR_COND(cond, ...) ROS_LOG_COND(cond, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_ERROR_STREAM_COND(cond, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_ERROR_COND_NAMED(cond, name, ...) ROS_LOG_COND(cond, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_ERROR_STREAM_COND_NAMED(cond, name, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_ERROR_ONCE(...) ROS_LOG_ONCE(::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_ERROR_STREAM_ONCE(args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_ERROR_ONCE_NAMED(name, ...) ROS_LOG_ONCE(::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_ERROR_STREAM_ONCE_NAMED(name, args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_ERROR_THROTTLE(rate, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_ERROR_STREAM_THROTTLE(rate, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_ERROR_THROTTLE_NAMED(rate, name, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_ERROR_STREAM_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_ERROR_DELAYED_THROTTLE(rate, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_ERROR_STREAM_DELAYED_THROTTLE(rate, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_ERROR_DELAYED_THROTTLE_NAMED(rate, name, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_ERROR_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_ERROR_FILTER(filter, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_ERROR_STREAM_FILTER(filter, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Error, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_ERROR_FILTER_NAMED(filter, name, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_ERROR_STREAM_FILTER_NAMED(filter, name, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Error, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #endif #if (ROSCONSOLE_MIN_SEVERITY > ROSCONSOLE_SEVERITY_FATAL) #define ROS_FATAL(...) #define ROS_FATAL_STREAM(args) #define ROS_FATAL_NAMED(name, ...) #define ROS_FATAL_STREAM_NAMED(name, args) #define ROS_FATAL_COND(cond, ...) #define ROS_FATAL_STREAM_COND(cond, args) #define ROS_FATAL_COND_NAMED(cond, name, ...) #define ROS_FATAL_STREAM_COND_NAMED(cond, name, args) #define ROS_FATAL_ONCE(...) #define ROS_FATAL_STREAM_ONCE(args) #define ROS_FATAL_ONCE_NAMED(name, ...) #define ROS_FATAL_STREAM_ONCE_NAMED(name, args) #define ROS_FATAL_THROTTLE(rate, ...) #define ROS_FATAL_STREAM_THROTTLE(rate, args) #define ROS_FATAL_THROTTLE_NAMED(rate, name, ...) #define ROS_FATAL_STREAM_THROTTLE_NAMED(rate, name, args) #define ROS_FATAL_DELAYED_THROTTLE(rate, ...) #define ROS_FATAL_STREAM_DELAYED_THROTTLE(rate, args) #define ROS_FATAL_DELAYED_THROTTLE_NAMED(rate, name, ...) #define ROS_FATAL_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) #define ROS_FATAL_FILTER(filter, ...) #define ROS_FATAL_STREAM_FILTER(filter, args) #define ROS_FATAL_FILTER_NAMED(filter, name, ...) #define ROS_FATAL_STREAM_FILTER_NAMED(filter, name, args) #else #define ROS_FATAL(...) ROS_LOG(::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_FATAL_STREAM(args) ROS_LOG_STREAM(::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_FATAL_NAMED(name, ...) ROS_LOG(::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_FATAL_STREAM_NAMED(name, args) ROS_LOG_STREAM(::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_FATAL_COND(cond, ...) ROS_LOG_COND(cond, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_FATAL_STREAM_COND(cond, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_FATAL_COND_NAMED(cond, name, ...) ROS_LOG_COND(cond, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_FATAL_STREAM_COND_NAMED(cond, name, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_FATAL_ONCE(...) ROS_LOG_ONCE(::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_FATAL_STREAM_ONCE(args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_FATAL_ONCE_NAMED(name, ...) ROS_LOG_ONCE(::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_FATAL_STREAM_ONCE_NAMED(name, args) ROS_LOG_STREAM_ONCE(::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_FATAL_THROTTLE(rate, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_FATAL_STREAM_THROTTLE(rate, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_FATAL_THROTTLE_NAMED(rate, name, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_FATAL_STREAM_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_FATAL_DELAYED_THROTTLE(rate, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_FATAL_STREAM_DELAYED_THROTTLE(rate, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_FATAL_DELAYED_THROTTLE_NAMED(rate, name, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_FATAL_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #define ROS_FATAL_FILTER(filter, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__) #define ROS_FATAL_STREAM_FILTER(filter, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Fatal, ROSCONSOLE_DEFAULT_NAME, args) #define ROS_FATAL_FILTER_NAMED(filter, name, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__) #define ROS_FATAL_STREAM_FILTER_NAMED(filter, name, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::Fatal, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args) #endif
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/env-hooks/10.rosconsole.bat.develspace.em
REM generated from rosconsole/env-hooks/10.rosconsole.bat.develspace.em set ROSCONSOLE_CONFIG_FILE=@(CMAKE_CURRENT_SOURCE_DIR)/config/rosconsole.config
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/env-hooks/10.rosconsole.sh.develspace.em
# generated from rosconsole/env-hooks/10.rosconsole.sh.develspace.em export ROSCONSOLE_CONFIG_FILE="@(CMAKE_CURRENT_SOURCE_DIR)/config/rosconsole.config"
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/examples/example.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include "ros/console.h" #include <log4cxx/logger.h> void print(ros::console::Level level, const std::string& s) { ROS_LOG(level, ROSCONSOLE_DEFAULT_NAME, "%s", s.c_str()); } int main(int /*argc*/, char** /*argv*/) { // This needs to happen before we start fooling around with logger levels. Otherwise the level we set may be overwritten by // a configuration file ROSCONSOLE_AUTOINIT; log4cxx::LoggerPtr my_logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME); // Set the logger for this package to output all statements my_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Debug]); // All these should print ROS_DEBUG("This is a debug statement, and should print"); ROS_INFO("This is an info statement, and should print"); ROS_WARN("This is a warn statement, and should print"); ROS_ERROR("This is an error statement, and should print"); ROS_FATAL("This is a fatal statement, and should print"); // This should also print print(ros::console::levels::Debug, "Hello, this should print"); my_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Error]); // This will STILL print, because the logger's enabled state has been cached print(ros::console::levels::Debug, "Hello, this will also print"); // Calling notifyLoggerLevelsChanged() will force a reevaluation of which logging statements are enabled ros::console::notifyLoggerLevelsChanged(); // Which will cause this to not print print(ros::console::levels::Debug, "Hello, this will NOT print"); log4cxx::LoggerPtr ros_logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME); my_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Debug]); ros_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Error]); ROS_DEBUG("This will still print, because the child logger's level overrides its ancestor loggers' levels"); log4cxx::LoggerPtr test_logger = log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME".test"); test_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Error]); ROS_INFO_NAMED("test", "This will not print, because the ros.rosconsole.test logger has been set to Error verbosity"); test_logger->setLevel(ros::console::g_level_lookup[ros::console::levels::Debug]); ROS_INFO_NAMED("test", "Now everything sent to the ros.rosconsole.test logger will be printed (including this)"); return 0; }
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/scripts/generate_macros.py
#!/usr/bin/python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import sys def add_macro(f, caps_name, enum_name): f.write('#if (ROSCONSOLE_MIN_SEVERITY > ROSCONSOLE_SEVERITY_%s)\n' %(caps_name)) f.write('#define ROS_%s(...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM(args)\n' %(caps_name)) f.write('#define ROS_%s_NAMED(name, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_NAMED(name, args)\n' %(caps_name)) f.write('#define ROS_%s_COND(cond, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_COND(cond, args)\n' %(caps_name)) f.write('#define ROS_%s_COND_NAMED(cond, name, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_COND_NAMED(cond, name, args)\n' %(caps_name)) f.write('#define ROS_%s_ONCE(...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_ONCE(args)\n' %(caps_name)) f.write('#define ROS_%s_ONCE_NAMED(name, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_ONCE_NAMED(name, args)\n' %(caps_name)) f.write('#define ROS_%s_THROTTLE(rate, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_THROTTLE(rate, args)\n' %(caps_name)) f.write('#define ROS_%s_THROTTLE_NAMED(rate, name, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_THROTTLE_NAMED(rate, name, args)\n' %(caps_name)) f.write('#define ROS_%s_DELAYED_THROTTLE(rate, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_DELAYED_THROTTLE(rate, args)\n' %(caps_name)) f.write('#define ROS_%s_DELAYED_THROTTLE_NAMED(rate, name, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args)\n' %(caps_name)) f.write('#define ROS_%s_FILTER(filter, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_FILTER(filter, args)\n' %(caps_name)) f.write('#define ROS_%s_FILTER_NAMED(filter, name, ...)\n' %(caps_name)) f.write('#define ROS_%s_STREAM_FILTER_NAMED(filter, name, args)\n' %(caps_name)) f.write('#else\n') f.write('#define ROS_%s(...) ROS_LOG(::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM(args) ROS_LOG_STREAM(::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_NAMED(name, ...) ROS_LOG(::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_NAMED(name, args) ROS_LOG_STREAM(::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_COND(cond, ...) ROS_LOG_COND(cond, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_COND(cond, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_COND_NAMED(cond, name, ...) ROS_LOG_COND(cond, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_COND_NAMED(cond, name, args) ROS_LOG_STREAM_COND(cond, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_ONCE(...) ROS_LOG_ONCE(::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_ONCE(args) ROS_LOG_STREAM_ONCE(::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_ONCE_NAMED(name, ...) ROS_LOG_ONCE(::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_ONCE_NAMED(name, args) ROS_LOG_STREAM_ONCE(::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_THROTTLE(rate, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_THROTTLE(rate, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_THROTTLE_NAMED(rate, name, ...) ROS_LOG_THROTTLE(rate, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_THROTTLE(rate, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_DELAYED_THROTTLE(rate, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_DELAYED_THROTTLE(rate, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_DELAYED_THROTTLE_NAMED(rate, name, ...) ROS_LOG_DELAYED_THROTTLE(rate, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_DELAYED_THROTTLE_NAMED(rate, name, args) ROS_LOG_STREAM_DELAYED_THROTTLE(rate, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_FILTER(filter, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_FILTER(filter, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::%s, ROSCONSOLE_DEFAULT_NAME, args)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_FILTER_NAMED(filter, name, ...) ROS_LOG_FILTER(filter, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, __VA_ARGS__)\n' %(caps_name, enum_name)) f.write('#define ROS_%s_STREAM_FILTER_NAMED(filter, name, args) ROS_LOG_STREAM_FILTER(filter, ::ros::console::levels::%s, std::string(ROSCONSOLE_NAME_PREFIX) + "." + name, args)\n' %(caps_name, enum_name)) f.write('#endif\n\n') f = open('%s/../include/rosconsole/macros_generated.h' %(os.path.dirname(__file__)), 'w') f.write("// !!!!!!!!!!!!!!!!!!!!!!! This is a generated file, do not edit manually\n\n") f.write('/*\n') f.write(' * Copyright (c) 2008, Willow Garage, Inc.\n') f.write(' * All rights reserved.\n') f.write(' *\n') f.write(' * Redistribution and use in source and binary forms, with or without\n') f.write(' * modification, are permitted provided that the following conditions are met:\n') f.write(' *\n') f.write(' * * Redistributions of source code must retain the above copyright\n') f.write(' * notice, this list of conditions and the following disclaimer.\n') f.write(' * * Redistributions in binary form must reproduce the above copyright\n') f.write(' * notice, this list of conditions and the following disclaimer in the\n') f.write(' * documentation and/or other materials provided with the distribution.\n') f.write(' * * Neither the name of Willow Garage, Inc. nor the names of its\n') f.write(' * contributors may be used to endorse or promote products derived from\n') f.write(' * this software without specific prior written permission.\n') f.write(' *\n') f.write(' * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n') f.write(' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n') f.write(' * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n') f.write(' * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n') f.write(' * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n') f.write(' * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n') f.write(' * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n') f.write(' * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n') f.write(' * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n') f.write(' * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n') f.write(' * POSSIBILITY OF SUCH DAMAGE.\n') f.write(' */\n\n') add_macro(f, "DEBUG", "Debug") add_macro(f, "INFO", "Info") add_macro(f, "WARN", "Warn") add_macro(f, "ERROR", "Error") add_macro(f, "FATAL", "Fatal")
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/scripts/generate_speed_test.py
#!/usr/bin/python # Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import sys f = open('%s/../test/speed_test.cpp' % (os.path.dirname(__file__)), 'w') f.write("// !!!!!!!!!!!!!!!!!!!!!!! This is a generated file, do not edit manually\n\n") f.write('/*\n') f.write(' * Copyright (c) 2008, Willow Garage, Inc.\n') f.write(' * All rights reserved.\n') f.write(' *\n') f.write(' * Redistribution and use in source and binary forms, with or without\n') f.write(' * modification, are permitted provided that the following conditions are met:\n') f.write(' *\n') f.write(' * * Redistributions of source code must retain the above copyright\n') f.write(' * notice, this list of conditions and the following disclaimer.\n') f.write(' * * Redistributions in binary form must reproduce the above copyright\n') f.write(' * notice, this list of conditions and the following disclaimer in the\n') f.write(' * documentation and/or other materials provided with the distribution.\n') f.write(' * * Neither the name of Willow Garage, Inc. nor the names of its\n') f.write(' * contributors may be used to endorse or promote products derived from\n') f.write(' * this software without specific prior written permission.\n') f.write(' *\n') f.write(' * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n') f.write(' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n') f.write(' * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n') f.write(' * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n') f.write(' * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n') f.write(' * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n') f.write(' * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n') f.write(' * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n') f.write(' * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n') f.write(' * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n') f.write(' * POSSIBILITY OF SUCH DAMAGE.\n') f.write(' */\n\n') f.write('#include "ros/console.h"\n') f.write('#include "log4cxx/appenderskeleton.h"\n') #for i in range(0,int(sys.argv[1])): # f.write('void info%s(int i) { ROS_INFO("Info%s: %%d", i); }\n' %(i,i)) # f.write('void warn%s(int i) { ROS_WARN("Warn%s: %%d", i); }\n' %(i,i)) # f.write('void error%s(int i) { ROS_ERROR("Error%s: %%d", i); }\n' %(i,i)) # f.write('void debug%s(int i) { ROS_DEBUG("Debug%s: %%d", i); }\n' %(i,i)) # f.write('void errorr%s(int i) { ROS_ERROR("Error2%s: %%d", i); }\n' %(i,i)) f.write('class NullAppender : public log4cxx::AppenderSkeleton {\n') f.write('protected:\n') f.write('virtual void append(const log4cxx::spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool){printf("blah\\n");}\n') f.write('virtual void close() {}\n') f.write('virtual bool requiresLayout() const { return false; } };\n') f.write('int main(int argc, char** argv)\n{\n') f.write('ROSCONSOLE_AUTOINIT; \nlog4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME)->removeAllAppenders();\n') f.write('log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->addAppender(new NullAppender);\n') f.write('log4cxx::Logger::getLogger(ROSCONSOLE_DEFAULT_NAME)->setLevel(log4cxx::Level::getFatal());\n') f.write('for (int i = 0;i < %s; ++i)\n{\n' %(sys.argv[2])) for i in range(0,int(sys.argv[1])): #f.write('info%s(i);\n' %(i)) #f.write('warn%s(i);\n' %(i)) #f.write('error%s(i);\n' %(i)) #f.write('debug%s(i);\n' %(i)) #f.write('errorr%s(i);\n' %(i)) f.write('ROS_INFO("test");') f.write('ROS_WARN("test");') f.write('ROS_ERROR("test");') f.write('ROS_DEBUG("test");') f.write('ROS_ERROR("test");') f.write('}\n') f.write('}\n')
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole/rosconsole.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #if defined(__APPLE__) && defined(__GNUC__) && defined(__llvm__) && !defined(__clang__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 2) #error This code is known to provoke a compiler crash with llvm-gcc 4.2. You will have better luck with clang++. See code.ros.org/trac/ros/ticket/3626 #endif #include "ros/console.h" #include "ros/assert.h" #include <ros/time.h> #include <boost/thread.hpp> #include <boost/shared_array.hpp> #include <boost/regex.hpp> #include <boost/make_shared.hpp> #include <cstdarg> #include <cstdlib> #include <cstdio> #include <memory> #include <cstring> #include <stdexcept> // declare interface for rosconsole implementations namespace ros { namespace console { namespace impl { void initialize(); void shutdown(); void register_appender(LogAppender* appender); void print(void* handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line); bool isEnabledFor(void* handle, ::ros::console::Level level); void* getHandle(const std::string& name); std::string getName(void* handle); bool get_loggers(std::map<std::string, levels::Level>& loggers); bool set_logger_level(const std::string& name, levels::Level level); } // namespace impl bool g_initialized = false; bool g_shutting_down = false; boost::mutex g_init_mutex; #ifdef ROSCONSOLE_BACKEND_LOG4CXX log4cxx::LevelPtr g_level_lookup[levels::Count] = { log4cxx::Level::getDebug(), log4cxx::Level::getInfo(), log4cxx::Level::getWarn(), log4cxx::Level::getError(), log4cxx::Level::getFatal(), }; #endif std::string g_last_error_message = "Unknown Error"; #ifdef WIN32 #define COLOR_NORMAL "" #define COLOR_RED "" #define COLOR_GREEN "" #define COLOR_YELLOW "" #else #define COLOR_NORMAL "\033[0m" #define COLOR_RED "\033[31m" #define COLOR_GREEN "\033[32m" #define COLOR_YELLOW "\033[33m" #endif const char* g_format_string = "[${severity}] [${time}]: ${message}"; typedef std::map<std::string, std::string> M_string; M_string g_extra_fixed_tokens; void setFixedFilterToken(const std::string& key, const std::string& val) { g_extra_fixed_tokens[key] = val; } struct FixedToken : public Token { FixedToken(const std::string& str) : str_(str) {} virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int) { return str_; } std::string str_; }; struct FixedMapToken : public Token { FixedMapToken(const std::string& str) : str_(str) {} virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int) { M_string::iterator it = g_extra_fixed_tokens.find(str_); if (it == g_extra_fixed_tokens.end()) { return "${" + str_ + "}"; } return it->second; } std::string str_; }; struct PlaceHolderToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int) { return "PLACEHOLDER"; } }; struct SeverityToken : public Token { virtual std::string getString(void*, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { (void)str; (void)file; (void)function; (void)line; if (level == levels::Fatal) { return "FATAL"; } else if (level == levels::Error) { return "ERROR"; } else if (level == levels::Warn) { return " WARN"; } else if (level == levels::Info) { return " INFO"; } else if (level == levels::Debug) { return "DEBUG"; } return "UNKNO"; } }; struct MessageToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char* str, const char*, const char*, int) { return str; } }; struct TimeToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int) { std::stringstream ss; if (ros::Time::isValid() && ros::Time::isSimTime()) { ss << ros::WallTime::now() << ", " << ros::Time::now(); } else { ss << ros::WallTime::now(); } return ss.str(); } }; struct ThreadToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int) { std::stringstream ss; ss << boost::this_thread::get_id(); return ss.str(); } }; struct LoggerToken : public Token { virtual std::string getString(void* logger_handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { (void)level; (void)str; (void)file; (void)function; (void)line; return ::ros::console::impl::getName(logger_handle); } }; struct FileToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char*, const char* file, const char*, int) { return file; } }; struct FunctionToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char* function, int) { return function; } }; struct LineToken : public Token { virtual std::string getString(void*, ::ros::console::Level, const char*, const char*, const char*, int line) { std::stringstream ss; ss << line; return ss.str(); } }; TokenPtr createTokenFromType(const std::string& type) { if (type == "severity") { return TokenPtr(boost::make_shared<SeverityToken>()); } else if (type == "message") { return TokenPtr(boost::make_shared<MessageToken>()); } else if (type == "time") { return TokenPtr(boost::make_shared<TimeToken>()); } else if (type == "thread") { return TokenPtr(boost::make_shared<ThreadToken>()); } else if (type == "logger") { return TokenPtr(boost::make_shared<LoggerToken>()); } else if (type == "file") { return TokenPtr(boost::make_shared<FileToken>()); } else if (type == "line") { return TokenPtr(boost::make_shared<LineToken>()); } else if (type == "function") { return TokenPtr(boost::make_shared<FunctionToken>()); } return TokenPtr(boost::make_shared<FixedMapToken>(type)); } void Formatter::init(const char* fmt) { format_ = fmt; boost::regex e("\\$\\{([a-z|A-Z]+)\\}"); boost::match_results<std::string::const_iterator> results; std::string::const_iterator start, end; start = format_.begin(); end = format_.end(); bool matched_once = false; std::string last_suffix; while (boost::regex_search(start, end, results, e)) { #if 0 for (size_t i = 0; i < results.size(); ++i) { std::cout << i << "|" << results.prefix() << "|" << results[i] << "|" << results.suffix() << std::endl; } #endif std::string token = results[1]; last_suffix = results.suffix(); tokens_.push_back(TokenPtr(boost::make_shared<FixedToken>(results.prefix()))); tokens_.push_back(createTokenFromType(token)); start = results[0].second; matched_once = true; } if (matched_once) { tokens_.push_back(TokenPtr(boost::make_shared<FixedToken>(last_suffix))); } else { tokens_.push_back(TokenPtr(boost::make_shared<FixedToken>(format_))); } } void Formatter::print(void* logger_handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { const char* color = NULL; FILE* f = stdout; if (level == levels::Fatal) { color = COLOR_RED; f = stderr; } else if (level == levels::Error) { color = COLOR_RED; f = stderr; } else if (level == levels::Warn) { color = COLOR_YELLOW; } else if (level == levels::Info) { color = COLOR_NORMAL; } else if (level == levels::Debug) { color = COLOR_GREEN; } ROS_ASSERT(color != NULL); std::stringstream ss; ss << color; V_Token::iterator it = tokens_.begin(); V_Token::iterator end = tokens_.end(); for (; it != end; ++it) { ss << (*it)->getString(logger_handle, level, str, file, function, line); } ss << COLOR_NORMAL; fprintf(f, "%s\n", ss.str().c_str()); } Formatter g_formatter; void _print(void* logger_handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { g_formatter.print(logger_handle, level, str, file, function, line); } void initialize() { boost::mutex::scoped_lock lock(g_init_mutex); if (!g_initialized) { // Check for the format string environment variable char* format_string = NULL; #ifdef _MSC_VER _dupenv_s(&format_string, NULL, "ROSCONSOLE_FORMAT"); #else format_string = getenv("ROSCONSOLE_FORMAT"); #endif if (format_string) { g_format_string = format_string; } g_formatter.init(g_format_string); backend::function_notifyLoggerLevelsChanged = notifyLoggerLevelsChanged; backend::function_print = _print; ::ros::console::impl::initialize(); g_initialized = true; } } void vformatToBuffer(boost::shared_array<char>& buffer, size_t& buffer_size, const char* fmt, va_list args) { #ifdef _MSC_VER va_list arg_copy = args; // dangerous? #else va_list arg_copy; va_copy(arg_copy, args); #endif #ifdef _MSC_VER size_t total = vsnprintf_s(buffer.get(), buffer_size, buffer_size, fmt, args); #else size_t total = vsnprintf(buffer.get(), buffer_size, fmt, args); #endif if (total >= buffer_size) { buffer_size = total + 1; buffer.reset(new char[buffer_size]); #ifdef _MSC_VER vsnprintf_s(buffer.get(), buffer_size, buffer_size, fmt, arg_copy); #else vsnprintf(buffer.get(), buffer_size, fmt, arg_copy); #endif } va_end(arg_copy); } void formatToBuffer(boost::shared_array<char>& buffer, size_t& buffer_size, const char* fmt, ...) { va_list args; va_start(args, fmt); vformatToBuffer(buffer, buffer_size, fmt, args); va_end(args); } std::string formatToString(const char* fmt, ...) { boost::shared_array<char> buffer; size_t size = 0; va_list args; va_start(args, fmt); vformatToBuffer(buffer, size, fmt, args); va_end(args); return std::string(buffer.get(), size); } #define INITIAL_BUFFER_SIZE 4096 static boost::mutex g_print_mutex; static boost::shared_array<char> g_print_buffer(new char[INITIAL_BUFFER_SIZE]); static size_t g_print_buffer_size = INITIAL_BUFFER_SIZE; static boost::thread::id g_printing_thread_id; void print(FilterBase* filter, void* logger_handle, Level level, const char* file, int line, const char* function, const char* fmt, ...) { if (g_shutting_down) return; if (g_printing_thread_id == boost::this_thread::get_id()) { fprintf(stderr, "Warning: recursive print statement has occurred. Throwing out recursive print.\n"); return; } boost::mutex::scoped_lock lock(g_print_mutex); g_printing_thread_id = boost::this_thread::get_id(); va_list args; va_start(args, fmt); vformatToBuffer(g_print_buffer, g_print_buffer_size, fmt, args); va_end(args); bool enabled = true; if (filter) { FilterParams params; params.file = file; params.function = function; params.line = line; params.level = level; params.logger = logger_handle; params.message = g_print_buffer.get(); enabled = filter->isEnabled(params); level = params.level; if (!params.out_message.empty()) { size_t msg_size = params.out_message.size(); if (g_print_buffer_size <= msg_size) { g_print_buffer_size = msg_size + 1; g_print_buffer.reset(new char[g_print_buffer_size]); } memcpy(g_print_buffer.get(), params.out_message.c_str(), msg_size + 1); } } if (enabled) { if (level == levels::Error) { g_last_error_message = g_print_buffer.get(); } try { ::ros::console::impl::print(logger_handle, level, g_print_buffer.get(), file, function, line); } catch (std::exception& e) { fprintf(stderr, "Caught exception while logging: [%s]\n", e.what()); } } g_printing_thread_id = boost::thread::id(); } void print(FilterBase* filter, void* logger_handle, Level level, const std::stringstream& ss, const char* file, int line, const char* function) { if (g_shutting_down) return; if (g_printing_thread_id == boost::this_thread::get_id()) { fprintf(stderr, "Warning: recursive print statement has occurred. Throwing out recursive print.\n"); return; } boost::mutex::scoped_lock lock(g_print_mutex); g_printing_thread_id = boost::this_thread::get_id(); bool enabled = true; std::string str = ss.str(); if (filter) { FilterParams params; params.file = file; params.function = function; params.line = line; params.level = level; params.logger = logger_handle; params.message = g_print_buffer.get(); enabled = filter->isEnabled(params); level = params.level; if (!params.out_message.empty()) { str = params.out_message; } } if (enabled) { if (level == levels::Error) { g_last_error_message = str; } try { ::ros::console::impl::print(logger_handle, level, str.c_str(), file, function, line); } catch (std::exception& e) { fprintf(stderr, "Caught exception while logging: [%s]\n", e.what()); } } g_printing_thread_id = boost::thread::id(); } typedef std::vector<LogLocation*> V_LogLocation; V_LogLocation g_log_locations; boost::mutex g_locations_mutex; void registerLogLocation(LogLocation* loc) { boost::mutex::scoped_lock lock(g_locations_mutex); g_log_locations.push_back(loc); } void checkLogLocationEnabledNoLock(LogLocation* loc) { loc->logger_enabled_ = ::ros::console::impl::isEnabledFor(loc->logger_, loc->level_); } void initializeLogLocation(LogLocation* loc, const std::string& name, Level level) { boost::mutex::scoped_lock lock(g_locations_mutex); if (loc->initialized_) { return; } loc->logger_ = ::ros::console::impl::getHandle(name); loc->level_ = level; g_log_locations.push_back(loc); checkLogLocationEnabledNoLock(loc); loc->initialized_ = true; } void setLogLocationLevel(LogLocation* loc, Level level) { boost::mutex::scoped_lock lock(g_locations_mutex); loc->level_ = level; } void checkLogLocationEnabled(LogLocation* loc) { boost::mutex::scoped_lock lock(g_locations_mutex); checkLogLocationEnabledNoLock(loc); } void notifyLoggerLevelsChanged() { boost::mutex::scoped_lock lock(g_locations_mutex); V_LogLocation::iterator it = g_log_locations.begin(); V_LogLocation::iterator end = g_log_locations.end(); for ( ; it != end; ++it ) { LogLocation* loc = *it; checkLogLocationEnabledNoLock(loc); } } class StaticInit { public: StaticInit() { ROSCONSOLE_AUTOINIT; } }; StaticInit g_static_init; void register_appender(LogAppender* appender) { ros::console::impl::register_appender(appender); } void shutdown() { g_shutting_down = true; ros::console::impl::shutdown(); } bool get_loggers(std::map<std::string, levels::Level>& loggers) { return ros::console::impl::get_loggers(loggers); } bool set_logger_level(const std::string& name, levels::Level level) { return ros::console::impl::set_logger_level(name, level); } } // namespace console } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole/rosconsole_backend.cpp
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/console_backend.h" namespace ros { namespace console { namespace backend { void notifyLoggerLevelsChanged() { if (function_notifyLoggerLevelsChanged) { function_notifyLoggerLevelsChanged(); } } void (*function_notifyLoggerLevelsChanged)() = 0; void print(void* logger_handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { if (function_print) { function_print(logger_handle, level, str, file, function, line); } } void (*function_print)(void*, ::ros::console::Level, const char*, const char*, const char*, int) = 0; } // namespace backend } // namespace console } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole/impl/rosconsole_print.cpp
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "ros/console.h" namespace ros { namespace console { namespace impl { LogAppender* rosconsole_print_appender = 0; void initialize() {} void print(void* handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { ::ros::console::backend::print(0, level, str, file, function, line); if(rosconsole_print_appender) { rosconsole_print_appender->log(level, str, file, function, line); } } bool isEnabledFor(void* handle, ::ros::console::Level level) { return level != ::ros::console::levels::Debug; } void* getHandle(const std::string& name) { return 0; } std::string getName(void* handle) { return ""; } void register_appender(LogAppender* appender) { rosconsole_print_appender = appender; } void shutdown() {} bool get_loggers(std::map<std::string, levels::Level>& loggers) { return true; } bool set_logger_level(const std::string& name, levels::Level level) { return false; } } // namespace impl } // namespace console } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole/impl/rosconsole_glog.cpp
#include "ros/console.h" #include <glog/logging.h> namespace ros { namespace console { namespace impl { std::vector<std::pair<std::string, levels::Level> > rosconsole_glog_log_levels; LogAppender* rosconsole_glog_appender = 0; void initialize() { google::InitGoogleLogging("rosconsole"); } std::string getName(void* handle); void print(void* handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { // still printing to console ::ros::console::backend::print(0, level, str, file, function, line); // pass log message to appender if(rosconsole_glog_appender) { rosconsole_glog_appender->log(level, str, file, function, line); } google::LogSeverity glog_level; if(level == ::ros::console::levels::Info) { glog_level = google::GLOG_INFO; } else if(level == ::ros::console::levels::Warn) { glog_level = google::GLOG_WARNING; } else if(level == ::ros::console::levels::Error) { glog_level = google::GLOG_ERROR; } else if(level == ::ros::console::levels::Fatal) { glog_level = google::GLOG_FATAL; } else { // ignore debug return; } std::string name = getName(handle); google::LogMessage(file, line, glog_level).stream() << name << ": " << str; } bool isEnabledFor(void* handle, ::ros::console::Level level) { size_t index = (size_t)handle; if(index < rosconsole_glog_log_levels.size()) { return level >= rosconsole_glog_log_levels[index].second; } return false; } void* getHandle(const std::string& name) { size_t count = rosconsole_glog_log_levels.size(); for(size_t index = 0; index < count; index++) { if(name == rosconsole_glog_log_levels[index].first) { return (void*)index; } index++; } // add unknown names on demand with default level rosconsole_glog_log_levels.push_back(std::pair<std::string, levels::Level>(name, ::ros::console::levels::Info)); return (void*)(rosconsole_glog_log_levels.size() - 1); } std::string getName(void* handle) { size_t index = (size_t)handle; if(index < rosconsole_glog_log_levels.size()) { return rosconsole_glog_log_levels[index].first; } return ""; } void register_appender(LogAppender* appender) { rosconsole_glog_appender = appender; } void shutdown() {} bool get_loggers(std::map<std::string, levels::Level>& loggers) { for(std::vector<std::pair<std::string, levels::Level> >::const_iterator it = rosconsole_glog_log_levels.begin(); it != rosconsole_glog_log_levels.end(); it++) { loggers[it->first] = it->second; } return true; } bool set_logger_level(const std::string& name, levels::Level level) { for(std::vector<std::pair<std::string, levels::Level> >::iterator it = rosconsole_glog_log_levels.begin(); it != rosconsole_glog_log_levels.end(); it++) { if(name == it->first) { it->second = level; return true; } } return false; } } // namespace impl } // namespace console } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole
apollo_public_repos/apollo-platform/ros/ros_comm/rosconsole/src/rosconsole/impl/rosconsole_log4cxx.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // Author: Josh Faust #if defined(__APPLE__) && defined(__GNUC__) && defined(__llvm__) && !defined(__clang__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 2) #error This code is known to provoke a compiler crash with llvm-gcc 4.2. You will have better luck with clang++. See code.ros.org/trac/ros/ticket/3626 #endif #include "ros/console.h" #include "ros/assert.h" #include <ros/time.h> #include "log4cxx/appenderskeleton.h" #include "log4cxx/spi/loggingevent.h" #include "log4cxx/level.h" #include "log4cxx/propertyconfigurator.h" #ifdef _MSC_VER // Have to be able to encode wchar LogStrings on windows. #include "log4cxx/helpers/transcoder.h" #endif #include <boost/thread.hpp> #include <boost/shared_array.hpp> #include <boost/regex.hpp> #include <cstdarg> #include <cstdlib> #include <cstdio> #include <memory> #include <cstring> #include <stdexcept> namespace ros { namespace console { namespace impl { log4cxx::LevelPtr g_level_lookup[ levels::Count ] = { log4cxx::Level::getDebug(), log4cxx::Level::getInfo(), log4cxx::Level::getWarn(), log4cxx::Level::getError(), log4cxx::Level::getFatal(), }; class ROSConsoleStdioAppender : public log4cxx::AppenderSkeleton { public: ~ROSConsoleStdioAppender() { } protected: virtual void append(const log4cxx::spi::LoggingEventPtr& event, log4cxx::helpers::Pool&) { levels::Level level = levels::Count; if (event->getLevel() == log4cxx::Level::getDebug()) { level = levels::Debug; } else if (event->getLevel() == log4cxx::Level::getInfo()) { level = levels::Info; } else if (event->getLevel() == log4cxx::Level::getWarn()) { level = levels::Warn; } else if (event->getLevel() == log4cxx::Level::getError()) { level = levels::Error; } else if (event->getLevel() == log4cxx::Level::getFatal()) { level = levels::Fatal; } #ifdef _MSC_VER LOG4CXX_ENCODE_CHAR(tmpstr, event->getMessage()); // has to handle LogString with wchar types. std::string msg = tmpstr // tmpstr gets instantiated inside the LOG4CXX_ENCODE_CHAR macro #else std::string msg = event->getMessage(); #endif const log4cxx::spi::LocationInfo& location_info = event->getLocationInformation(); ::ros::console::backend::print(event.operator->(), level, msg.c_str(), location_info.getFileName(), location_info.getMethodName().c_str(), location_info.getLineNumber()); } virtual void close() { } virtual bool requiresLayout() const { return false; } }; void initialize() { // First set up some sane defaults programmatically. log4cxx::LoggerPtr ros_logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME); ros_logger->setLevel(log4cxx::Level::getInfo()); log4cxx::LoggerPtr roscpp_superdebug = log4cxx::Logger::getLogger("ros.roscpp.superdebug"); roscpp_superdebug->setLevel(log4cxx::Level::getWarn()); // Next try to load the default config file from ROS_ROOT/config/rosconsole.config char* ros_root_cstr = NULL; #ifdef _MSC_VER _dupenv_s(&ros_root_cstr, NULL, "ROS_ROOT"); #else ros_root_cstr = getenv("ROS_ROOT"); #endif if (ros_root_cstr) { std::string config_file = std::string(ros_root_cstr) + "/config/rosconsole.config"; FILE* config_file_ptr = fopen( config_file.c_str(), "r" ); if( config_file_ptr ) // only load it if the file exists, to avoid a warning message getting printed. { fclose( config_file_ptr ); log4cxx::PropertyConfigurator::configure(config_file); } } char* config_file_cstr = NULL; #ifdef _MSC_VER _dupenv_s(&config_file_cstr, NULL, "ROSCONSOLE_CONFIG_FILE"); #else config_file_cstr = getenv("ROSCONSOLE_CONFIG_FILE"); #endif if ( config_file_cstr ) { std::string config_file = config_file_cstr; log4cxx::PropertyConfigurator::configure(config_file); } log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME); logger->addAppender(new ROSConsoleStdioAppender); #ifdef _MSC_VER if ( ros_root_cstr != NULL ) { free(ros_root_cstr); } if ( config_file_cstr != NULL ) { free(config_file_cstr); } if ( format_string != NULL ) { free(format_string); } // getenv implementations don't need free'ing. #endif } void print(void* handle, ::ros::console::Level level, const char* str, const char* file, const char* function, int line) { log4cxx::Logger* logger = (log4cxx::Logger*)handle; try { logger->forcedLog(g_level_lookup[level], str, log4cxx::spi::LocationInfo(file, function, line)); } catch (std::exception& e) { fprintf(stderr, "Caught exception while logging: [%s]\n", e.what()); } } bool isEnabledFor(void* handle, ::ros::console::Level level) { log4cxx::Logger* logger = (log4cxx::Logger*)handle; return logger->isEnabledFor(g_level_lookup[level]); } void* getHandle(const std::string& name) { return log4cxx::Logger::getLogger(name); } std::string getName(void* handle) { const log4cxx::spi::LoggingEvent* event = (const log4cxx::spi::LoggingEvent*)handle; #ifdef _MSC_VER LOG4CXX_ENCODE_CHAR(tmpstr, event->getLoggerName()); // has to handle LogString with wchar types. return tmpstr // tmpstr gets instantiated inside the LOG4CXX_ENCODE_CHAR macro #else return event->getLoggerName(); #endif } bool get_loggers(std::map<std::string, levels::Level>& loggers) { log4cxx::spi::LoggerRepositoryPtr repo = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME)->getLoggerRepository(); log4cxx::LoggerList current_loggers = repo->getCurrentLoggers(); log4cxx::LoggerList::iterator it = current_loggers.begin(); log4cxx::LoggerList::iterator end = current_loggers.end(); for (; it != end; ++it) { std::string name; #ifdef _MSC_VER LOG4CXX_ENCODE_CHAR(name, (*it)->getName()); // has to handle LogString with wchar types. #else name = (*it)->getName(); #endif const log4cxx::LevelPtr& log4cxx_level = (*it)->getEffectiveLevel(); levels::Level level; if (log4cxx_level == log4cxx::Level::getDebug()) { level = levels::Debug; } else if (log4cxx_level == log4cxx::Level::getInfo()) { level = levels::Info; } else if (log4cxx_level == log4cxx::Level::getWarn()) { level = levels::Warn; } else if (log4cxx_level == log4cxx::Level::getError()) { level = levels::Error; } else if (log4cxx_level == log4cxx::Level::getFatal()) { level = levels::Fatal; } else { return false; } loggers[name] = level; } return true; } bool set_logger_level(const std::string& name, levels::Level level) { log4cxx::LevelPtr log4cxx_level; if (level == levels::Debug) { log4cxx_level = log4cxx::Level::getDebug(); } else if (level == levels::Info) { log4cxx_level = log4cxx::Level::getInfo(); } else if (level == levels::Warn) { log4cxx_level = log4cxx::Level::getWarn(); } else if (level == levels::Error) { log4cxx_level = log4cxx::Level::getError(); } else if (level == levels::Fatal) { log4cxx_level = log4cxx::Level::getFatal(); } else { return false; } log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(name); logger->setLevel(log4cxx_level); ::ros::console::backend::notifyLoggerLevelsChanged(); return true; } class Log4cxxAppender : public log4cxx::AppenderSkeleton { public: Log4cxxAppender(ros::console::LogAppender* appender) : appender_(appender) {} ~Log4cxxAppender() {} protected: virtual void append(const log4cxx::spi::LoggingEventPtr& event, log4cxx::helpers::Pool& pool) { (void)pool; levels::Level level; if (event->getLevel() == log4cxx::Level::getFatal()) { level = levels::Fatal; } else if (event->getLevel() == log4cxx::Level::getError()) { level = levels::Error; } else if (event->getLevel() == log4cxx::Level::getWarn()) { level = levels::Warn; } else if (event->getLevel() == log4cxx::Level::getInfo()) { level = levels::Info; } else if (event->getLevel() == log4cxx::Level::getDebug()) { level = levels::Debug; } else { return; } #ifdef _MSC_VER LOG4CXX_ENCODE_CHAR(tmpstr, event->getMessage()); // has to handle LogString with wchar types. std::string msg = tmpstr // tmpstr gets instantiated inside the LOG4CXX_ENCODE_CHAR macro #else std::string msg = event->getMessage(); #endif const log4cxx::spi::LocationInfo& info = event->getLocationInformation(); appender_->log(level, msg.c_str(), info.getFileName(), info.getMethodName().c_str(), info.getLineNumber()); } virtual void close() {} virtual bool requiresLayout() const { return false; } ros::console::LogAppender* appender_; }; Log4cxxAppender* g_log4cxx_appender; void register_appender(LogAppender* appender) { g_log4cxx_appender = new Log4cxxAppender(appender); const log4cxx::LoggerPtr& logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME); logger->addAppender(g_log4cxx_appender); } void shutdown() { const log4cxx::LoggerPtr& logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME); logger->removeAppender(g_log4cxx_appender); g_log4cxx_appender = 0; // reset this so that the logger doesn't get crashily destroyed // again during global destruction. // // See https://code.ros.org/trac/ros/ticket/3271 // log4cxx::Logger::getRootLogger()->getLoggerRepository()->shutdown(); } } // namespace impl } // namespace console } // namespace ros
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(rostest) find_package(catkin COMPONENTS rosunit) find_package(Boost COMPONENTS system thread) include_directories(include ${Boost_INCLUDE_DIRS}) catkin_package(DEPENDS Boost INCLUDE_DIRS include CFG_EXTRAS ${PROJECT_NAME}-extras.cmake ) catkin_python_setup() catkin_install_python(PROGRAMS nodes/hztest DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/nodes/hztest) install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.h") if(CATKIN_ENABLE_TESTING) find_package(catkin COMPONENTS rostest) catkin_add_gtest(test_permuter test/test_permuter.cpp) if(TARGET test_permuter) target_link_libraries(test_permuter ${Boost_LIBRARIES}) endif() add_rostest(test/hztest0.test) add_rostest(test/hztest.test) add_rostest(test/clean_master.test) add_rostest(test/distro_version.test) endif()
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/package.xml
<package> <name>rostest</name> <version>1.11.21</version> <description> Integration test suite based on roslaunch that is compatible with xUnit frameworks. </description> <maintainer email="dthomas@osrfoundation.org">Dirk Thomas</maintainer> <license>BSD</license> <url>http://ros.org/wiki/rostest</url> <author>Ken Conley</author> <buildtool_depend version_gte="0.5.78">catkin</buildtool_depend> <build_depend>boost</build_depend> <build_depend>rosunit</build_depend> <run_depend>boost</run_depend> <run_depend>rosgraph</run_depend> <run_depend>roslaunch</run_depend> <run_depend>rosmaster</run_depend> <run_depend>rospy</run_depend> <run_depend>rosunit</run_depend> <export> <rosdoc config="rosdoc.yaml"/> <architecture_independent/> </export> </package>
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/rosdoc.yaml
- builder: epydoc config: epydoc.config
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/setup.py
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rostest'], package_dir={'': 'src'}, scripts=['scripts/rostest'], requires=['rospkg', 'genmsg', 'genpy', 'roslib', 'rospy'] ) setup(**d)
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/.tar
{!!python/unicode 'url': 'https://github.com/ros-gbp/ros_comm-release/archive/release/indigo/rostest/1.11.21-0.tar.gz', !!python/unicode 'version': ros_comm-release-release-indigo-rostest-1.11.21-0}
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package rostest ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1.11.21 (2017-03-06) -------------------- * fix test type handling (`#722 <https://github.com/ros/ros_comm/issues/722>`_) * add_rostest_gtest does now add the created gtest-target as a dependeny to the created rostest (`#830 <https://github.com/ros/ros_comm/pull/830>`_) 1.11.20 (2016-06-27) -------------------- 1.11.19 (2016-04-18) -------------------- * fix passing multiple args to add_rostest (fix `#790 <https://github.com/ros/ros_comm/issues/790>`_) 1.11.18 (2016-03-17) -------------------- 1.11.17 (2016-03-11) -------------------- * rostest.rosrun now generates coverage reports (`#558 <https://github.com/ros/ros_comm/issues/558>`_) * rostest can load tests from a dotted name (`#722 <https://github.com/ros/ros_comm/issues/722>`_) * include GTEST_INCLUDE_DIRS so that the proper gtest headers are found (`#727 <https://github.com/ros/ros_comm/issues/727>`_) * rostest: move replacement of slashes after ARGS handling (`#721 <https://github.com/ros/ros_comm/pull/721>`_) 1.11.16 (2015-11-09) -------------------- 1.11.15 (2015-10-13) -------------------- 1.11.14 (2015-09-19) -------------------- * add --local option to rostest (`#137 <https://github.com/ros/ros_comm/issues/137>`_) * fix location of rosunit result files generated by rostests (`#668 <https://github.com/ros/ros_comm/pull/668>`_) 1.11.13 (2015-04-28) -------------------- * fix location of rostest result files (`#611 <https://github.com/ros/ros_comm/issues/611>`_) 1.11.12 (2015-04-27) -------------------- * fix location of rostest result files (`#82 <https://github.com/ros/ros/pull/82>`_) 1.11.11 (2015-04-16) -------------------- * add DEPENDENCIES option to CMake function add_rostest (`#546 <https://github.com/ros/ros_comm/issues/546>`_) 1.11.10 (2014-12-22) -------------------- 1.11.9 (2014-08-18) ------------------- 1.11.8 (2014-08-04) ------------------- 1.11.7 (2014-07-18) ------------------- * make rostest use a random master port and run rostests in parallel (`#468 <https://github.com/ros/ros_comm/issues/468>`_) 1.11.6 (2014-07-10) ------------------- * resolving naming conflicts when multiple test are added with arguments (`#462 <https://github.com/ros/ros_comm/issues/462>`_) 1.11.5 (2014-06-24) ------------------- 1.11.4 (2014-06-16) ------------------- * Python 3 compatibility (`#426 <https://github.com/ros/ros_comm/issues/426>`_) 1.11.3 (2014-05-21) ------------------- 1.11.2 (2014-05-08) ------------------- 1.11.1 (2014-05-07) ------------------- * add architecture_independent flag in package.xml (`#391 <https://github.com/ros/ros_comm/issues/391>`_) 1.11.0 (2014-03-04) ------------------- * use catkin_install_python() to install Python scripts (`#361 <https://github.com/ros/ros_comm/issues/361>`_) 1.10.0 (2014-02-11) ------------------- * modify rostest to wait when other instances are running 1.9.54 (2014-01-27) ------------------- 1.9.53 (2014-01-14) ------------------- 1.9.52 (2014-01-08) ------------------- 1.9.51 (2014-01-07) ------------------- * add missing boost component 1.9.50 (2013-10-04) ------------------- * fix result file naming for wet rostests when being built in-source (`ros/catkin#512 <https://github.com/ros/catkin/issues/512>`_) 1.9.49 (2013-09-16) ------------------- 1.9.48 (2013-08-21) ------------------- * add convenience function for rostest with gtests (`#258 <https://github.com/ros/ros_comm/issues/258>`_) * make rostest relocatable (`ros/catkin#490 <https://github.com/ros/catkin/issues/490>`_) 1.9.47 (2013-07-03) ------------------- * update 'rostest' to support CATKIN_ENABLE_TESTING * check for CATKIN_ENABLE_TESTING to enable configure without tests 1.9.46 (2013-06-18) ------------------- 1.9.45 (2013-06-06) ------------------- * allow passing arguments to add_rostest(ARGS ...) (`#232 <https://github.com/ros/ros_comm/issues/232>`_) 1.9.44 (2013-03-21) ------------------- 1.9.43 (2013-03-13) ------------------- 1.9.42 (2013-03-08) ------------------- 1.9.41 (2013-01-24) ------------------- 1.9.40 (2013-01-13) ------------------- 1.9.39 (2012-12-29) ------------------- * first public release for Groovy
0
apollo_public_repos/apollo-platform/ros/ros_comm
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/epydoc.config
[epydoc] name: rostest modules: rostest inheritance: included url: http://ros.org/wiki/rostest frames: no private: no
0
apollo_public_repos/apollo-platform/ros/ros_comm/rostest
apollo_public_repos/apollo-platform/ros/ros_comm/rostest/test/clean_master.test
<launch> <test pkg="rostest" type="test_clean_master.py" test-name="clean_master1" /> <test pkg="rostest" type="test_clean_master.py" test-name="clean_master2" /> <test pkg="rostest" type="test_clean_master.py" test-name="clean_master3" /> </launch>
0